|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Tempest\Cryptography\Encryption; |
| 4 | + |
| 5 | +use Stringable; |
| 6 | +use Tempest\Cryptography\Encryption\Exceptions\EncryptedDataWasInvalid; |
| 7 | +use Tempest\Cryptography\Signing\Signature; |
| 8 | +use Tempest\Support\Json; |
| 9 | + |
| 10 | +final readonly class EncryptedData implements Stringable |
| 11 | +{ |
| 12 | + public function __construct( |
| 13 | + private(set) string $payload, |
| 14 | + private(set) string $iv, |
| 15 | + private(set) string $tag, |
| 16 | + private(set) Signature $signature, |
| 17 | + private(set) EncryptionAlgorithm $algorithm, |
| 18 | + ) {} |
| 19 | + |
| 20 | + public function serialize(): string |
| 21 | + { |
| 22 | + $data = [ |
| 23 | + 'payload' => base64_encode($this->payload), |
| 24 | + 'iv' => base64_encode($this->iv), |
| 25 | + 'tag' => base64_encode($this->tag), |
| 26 | + 'signature' => $this->signature->value, |
| 27 | + 'algorithm' => $this->algorithm->value, |
| 28 | + ]; |
| 29 | + |
| 30 | + return base64_encode(Json\encode($data)); |
| 31 | + } |
| 32 | + |
| 33 | + public static function unserialize(string $data): self |
| 34 | + { |
| 35 | + $decoded = Json\decode(base64_decode($data, strict: true)); |
| 36 | + |
| 37 | + if (! is_array($decoded) || ! isset($decoded['payload'], $decoded['iv'], $decoded['tag'], $decoded['signature'], $decoded['algorithm'])) { |
| 38 | + throw EncryptedDataWasInvalid::dueToInvalidFormat(); |
| 39 | + } |
| 40 | + |
| 41 | + return new self( |
| 42 | + payload: base64_decode($decoded['payload'], strict: true), |
| 43 | + iv: base64_decode($decoded['iv'], strict: true), |
| 44 | + tag: base64_decode($decoded['tag'], strict: true), |
| 45 | + signature: new Signature($decoded['signature']), |
| 46 | + algorithm: EncryptionAlgorithm::from($decoded['algorithm']), |
| 47 | + ); |
| 48 | + } |
| 49 | + |
| 50 | + public function __toString(): string |
| 51 | + { |
| 52 | + return $this->serialize(); |
| 53 | + } |
| 54 | +} |
0 commit comments