From 1643eab60f1092f8d518dde13f8c09bfb5987430 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Sat, 7 Nov 2026 15:51:46 +0100 Subject: [PATCH 01/32] add first version of streamed encryption --- composer.json | 3 +- src/.gitkeep | 0 src/Encrypt.php | 94 +++++++++++++++++++++++++++++++++++++++++++++++++ src/Tag.php | 80 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 176 insertions(+), 1 deletion(-) delete mode 100644 src/.gitkeep create mode 100644 src/Encrypt.php create mode 100644 src/Tag.php diff --git a/composer.json b/composer.json index f3a0028..db4d140 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,8 @@ "issues": "http://github.com/innmind/encryption/issues" }, "require": { - "php": "~8.5" + "php": "~8.5", + "innmind/immutable": "~6.3" }, "autoload": { "psr-4": { diff --git a/src/.gitkeep b/src/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/Encrypt.php b/src/Encrypt.php new file mode 100644 index 0000000..a306595 --- /dev/null +++ b/src/Encrypt.php @@ -0,0 +1,94 @@ + $chunks + * + * @return Sequence + */ + public function __invoke(Sequence $chunks): Sequence + { + $password = $this->password; + + return Sequence::lazy(static function() use ($chunks, $password) { + $salt = \random_bytes(\SODIUM_CRYPTO_PWHASH_SALTBYTES); + $key = \sodium_crypto_pwhash( + \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, + $password, + $salt, + \SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE, + \SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE, + \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, + ); + $kdfHeader = \sprintf( + 'PWE1%s%s', + $salt, + \pack( + 'PP', + \SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE, + \SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE, + ), + ); + + /** + * @var string $header + */ + [$state, $header] = \sodium_crypto_secretstream_xchacha20poly1305_init_push($key); + \sodium_memzero($key); + + yield Sequence::of($kdfHeader, $header); + + yield $chunks + ->map(static fn($chunk) => $chunk->toEncoding(Str\Encoding::ascii)) + ->aggregate( + static fn(Str $a, Str $b) => $a + ->append($b) + ->chunk(8192), + ) + ->map(static fn($chunk) => $chunk->toString()) + ->map(Tag::of(...)) + ->aggregate(static fn(Tag $a, Tag $b) => $a->and($b)) + ->map( + static function($value) use (&$state, $kdfHeader) { + return \sodium_crypto_secretstream_xchacha20poly1305_push( + $state, + $value->unwrap(), + match ($value->first()) { + true => $kdfHeader, + false => '', + }, + match ($value->last()) { + true => \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL, + false => \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_MESSAGE, + }, + ); + }, + ); + + \sodium_memzero($state); + }) + ->flatMap(static fn($chunks) => $chunks) + ->map(Str::of(...)) + ->map(static fn($chunk) => $chunk->toEncoding(Str\Encoding::ascii)); + } + + public static function of(#[\SensitiveParameter] string $password): self + { + return new self($password); + } +} diff --git a/src/Tag.php b/src/Tag.php new file mode 100644 index 0000000..497d234 --- /dev/null +++ b/src/Tag.php @@ -0,0 +1,80 @@ + + */ + public static function of(mixed $value): self + { + return new self($value, true, true); + } + + public function and(self $next): Sequence + { + if ($this->first && $this->last) { + return Sequence::of( + new self( + $this->value, + true, + false, + ), + new self( + $next->value, + false, + true, + ), + ); + } + + return Sequence::of( + new self( + $this->value, + $this->first, + false, + ), + new self( + $next->value, + false, + true, + ), + ); + } + + public function first(): bool + { + return $this->first; + } + + public function last(): bool + { + return $this->last; + } + + public function unwrap(): mixed + { + return $this->value; + } +} From 10a61e752bf8a5246441a3cd3b5b9e1744dddc31 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Sun, 8 Nov 2026 17:19:50 +0100 Subject: [PATCH 02/32] use sequence position instead of own tag --- composer.json | 2 +- src/Encrypt.php | 3 +- src/Tag.php | 80 ------------------------------------------------- 3 files changed, 2 insertions(+), 83 deletions(-) delete mode 100644 src/Tag.php diff --git a/composer.json b/composer.json index db4d140..d1f2cd4 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,7 @@ }, "require": { "php": "~8.5", - "innmind/immutable": "~6.3" + "innmind/immutable": "~6.4" }, "autoload": { "psr-4": { diff --git a/src/Encrypt.php b/src/Encrypt.php index a306595..b7d9acb 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -61,8 +61,7 @@ public function __invoke(Sequence $chunks): Sequence ->chunk(8192), ) ->map(static fn($chunk) => $chunk->toString()) - ->map(Tag::of(...)) - ->aggregate(static fn(Tag $a, Tag $b) => $a->and($b)) + ->via(Sequence\Position::tag(...)) ->map( static function($value) use (&$state, $kdfHeader) { return \sodium_crypto_secretstream_xchacha20poly1305_push( diff --git a/src/Tag.php b/src/Tag.php deleted file mode 100644 index 497d234..0000000 --- a/src/Tag.php +++ /dev/null @@ -1,80 +0,0 @@ - - */ - public static function of(mixed $value): self - { - return new self($value, true, true); - } - - public function and(self $next): Sequence - { - if ($this->first && $this->last) { - return Sequence::of( - new self( - $this->value, - true, - false, - ), - new self( - $next->value, - false, - true, - ), - ); - } - - return Sequence::of( - new self( - $this->value, - $this->first, - false, - ), - new self( - $next->value, - false, - true, - ), - ); - } - - public function first(): bool - { - return $this->first; - } - - public function last(): bool - { - return $this->last; - } - - public function unwrap(): mixed - { - return $this->value; - } -} From 7f35ec1db2451056c1d72d4d3e262cb6eef64544 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Sun, 8 Nov 2026 17:20:25 +0100 Subject: [PATCH 03/32] zero out the salt --- src/Encrypt.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Encrypt.php b/src/Encrypt.php index b7d9acb..3fc9d7d 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -44,6 +44,7 @@ public function __invoke(Sequence $chunks): Sequence \SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE, ), ); + \sodium_memzero($salt); /** * @var string $header From da0840beb72a6f37db81d55f7b0f896e7e789557 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 14:26:04 +0100 Subject: [PATCH 04/32] discard error --- src/Encrypt.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Encrypt.php b/src/Encrypt.php index 3fc9d7d..a5cf816 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -80,6 +80,7 @@ static function($value) use (&$state, $kdfHeader) { }, ); + /** @psalm-suppress MixedArgument */ \sodium_memzero($state); }) ->flatMap(static fn($chunks) => $chunks) From 2635006160032ef91b26db0ce8d62d939e852c85 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 15:13:23 +0100 Subject: [PATCH 05/32] add streamed decryption --- composer.json | 3 +- src/Decrypt.php | 142 +++++++++++++++++++++++++++++++++++++++++ src/Decrypt/Chunk.php | 49 ++++++++++++++ src/Decrypt/Header.php | 33 ++++++++++ src/Decrypt/Plain.php | 36 +++++++++++ src/Decrypt/Pull.php | 61 ++++++++++++++++++ 6 files changed, 323 insertions(+), 1 deletion(-) create mode 100644 src/Decrypt.php create mode 100644 src/Decrypt/Chunk.php create mode 100644 src/Decrypt/Header.php create mode 100644 src/Decrypt/Plain.php create mode 100644 src/Decrypt/Pull.php diff --git a/composer.json b/composer.json index d1f2cd4..77c0f0c 100644 --- a/composer.json +++ b/composer.json @@ -16,7 +16,8 @@ }, "require": { "php": "~8.5", - "innmind/immutable": "~6.4" + "innmind/immutable": "~6.4", + "innmind/frame": "^1.0.1" }, "autoload": { "psr-4": { diff --git a/src/Decrypt.php b/src/Decrypt.php new file mode 100644 index 0000000..ec50395 --- /dev/null +++ b/src/Decrypt.php @@ -0,0 +1,142 @@ + */ + private Frame $decode; + + private function __construct( + #[\SensitiveParameter] string $password, + ) { + $this->decode = Frame::chunk(4) + ->map(static fn($magic) => match ($magic->toString()) { + 'PWE1' => $magic, + default => throw new \RuntimeException('Invalid encrypted file'), + }) + ->flatMap( + static fn($magic) => Frame::chunk(\SODIUM_CRYPTO_PWHASH_SALTBYTES)->map( + static fn($salt) => [$magic, $salt], + ), + ) + ->flatMap( + static fn($pair) => Frame::chunk(16)->map(static function($limits) use ($pair) { + /** + * @var int $ops + * @var int $mem + * @psalm-suppress PossiblyInvalidArrayAccess + */ + ['ops' => $ops, 'mem' => $mem] = \unpack('Pops/Pmem', $limits->toString()); + + if ( + $ops < \SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE || + $ops > \SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE || + $mem < \SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE || + $mem > \SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE + ) { + throw new \RuntimeException('Invalid derivation key parameters'); + } + + return [ + $pair[0]->toString().$pair[1]->toString().$limits->toString(), + $pair[1]->toString(), + $ops, + $mem, + ]; + }), + ) + ->map(static function($tuple) use ($password) { + [$kdfHeader, $salt, $ops, $mem] = $tuple; + $key = \sodium_crypto_pwhash( + \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, + $password, + $salt, + $ops, + $mem, + \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, + ); + + return [ + $kdfHeader, + $key, + ]; + }); + } + + /** + * @param Sequence $chunks + * + * @return Sequence + */ + public function __invoke(Sequence $chunks): Sequence + { + $decode = $this->decode; + + return Sequence::lazy(static function() use ($decode, $chunks) { + $state = ''; + $decode = $decode + ->flatMap( + static function($pair) use (&$state) { + return Frame::chunk(\SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES)->map( + static function($header) use (&$pair, &$state) { + $state = \sodium_crypto_secretstream_xchacha20poly1305_init_pull( + $header->toString(), + $pair[1], + ); + \sodium_memzero($pair[1]); + + return $pair[0]; + }, + ); + }, + ) + ->map(Str::of(...)) + ->map(Decrypt\Header::of(...)) + ->passthrough(); + + /** @psalm-suppress MixedArgumentTypeCoercion */ + yield $chunks + ->via($decode) + ->aggregate(static fn(Decrypt\Header|Str $a, Str $b) => match (true) { + $a instanceof Decrypt\Header => Sequence::of($a, $b), + $a->length() === self::CHUNK => Sequence::of($a, $b), + default => Sequence::of($a->append($b)), + }) + ->map(Decrypt\Chunk::of(...)) + ->aggregate(static fn(Decrypt\Chunk|Decrypt\Pull $a, Decrypt\Chunk $b) => $a->and($b)) + ->keep(Instance::of(Decrypt\Pull::class)) + ->map(static function($pull) use (&$state) { + [$plain, $state] = $pull($state); + + return $plain; + }) + ->via(Sequence\Position::tag(...)) + ->map( + static fn($value) => $value + ->unwrap() + ->validate($value->position()), + ); + + \sodium_memzero($state); + }) + ->flatMap(static fn($chunks) => $chunks) + ->map(static fn($chunk) => $chunk->toEncoding(Str\Encoding::ascii)); + } + + public static function of(#[\SensitiveParameter] string $password): self + { + return new self($password); + } +} diff --git a/src/Decrypt/Chunk.php b/src/Decrypt/Chunk.php new file mode 100644 index 0000000..03adb01 --- /dev/null +++ b/src/Decrypt/Chunk.php @@ -0,0 +1,49 @@ + + */ + public function and(self $next): Sequence + { + if ($next->value instanceof Header) { + throw new \LogicException('The header should be the first value only'); + } + + if ($this->value instanceof Header) { + return Sequence::of(Pull::first($next->value, $this->value->unwrap())); + } + + return Sequence::of( + Pull::middle($this->value), + Pull::middle($next->value), + ); + } + + public function pull(): Pull + { + if ($this->value instanceof Header) { + throw new \LogicException; + } + + return Pull::middle($this->value); + } +} diff --git a/src/Decrypt/Header.php b/src/Decrypt/Header.php new file mode 100644 index 0000000..dae2d22 --- /dev/null +++ b/src/Decrypt/Header.php @@ -0,0 +1,33 @@ +value; + } +} diff --git a/src/Decrypt/Plain.php b/src/Decrypt/Plain.php new file mode 100644 index 0000000..969a8c8 --- /dev/null +++ b/src/Decrypt/Plain.php @@ -0,0 +1,36 @@ +last() && !$this->last) { + throw new \RuntimeException('Truncated file'); + } + + return $this->value; + } +} diff --git a/src/Decrypt/Pull.php b/src/Decrypt/Pull.php new file mode 100644 index 0000000..fd2af0c --- /dev/null +++ b/src/Decrypt/Pull.php @@ -0,0 +1,61 @@ +cipher->toString(), + $this->ad->toString(), + ); + + if ($result === false) { + throw new \RuntimeException('Wrong password or corrupted file'); + } + + [$plain, $tag] = $result; + + /** @psalm-suppress MixedArgument */ + $plain = match ($tag) { + \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL => Plain::last(Str::of($plain)), + default => Plain::middle(Str::of($plain)), + }; + + return [$plain, $state]; + } + + public static function first(Str $cipher, Str $kdfHeader): self + { + return new self($cipher, $kdfHeader); + } + + public static function middle(Str $cipher): self + { + return new self($cipher, Str::of('')); + } + + /** + * @return Sequence + */ + public function and(Chunk $next): Sequence + { + return Sequence::of($this, $next->pull()); + } +} From 90ea9c5705a0cbac63ec5dd94786a0a831407236 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 15:19:34 +0100 Subject: [PATCH 06/32] prove encryption/decryption identity --- proofs/.gitkeep | 0 proofs/encryption.php | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) delete mode 100644 proofs/.gitkeep create mode 100644 proofs/encryption.php diff --git a/proofs/.gitkeep b/proofs/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/proofs/encryption.php b/proofs/encryption.php new file mode 100644 index 0000000..429772e --- /dev/null +++ b/proofs/encryption.php @@ -0,0 +1,42 @@ +proof('Encryption/decryption identity') + ->given( + Set::sequence( + Set::strings(), + ), + Set::strings()->between(1, 4096), + ) + ->test(static function($assert, $chunks, $password) { + $encrypt = Encrypt::of($password); + $decrypt = Decrypt::of($password); + + $assert->same( + \implode('', $chunks), + Sequence::of(...$chunks) + ->map(Str::of(...)) + ->via($encrypt) + ->via($decrypt) + ->fold(Concat::monoid) + ->toString(), + ); + }); +}; From 5c3facaa2bfe5bb083bc861c257c790177f94cbc Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 15:34:59 +0100 Subject: [PATCH 07/32] prove the plain content does not appear in the encrypted version --- proofs/encryption.php | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/proofs/encryption.php b/proofs/encryption.php index 429772e..2618726 100644 --- a/proofs/encryption.php +++ b/proofs/encryption.php @@ -14,6 +14,7 @@ use Innmind\BlackBox\{ Set, Prove, + Runner\Assert, }; return static function(Prove $prove) { @@ -25,7 +26,7 @@ ), Set::strings()->between(1, 4096), ) - ->test(static function($assert, $chunks, $password) { + ->test(static function(Assert $assert, $chunks, $password) { $encrypt = Encrypt::of($password); $decrypt = Decrypt::of($password); @@ -39,4 +40,35 @@ ->toString(), ); }); + + yield $prove + ->proof('Encryption does not expose chunks in plain text') + ->given( + Set::sequence( + Set::strings()->atLeast(3), // statistically probable that a short chunk can be found as an encrypted value + ), + Set::strings()->between(1, 4096), + ) + ->test(static function(Assert $assert, $chunks, $password) { + $encrypt = Encrypt::of($password); + + $encrypted = Sequence::of(...$chunks) + ->map(Str::of(...)) + ->via($encrypt) + ->fold(Concat::monoid) + ->toString(); + + $assert + ->string($encrypted) + ->not() + ->empty(); + + foreach ($chunks as $chunk) { + $assert + ->string($encrypted) + ->not() + ->contains($chunk) + ->contains(\strrev($chunk)); + } + }); }; From 4e91ff967b2f6e2524f12a9fa230602a759ac374 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 15:42:41 +0100 Subject: [PATCH 08/32] fix blackbox configuration --- blackbox.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/blackbox.php b/blackbox.php index 6e714d7..2b7a84f 100644 --- a/blackbox.php +++ b/blackbox.php @@ -19,8 +19,7 @@ __DIR__.'/src/', __DIR__.'/proofs/', ) - ->dumpTo('coverage.clover') - ->enableWhen(true), + ->dumpTo('coverage.clover'), ), default => $app, }) From d6a4293273812495144f29e0cf5f617730b911f6 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 15:48:33 +0100 Subject: [PATCH 09/32] reduce probability that a short chunk may appear in the encrypted file --- proofs/encryption.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/proofs/encryption.php b/proofs/encryption.php index 2618726..f788657 100644 --- a/proofs/encryption.php +++ b/proofs/encryption.php @@ -45,7 +45,7 @@ ->proof('Encryption does not expose chunks in plain text') ->given( Set::sequence( - Set::strings()->atLeast(3), // statistically probable that a short chunk can be found as an encrypted value + Set::strings()->atLeast(4), // statistically probable that a short chunk can be found as an encrypted value ), Set::strings()->between(1, 4096), ) From d5fab8fffc69c8ceb55528e7bfaceef1dba1da7c Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 15:57:26 +0100 Subject: [PATCH 10/32] make sure there is always at least one chunk to encrypt --- src/Encrypt.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Encrypt.php b/src/Encrypt.php index a5cf816..c0654cb 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -55,6 +55,7 @@ public function __invoke(Sequence $chunks): Sequence yield Sequence::of($kdfHeader, $header); yield $chunks + ->add(Str::of('')) // to make sure there is always at least one chunk ->map(static fn($chunk) => $chunk->toEncoding(Str\Encoding::ascii)) ->aggregate( static fn(Str $a, Str $b) => $a From 95a4ac94e89c2ef4efc4965150037bd760b1cda7 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 16:02:43 +0100 Subject: [PATCH 11/32] make sure no one big chunk can go undecrypted --- src/Decrypt.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Decrypt.php b/src/Decrypt.php index ec50395..823cf05 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -109,10 +109,13 @@ static function($header) use (&$pair, &$state) { /** @psalm-suppress MixedArgumentTypeCoercion */ yield $chunks ->via($decode) + ->flatMap(static fn($chunk) => match (true) { + $chunk instanceof Decrypt\Header => Sequence::of($chunk), + default => $chunk->chunk(self::CHUNK), + }) ->aggregate(static fn(Decrypt\Header|Str $a, Str $b) => match (true) { $a instanceof Decrypt\Header => Sequence::of($a, $b), - $a->length() === self::CHUNK => Sequence::of($a, $b), - default => Sequence::of($a->append($b)), + default => $a->append($b)->chunk(self::CHUNK), }) ->map(Decrypt\Chunk::of(...)) ->aggregate(static fn(Decrypt\Chunk|Decrypt\Pull $a, Decrypt\Chunk $b) => $a->and($b)) From 4275a696cb6eceff7817354e76203700656f0912 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 16:10:16 +0100 Subject: [PATCH 12/32] fail when the last encrypted chunk is not the last one in the sequence --- src/Decrypt/Plain.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Decrypt/Plain.php b/src/Decrypt/Plain.php index 969a8c8..a64fa4e 100644 --- a/src/Decrypt/Plain.php +++ b/src/Decrypt/Plain.php @@ -27,7 +27,10 @@ public static function middle(Str $value): self public function validate(Position $position): Str { - if ($position->last() && !$this->last) { + if ( + ($position->last() && !$this->last) || + ($this->last && !$position->last()) + ) { throw new \RuntimeException('Truncated file'); } From 8769d1ae30defc7a1fd1dce735ed73eba226e778 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 16:27:21 +0100 Subject: [PATCH 13/32] exclude empty chunks from encryption --- src/Encrypt.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Encrypt.php b/src/Encrypt.php index c0654cb..e76f7b3 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -55,6 +55,7 @@ public function __invoke(Sequence $chunks): Sequence yield Sequence::of($kdfHeader, $header); yield $chunks + ->filter(static fn($chunk) => !$chunk->empty()) ->add(Str::of('')) // to make sure there is always at least one chunk ->map(static fn($chunk) => $chunk->toEncoding(Str\Encoding::ascii)) ->aggregate( From 1324655e1008497f0812b5e7f10edf8a4a65dd80 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 16:55:21 +0100 Subject: [PATCH 14/32] make sure truncated files fail decryption --- proofs/encryption.php | 40 ++++++++++++++++++++++++++++++++++++++++ src/Decrypt.php | 3 +-- src/Decrypt/Chunk.php | 29 ++++++++++++++++++++++++++--- 3 files changed, 67 insertions(+), 5 deletions(-) diff --git a/proofs/encryption.php b/proofs/encryption.php index f788657..e8f465c 100644 --- a/proofs/encryption.php +++ b/proofs/encryption.php @@ -71,4 +71,44 @@ ->contains(\strrev($chunk)); } }); + + yield $prove + ->proof('Decryption of truncated file fails') + ->given( + Set::strings() + ->between(1, 4096) + ->flatMap( + static fn($password) => Set::sequence(Set::strings()) + ->map(static fn($chunks) => Sequence::of(...$chunks)->map(Str::of(...))) + ->map(Encrypt::of($password->unwrap())) + ->flatMap( + static fn($encrypted) => Set::integers() + ->between( + 0, + $encrypted + ->unwrap() + ->fold(Concat::monoid) + ->toEncoding(Str\Encoding::ascii) + ->length(), + ) + ->map(static fn($truntaed) => [ + $encrypted->unwrap(), + $password->unwrap(), + $truntaed, + ]), + ), + ), + ) + ->test(static function(Assert $assert, $config) { + [$encrypted, $password, $truncated] = $config; + + $assert->throws( + static fn() => $encrypted + ->flatMap(static fn($chunk) => $chunk->chunk()) + ->take($truncated) + ->via(Decrypt::of($password)) + ->fold(Concat::monoid) + ->toString(), + ); + }); }; diff --git a/src/Decrypt.php b/src/Decrypt.php index 823cf05..ff7afdb 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -9,7 +9,6 @@ Sequence, Str, }; -use Innmind\Immutable\Predicate\Instance; final class Decrypt { @@ -118,8 +117,8 @@ static function($header) use (&$pair, &$state) { default => $a->append($b)->chunk(self::CHUNK), }) ->map(Decrypt\Chunk::of(...)) + ->prepend(Sequence::of(Decrypt\Chunk::none())) ->aggregate(static fn(Decrypt\Chunk|Decrypt\Pull $a, Decrypt\Chunk $b) => $a->and($b)) - ->keep(Instance::of(Decrypt\Pull::class)) ->map(static function($pull) use (&$state) { [$plain, $state] = $pull($state); diff --git a/src/Decrypt/Chunk.php b/src/Decrypt/Chunk.php index 03adb01..dea2285 100644 --- a/src/Decrypt/Chunk.php +++ b/src/Decrypt/Chunk.php @@ -10,20 +10,43 @@ final class Chunk { private function __construct( - private Header|Str $value, + private Header|Str|null $value, ) { } + /** + * @return array{Plain, string} + */ + public function __invoke(string $state): array + { + // the argument and return type is only here for psalm for the + // compatibility with Pull::__invoke() + throw new \RuntimeException('Truncated file'); + } + public static function of(Header|Str $value): self { return new self($value); } + public static function none(): self + { + return new self(null); + } + /** - * @return Sequence + * @return Sequence */ public function and(self $next): Sequence { + if (\is_null($this->value)) { + return Sequence::of($next); + } + + if (\is_null($next->value)) { + throw new \LogicException('Multiple "none" chunk inserted in the sequence'); + } + if ($next->value instanceof Header) { throw new \LogicException('The header should be the first value only'); } @@ -40,7 +63,7 @@ public function and(self $next): Sequence public function pull(): Pull { - if ($this->value instanceof Header) { + if (!($this->value instanceof Str)) { throw new \LogicException; } From 76c42d244829b11f2e177e9045900cb937029725 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 17:04:01 +0100 Subject: [PATCH 15/32] force the efforts to be the same as encryption --- src/Decrypt.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Decrypt.php b/src/Decrypt.php index ff7afdb..33ffd67 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -40,10 +40,8 @@ private function __construct( ['ops' => $ops, 'mem' => $mem] = \unpack('Pops/Pmem', $limits->toString()); if ( - $ops < \SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE || - $ops > \SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE || - $mem < \SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE || - $mem > \SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE + $ops !== \SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE || + $mem !== \SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE ) { throw new \RuntimeException('Invalid derivation key parameters'); } From bdc0df430481fb519255b7a745649ffd4a2206f3 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 17:06:43 +0100 Subject: [PATCH 16/32] remove useless call as the info is publicly available --- src/Encrypt.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Encrypt.php b/src/Encrypt.php index e76f7b3..1271297 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -44,7 +44,6 @@ public function __invoke(Sequence $chunks): Sequence \SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE, ), ); - \sodium_memzero($salt); /** * @var string $header From fc4466a1b6f3b989f02995f204b000f15bbbb462 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 17:13:04 +0100 Subject: [PATCH 17/32] remove empty last chunk if there is another previous chunk --- src/Encrypt.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Encrypt.php b/src/Encrypt.php index 1271297..9424ae2 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -58,9 +58,12 @@ public function __invoke(Sequence $chunks): Sequence ->add(Str::of('')) // to make sure there is always at least one chunk ->map(static fn($chunk) => $chunk->toEncoding(Str\Encoding::ascii)) ->aggregate( - static fn(Str $a, Str $b) => $a - ->append($b) - ->chunk(8192), + static fn(Str $a, Str $b) => match ($b->empty()) { + true => $a->chunk(8192), // this removes the appended empty chunk if there's at least one other chunk + false => $a + ->append($b) + ->chunk(8192), + }, ) ->map(static fn($chunk) => $chunk->toString()) ->via(Sequence\Position::tag(...)) From 2dbe267bd0da104228405d0deeabd510ba6a7334 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 17:16:28 +0100 Subject: [PATCH 18/32] filter out empty chunks before decrypting --- src/Decrypt.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Decrypt.php b/src/Decrypt.php index 33ffd67..7a5ee6a 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -106,6 +106,7 @@ static function($header) use (&$pair, &$state) { /** @psalm-suppress MixedArgumentTypeCoercion */ yield $chunks ->via($decode) + ->filter(static fn($chunk) => $chunk instanceof Decrypt\Header || !$chunk->empty()) ->flatMap(static fn($chunk) => match (true) { $chunk instanceof Decrypt\Header => Sequence::of($chunk), default => $chunk->chunk(self::CHUNK), From d6648f3400ea8247b7853a4e4f2db3a9d381ad29 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 17:28:02 +0100 Subject: [PATCH 19/32] make the most likely branch to run first --- src/Decrypt.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Decrypt.php b/src/Decrypt.php index 7a5ee6a..745fa3e 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -108,12 +108,12 @@ static function($header) use (&$pair, &$state) { ->via($decode) ->filter(static fn($chunk) => $chunk instanceof Decrypt\Header || !$chunk->empty()) ->flatMap(static fn($chunk) => match (true) { - $chunk instanceof Decrypt\Header => Sequence::of($chunk), - default => $chunk->chunk(self::CHUNK), + $chunk instanceof Str => $chunk->chunk(self::CHUNK), + default => Sequence::of($chunk), }) ->aggregate(static fn(Decrypt\Header|Str $a, Str $b) => match (true) { - $a instanceof Decrypt\Header => Sequence::of($a, $b), - default => $a->append($b)->chunk(self::CHUNK), + $a instanceof Str => $a->append($b)->chunk(self::CHUNK), + default => Sequence::of($a, $b), }) ->map(Decrypt\Chunk::of(...)) ->prepend(Sequence::of(Decrypt\Chunk::none())) From 978878808e1097e5d5a5dea442e66bcc9c806b8e Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Thu, 12 Nov 2026 17:32:08 +0100 Subject: [PATCH 20/32] fix truncating to the exact encrypted size --- proofs/encryption.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/proofs/encryption.php b/proofs/encryption.php index e8f465c..8028be9 100644 --- a/proofs/encryption.php +++ b/proofs/encryption.php @@ -89,7 +89,7 @@ ->unwrap() ->fold(Concat::monoid) ->toEncoding(Str\Encoding::ascii) - ->length(), + ->length() - 1, ) ->map(static fn($truntaed) => [ $encrypted->unwrap(), From ee1c68b0cdd81289e6a505b1dfd053164050c8f4 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 15:32:58 +0100 Subject: [PATCH 21/32] bump dependencies --- composer.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index 77c0f0c..2f0502c 100644 --- a/composer.json +++ b/composer.json @@ -16,8 +16,8 @@ }, "require": { "php": "~8.5", - "innmind/immutable": "~6.4", - "innmind/frame": "^1.0.1" + "innmind/immutable": "~6.5", + "innmind/frame": "^1.0.2" }, "autoload": { "psr-4": { From dbf340fc78f0c0e1257f834049031c2cd0e05de6 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 16:12:03 +0100 Subject: [PATCH 22/32] make sure decrypting with the wrong password fails --- proofs/encryption.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/proofs/encryption.php b/proofs/encryption.php index 8028be9..3e63ed2 100644 --- a/proofs/encryption.php +++ b/proofs/encryption.php @@ -111,4 +111,26 @@ ->toString(), ); }); + + yield $prove + ->proof('Decryption with wrong password fails') + ->given( + Set::sequence( + Set::strings(), + ), + Set::strings()->between(1, 4096), + Set::strings()->between(1, 4096), + ) + ->exclude(static fn($_, $a, $b) => $a === $b) + ->test(static function(Assert $assert, $chunks, $password, $wrongPassword) { + $encrypt = Encrypt::of($password); + $decrypt = Decrypt::of($wrongPassword); + $encrypted = Sequence::of(...$chunks) + ->map(Str::of(...)) + ->via($encrypt); + + $assert->throws( + static fn() => $decrypt($encrypted)->memoize(), + ); + }); }; From 341390b477727d94da1f590eb7cb1dca68835964 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 16:24:23 +0100 Subject: [PATCH 23/32] use an object to keep a signle reference to the derivation key --- src/Decrypt.php | 10 +++++----- src/Decrypt/Key.php | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 5 deletions(-) create mode 100644 src/Decrypt/Key.php diff --git a/src/Decrypt.php b/src/Decrypt.php index 745fa3e..1839868 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -14,7 +14,7 @@ final class Decrypt { private const int CHUNK = 8192 + \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES; - /** @var Frame */ + /** @var Frame */ private Frame $decode; private function __construct( @@ -56,14 +56,14 @@ private function __construct( ) ->map(static function($tuple) use ($password) { [$kdfHeader, $salt, $ops, $mem] = $tuple; - $key = \sodium_crypto_pwhash( + $key = new Decrypt\Key(\sodium_crypto_pwhash( \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, $password, $salt, $ops, $mem, \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, - ); + )); return [ $kdfHeader, @@ -90,9 +90,9 @@ static function($pair) use (&$state) { static function($header) use (&$pair, &$state) { $state = \sodium_crypto_secretstream_xchacha20poly1305_init_pull( $header->toString(), - $pair[1], + $pair[1]->unwrap(), ); - \sodium_memzero($pair[1]); + $pair[1]->destroy(); return $pair[0]; }, diff --git a/src/Decrypt/Key.php b/src/Decrypt/Key.php new file mode 100644 index 0000000..6f22bf9 --- /dev/null +++ b/src/Decrypt/Key.php @@ -0,0 +1,24 @@ +value; + } + + public function destroy(): void + { + /** @psalm-suppress PossiblyNullPropertyAssignmentValue If the PHP Doc is to be belived this should not happen */ + \sodium_memzero($this->value); + } +} From 8c16a30ba68bee9337765d00de1027ff075481ec Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 16:29:15 +0100 Subject: [PATCH 24/32] use a value object to hold passwords --- proofs/encryption.php | 15 ++++++++------- src/Decrypt.php | 6 +++--- src/Encrypt.php | 6 +++--- src/Password.php | 42 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 56 insertions(+), 13 deletions(-) create mode 100644 src/Password.php diff --git a/proofs/encryption.php b/proofs/encryption.php index 3e63ed2..fad920b 100644 --- a/proofs/encryption.php +++ b/proofs/encryption.php @@ -5,6 +5,7 @@ use Innmind\Encryption\{ Encrypt, Decrypt, + Password, }; use Innmind\Immutable\{ Sequence, @@ -27,8 +28,8 @@ Set::strings()->between(1, 4096), ) ->test(static function(Assert $assert, $chunks, $password) { - $encrypt = Encrypt::of($password); - $decrypt = Decrypt::of($password); + $encrypt = Encrypt::of(Password::of($password)); + $decrypt = Decrypt::of(Password::of($password)); $assert->same( \implode('', $chunks), @@ -50,7 +51,7 @@ Set::strings()->between(1, 4096), ) ->test(static function(Assert $assert, $chunks, $password) { - $encrypt = Encrypt::of($password); + $encrypt = Encrypt::of(Password::of($password)); $encrypted = Sequence::of(...$chunks) ->map(Str::of(...)) @@ -80,7 +81,7 @@ ->flatMap( static fn($password) => Set::sequence(Set::strings()) ->map(static fn($chunks) => Sequence::of(...$chunks)->map(Str::of(...))) - ->map(Encrypt::of($password->unwrap())) + ->map(Encrypt::of(Password::of($password->unwrap()))) ->flatMap( static fn($encrypted) => Set::integers() ->between( @@ -106,7 +107,7 @@ static fn() => $encrypted ->flatMap(static fn($chunk) => $chunk->chunk()) ->take($truncated) - ->via(Decrypt::of($password)) + ->via(Decrypt::of(Password::of($password))) ->fold(Concat::monoid) ->toString(), ); @@ -123,8 +124,8 @@ ) ->exclude(static fn($_, $a, $b) => $a === $b) ->test(static function(Assert $assert, $chunks, $password, $wrongPassword) { - $encrypt = Encrypt::of($password); - $decrypt = Decrypt::of($wrongPassword); + $encrypt = Encrypt::of(Password::of($password)); + $decrypt = Decrypt::of(Password::of($wrongPassword)); $encrypted = Sequence::of(...$chunks) ->map(Str::of(...)) ->via($encrypt); diff --git a/src/Decrypt.php b/src/Decrypt.php index 1839868..2ebf37d 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -18,7 +18,7 @@ final class Decrypt private Frame $decode; private function __construct( - #[\SensitiveParameter] string $password, + Password $password, ) { $this->decode = Frame::chunk(4) ->map(static fn($magic) => match ($magic->toString()) { @@ -58,7 +58,7 @@ private function __construct( [$kdfHeader, $salt, $ops, $mem] = $tuple; $key = new Decrypt\Key(\sodium_crypto_pwhash( \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, - $password, + $password->unwrap(), $salt, $ops, $mem, @@ -136,7 +136,7 @@ static function($header) use (&$pair, &$state) { ->map(static fn($chunk) => $chunk->toEncoding(Str\Encoding::ascii)); } - public static function of(#[\SensitiveParameter] string $password): self + public static function of(Password $password): self { return new self($password); } diff --git a/src/Encrypt.php b/src/Encrypt.php index 9424ae2..21dfa39 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -12,7 +12,7 @@ final class Encrypt { private function __construct( - private string $password, + private Password $password, ) { } @@ -29,7 +29,7 @@ public function __invoke(Sequence $chunks): Sequence $salt = \random_bytes(\SODIUM_CRYPTO_PWHASH_SALTBYTES); $key = \sodium_crypto_pwhash( \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, - $password, + $password->unwrap(), $salt, \SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE, \SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE, @@ -92,7 +92,7 @@ static function($value) use (&$state, $kdfHeader) { ->map(static fn($chunk) => $chunk->toEncoding(Str\Encoding::ascii)); } - public static function of(#[\SensitiveParameter] string $password): self + public static function of(Password $password): self { return new self($password); } diff --git a/src/Password.php b/src/Password.php new file mode 100644 index 0000000..89fca9a --- /dev/null +++ b/src/Password.php @@ -0,0 +1,42 @@ + $value + */ + private function __construct( + private \SensitiveParameterValue $value, + ) { + } + + /** + * @psalm-pure + * + * @param non-empty-string $value + */ + public static function of(#[\SensitiveParameter] string $value): self + { + /** @psalm-suppress TypeDoesNotContainType */ + if ($value === '') { + throw new \DomainException('Password cannot be empty'); + } + + return new self(new \SensitiveParameterValue($value)); + } + + /** + * @return non-empty-string + */ + public function unwrap(): string + { + return $this->value->getValue(); + } +} From e778975e33788f7c1eb40a92534ab8a46662f969 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 17:00:41 +0100 Subject: [PATCH 25/32] add Version enum --- src/Decrypt.php | 9 +++------ src/Encrypt.php | 3 ++- src/Version.php | 43 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 7 deletions(-) create mode 100644 src/Version.php diff --git a/src/Decrypt.php b/src/Decrypt.php index 2ebf37d..af70d93 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -21,13 +21,10 @@ private function __construct( Password $password, ) { $this->decode = Frame::chunk(4) - ->map(static fn($magic) => match ($magic->toString()) { - 'PWE1' => $magic, - default => throw new \RuntimeException('Invalid encrypted file'), - }) + ->map(Version::of(...)) ->flatMap( - static fn($magic) => Frame::chunk(\SODIUM_CRYPTO_PWHASH_SALTBYTES)->map( - static fn($salt) => [$magic, $salt], + static fn($version) => Frame::chunk(\SODIUM_CRYPTO_PWHASH_SALTBYTES)->map( + static fn($salt) => [$version, $salt], ), ) ->flatMap( diff --git a/src/Encrypt.php b/src/Encrypt.php index 21dfa39..f78e396 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -36,7 +36,8 @@ public function __invoke(Sequence $chunks): Sequence \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, ); $kdfHeader = \sprintf( - 'PWE1%s%s', + '%s%s%s', + Version::latest()->toString(), $salt, \pack( 'PP', diff --git a/src/Version.php b/src/Version.php new file mode 100644 index 0000000..62819e9 --- /dev/null +++ b/src/Version.php @@ -0,0 +1,43 @@ +toString()) { + "IE@\x01" => self::v1, + }; + } + + /** + * @psalm-pure + */ + public static function latest(): self + { + return self::v1; + } + + /** + * @return non-empty-string + */ + public function toString(): string + { + return match ($this) { + self::v1 => "IE@\x01", + }; + } +} From 50964255944c95d2b29d4813741b9bd22231ea16 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 17:16:36 +0100 Subject: [PATCH 26/32] use an enum to specify the sensitivity of the encryption --- src/Decrypt.php | 22 +++++----------------- src/Encrypt.php | 10 +++------- src/Sensitivity.php | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 24 deletions(-) create mode 100644 src/Sensitivity.php diff --git a/src/Decrypt.php b/src/Decrypt.php index af70d93..ae7f90d 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -29,36 +29,24 @@ private function __construct( ) ->flatMap( static fn($pair) => Frame::chunk(16)->map(static function($limits) use ($pair) { - /** - * @var int $ops - * @var int $mem - * @psalm-suppress PossiblyInvalidArrayAccess - */ - ['ops' => $ops, 'mem' => $mem] = \unpack('Pops/Pmem', $limits->toString()); - - if ( - $ops !== \SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE || - $mem !== \SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE - ) { + if (Sensitivity::moderate->pack() !== $limits->toString()) { throw new \RuntimeException('Invalid derivation key parameters'); } return [ $pair[0]->toString().$pair[1]->toString().$limits->toString(), $pair[1]->toString(), - $ops, - $mem, ]; }), ) - ->map(static function($tuple) use ($password) { - [$kdfHeader, $salt, $ops, $mem] = $tuple; + ->map(static function($pair) use ($password) { + [$kdfHeader, $salt] = $pair; $key = new Decrypt\Key(\sodium_crypto_pwhash( \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, $password->unwrap(), $salt, - $ops, - $mem, + Sensitivity::moderate->operations(), + Sensitivity::moderate->memory(), \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, )); diff --git a/src/Encrypt.php b/src/Encrypt.php index f78e396..ee091bb 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -31,19 +31,15 @@ public function __invoke(Sequence $chunks): Sequence \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, $password->unwrap(), $salt, - \SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE, - \SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE, + Sensitivity::moderate->operations(), + Sensitivity::moderate->memory(), \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, ); $kdfHeader = \sprintf( '%s%s%s', Version::latest()->toString(), $salt, - \pack( - 'PP', - \SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE, - \SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE, - ), + Sensitivity::moderate->pack(), ); /** diff --git a/src/Sensitivity.php b/src/Sensitivity.php new file mode 100644 index 0000000..ee82906 --- /dev/null +++ b/src/Sensitivity.php @@ -0,0 +1,42 @@ +operations(), + $this->memory(), + ); + } + + public function operations(): int + { + return match ($this) { + self::low => \SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, + self::moderate => \SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE, + self::high => \SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE, + }; + } + + public function memory(): int + { + return match ($this) { + self::low => \SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE, + self::moderate => \SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE, + self::high => \SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE, + }; + } +} From 75907781262fb7e1f62ba8721819343146680399 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 17:23:47 +0100 Subject: [PATCH 27/32] derive the sensitivity from the version --- src/Decrypt.php | 11 ++++++----- src/Encrypt.php | 7 ++++--- src/Version.php | 7 +++++++ 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/src/Decrypt.php b/src/Decrypt.php index ae7f90d..07dfbf6 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -29,24 +29,25 @@ private function __construct( ) ->flatMap( static fn($pair) => Frame::chunk(16)->map(static function($limits) use ($pair) { - if (Sensitivity::moderate->pack() !== $limits->toString()) { + if ($pair[0]->sensitivity()->pack() !== $limits->toString()) { throw new \RuntimeException('Invalid derivation key parameters'); } return [ $pair[0]->toString().$pair[1]->toString().$limits->toString(), $pair[1]->toString(), + $pair[0]->sensitivity(), ]; }), ) - ->map(static function($pair) use ($password) { - [$kdfHeader, $salt] = $pair; + ->map(static function($tuple) use ($password) { + [$kdfHeader, $salt, $sensitivity] = $tuple; $key = new Decrypt\Key(\sodium_crypto_pwhash( \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, $password->unwrap(), $salt, - Sensitivity::moderate->operations(), - Sensitivity::moderate->memory(), + $sensitivity->operations(), + $sensitivity->memory(), \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, )); diff --git a/src/Encrypt.php b/src/Encrypt.php index ee091bb..1fc51c6 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -26,20 +26,21 @@ public function __invoke(Sequence $chunks): Sequence $password = $this->password; return Sequence::lazy(static function() use ($chunks, $password) { + $version = Version::latest(); $salt = \random_bytes(\SODIUM_CRYPTO_PWHASH_SALTBYTES); $key = \sodium_crypto_pwhash( \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, $password->unwrap(), $salt, - Sensitivity::moderate->operations(), - Sensitivity::moderate->memory(), + $version->sensitivity()->operations(), + $version->sensitivity()->memory(), \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, ); $kdfHeader = \sprintf( '%s%s%s', Version::latest()->toString(), $salt, - Sensitivity::moderate->pack(), + $version->sensitivity()->pack(), ); /** diff --git a/src/Version.php b/src/Version.php index 62819e9..0ca1d05 100644 --- a/src/Version.php +++ b/src/Version.php @@ -31,6 +31,13 @@ public static function latest(): self return self::v1; } + public function sensitivity(): Sensitivity + { + return match ($this) { + self::v1 => Sensitivity::moderate, + }; + } + /** * @return non-empty-string */ From 2cd1bd8206d0d6c7b878101ec0d3b969df1a99b7 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 17:32:48 +0100 Subject: [PATCH 28/32] make sure to use the same version --- src/Encrypt.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Encrypt.php b/src/Encrypt.php index 1fc51c6..c2fae29 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -38,7 +38,7 @@ public function __invoke(Sequence $chunks): Sequence ); $kdfHeader = \sprintf( '%s%s%s', - Version::latest()->toString(), + $version->toString(), $salt, $version->sensitivity()->pack(), ); From d56360837b3496f1d44acd44fd07a18c63265eaf Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 17:54:47 +0100 Subject: [PATCH 29/32] add Algorithm enum to centralize derivation key logic --- src/Algorithm.php | 27 +++++++++++++++++++++++++++ src/Algorithm/Hash.php | 40 ++++++++++++++++++++++++++++++++++++++++ src/Algorithm/Salt.php | 38 ++++++++++++++++++++++++++++++++++++++ src/Decrypt.php | 21 ++++++++++----------- src/Encrypt.php | 11 ++++------- src/Version.php | 7 +++++++ 6 files changed, 126 insertions(+), 18 deletions(-) create mode 100644 src/Algorithm.php create mode 100644 src/Algorithm/Hash.php create mode 100644 src/Algorithm/Salt.php diff --git a/src/Algorithm.php b/src/Algorithm.php new file mode 100644 index 0000000..f914a47 --- /dev/null +++ b/src/Algorithm.php @@ -0,0 +1,27 @@ + Algorithm\Hash::xchacha20poly1305, + }; + } + + public function salt(): Algorithm\Salt + { + return match ($this) { + self::xchacha20poly1305 => Algorithm\Salt::xchacha20poly1305, + }; + } +} diff --git a/src/Algorithm/Hash.php b/src/Algorithm/Hash.php new file mode 100644 index 0000000..4a1581c --- /dev/null +++ b/src/Algorithm/Hash.php @@ -0,0 +1,40 @@ + \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, + }; + } + + public function key( + Password $password, + string $salt, + Sensitivity $sensitivity, + ): string { + return match ($this) { + self::xchacha20poly1305 => \sodium_crypto_pwhash( + $this->size(), + $password->unwrap(), + $salt, + $sensitivity->operations(), + $sensitivity->memory(), + \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, + ), + }; + } +} diff --git a/src/Algorithm/Salt.php b/src/Algorithm/Salt.php new file mode 100644 index 0000000..be7300c --- /dev/null +++ b/src/Algorithm/Salt.php @@ -0,0 +1,38 @@ +size()); + } + + /** + * @return Frame + */ + public function frame(): Frame + { + return match ($this) { + self::xchacha20poly1305 => Frame::chunk($this->size()), + }; + } + + /** + * @return int<1, max> + */ + private function size(): int + { + return match ($this) { + self::xchacha20poly1305 => \SODIUM_CRYPTO_PWHASH_SALTBYTES, + }; + } +} diff --git a/src/Decrypt.php b/src/Decrypt.php index 07dfbf6..73589a0 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -23,9 +23,11 @@ private function __construct( $this->decode = Frame::chunk(4) ->map(Version::of(...)) ->flatMap( - static fn($version) => Frame::chunk(\SODIUM_CRYPTO_PWHASH_SALTBYTES)->map( - static fn($salt) => [$version, $salt], - ), + static fn($version) => $version + ->algorithm() + ->salt() + ->frame() + ->map(static fn($salt) => [$version, $salt]), ) ->flatMap( static fn($pair) => Frame::chunk(16)->map(static function($limits) use ($pair) { @@ -36,19 +38,16 @@ private function __construct( return [ $pair[0]->toString().$pair[1]->toString().$limits->toString(), $pair[1]->toString(), - $pair[0]->sensitivity(), + $pair[0], ]; }), ) ->map(static function($tuple) use ($password) { - [$kdfHeader, $salt, $sensitivity] = $tuple; - $key = new Decrypt\Key(\sodium_crypto_pwhash( - \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, - $password->unwrap(), + [$kdfHeader, $salt, $version] = $tuple; + $key = new Decrypt\Key($version->algorithm()->hash()->key( + $password, $salt, - $sensitivity->operations(), - $sensitivity->memory(), - \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, + $version->sensitivity(), )); return [ diff --git a/src/Encrypt.php b/src/Encrypt.php index c2fae29..64c4961 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -27,14 +27,11 @@ public function __invoke(Sequence $chunks): Sequence return Sequence::lazy(static function() use ($chunks, $password) { $version = Version::latest(); - $salt = \random_bytes(\SODIUM_CRYPTO_PWHASH_SALTBYTES); - $key = \sodium_crypto_pwhash( - \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, - $password->unwrap(), + $salt = $version->algorithm()->salt()->new(); + $key = $version->algorithm()->hash()->key( + $password, $salt, - $version->sensitivity()->operations(), - $version->sensitivity()->memory(), - \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, + $version->sensitivity(), ); $kdfHeader = \sprintf( '%s%s%s', diff --git a/src/Version.php b/src/Version.php index 0ca1d05..f81c9a0 100644 --- a/src/Version.php +++ b/src/Version.php @@ -38,6 +38,13 @@ public function sensitivity(): Sensitivity }; } + public function algorithm(): Algorithm + { + return match ($this) { + self::v1 => Algorithm::xchacha20poly1305, + }; + } + /** * @return non-empty-string */ From f14ff878d509e6b0ee7a08a0cdc4ec3ffcc030ec Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 18:02:51 +0100 Subject: [PATCH 30/32] build the sensitivity frame from the enum --- src/Decrypt.php | 15 ++++++--------- src/Sensitivity.php | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/src/Decrypt.php b/src/Decrypt.php index 73589a0..2ac175b 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -30,17 +30,14 @@ private function __construct( ->map(static fn($salt) => [$version, $salt]), ) ->flatMap( - static fn($pair) => Frame::chunk(16)->map(static function($limits) use ($pair) { - if ($pair[0]->sensitivity()->pack() !== $limits->toString()) { - throw new \RuntimeException('Invalid derivation key parameters'); - } - - return [ - $pair[0]->toString().$pair[1]->toString().$limits->toString(), + static fn($pair) => $pair[0] + ->sensitivity() + ->frame() + ->map(static fn($limits) => [ + $pair[0]->toString().$pair[1]->toString().$limits->pack(), $pair[1]->toString(), $pair[0], - ]; - }), + ]), ) ->map(static function($tuple) use ($password) { [$kdfHeader, $salt, $version] = $tuple; diff --git a/src/Sensitivity.php b/src/Sensitivity.php index ee82906..a62b968 100644 --- a/src/Sensitivity.php +++ b/src/Sensitivity.php @@ -4,6 +4,8 @@ namespace Innmind\Encryption; +use Innmind\Frame\Frame; + /** * @psalm-immutable */ @@ -39,4 +41,18 @@ public function memory(): int self::high => \SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE, }; } + + /** + * @return Frame + */ + public function frame(): Frame + { + return Frame::chunk(16)->map(function($limits) { + if ($this->pack() !== $limits->toString()) { + throw new \RuntimeException('Invalid derivation key parameters'); + } + + return $this; + }); + } } From 88a432757f018bbcf64657dc545ff6f9960eeba8 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 18:09:15 +0100 Subject: [PATCH 31/32] use single DerivationKey object for both encryption and decryption --- src/Algorithm/Hash.php | 13 ++++++++----- src/Decrypt.php | 6 +++--- src/{Decrypt/Key.php => DerivationKey.php} | 4 ++-- src/Encrypt.php | 4 ++-- 4 files changed, 15 insertions(+), 12 deletions(-) rename src/{Decrypt/Key.php => DerivationKey.php} (87%) diff --git a/src/Algorithm/Hash.php b/src/Algorithm/Hash.php index 4a1581c..3f134de 100644 --- a/src/Algorithm/Hash.php +++ b/src/Algorithm/Hash.php @@ -4,8 +4,11 @@ namespace Innmind\Encryption\Algorithm; -use Innmind\Encryption\Password; -use Innmind\Encryption\Sensitivity; +use Innmind\Encryption\{ + DerivationKey, + Password, + Sensitivity, +}; /** * @psalm-immutable @@ -25,8 +28,8 @@ public function key( Password $password, string $salt, Sensitivity $sensitivity, - ): string { - return match ($this) { + ): DerivationKey { + return new DerivationKey(match ($this) { self::xchacha20poly1305 => \sodium_crypto_pwhash( $this->size(), $password->unwrap(), @@ -35,6 +38,6 @@ public function key( $sensitivity->memory(), \SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13, ), - }; + }); } } diff --git a/src/Decrypt.php b/src/Decrypt.php index 2ac175b..aac7d68 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -14,7 +14,7 @@ final class Decrypt { private const int CHUNK = 8192 + \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES; - /** @var Frame */ + /** @var Frame */ private Frame $decode; private function __construct( @@ -41,11 +41,11 @@ private function __construct( ) ->map(static function($tuple) use ($password) { [$kdfHeader, $salt, $version] = $tuple; - $key = new Decrypt\Key($version->algorithm()->hash()->key( + $key = $version->algorithm()->hash()->key( $password, $salt, $version->sensitivity(), - )); + ); return [ $kdfHeader, diff --git a/src/Decrypt/Key.php b/src/DerivationKey.php similarity index 87% rename from src/Decrypt/Key.php rename to src/DerivationKey.php index 6f22bf9..3b0f567 100644 --- a/src/Decrypt/Key.php +++ b/src/DerivationKey.php @@ -2,9 +2,9 @@ declare(strict_types = 1); -namespace Innmind\Encryption\Decrypt; +namespace Innmind\Encryption; -final class Key +final class DerivationKey { public function __construct( private string $value, diff --git a/src/Encrypt.php b/src/Encrypt.php index 64c4961..6b42285 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -43,8 +43,8 @@ public function __invoke(Sequence $chunks): Sequence /** * @var string $header */ - [$state, $header] = \sodium_crypto_secretstream_xchacha20poly1305_init_push($key); - \sodium_memzero($key); + [$state, $header] = \sodium_crypto_secretstream_xchacha20poly1305_init_push($key->unwrap()); + $key->destroy(); yield Sequence::of($kdfHeader, $header); From 64ef24a3e4301829c0f9a1efb652c66ecdb522c1 Mon Sep 17 00:00:00 2001 From: Baptiste Langlade Date: Fri, 13 Nov 2026 18:18:18 +0100 Subject: [PATCH 32/32] use the version enum to build the kdf header --- src/Decrypt.php | 2 +- src/Encrypt.php | 7 +------ src/Version.php | 15 +++++++++++++++ 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/src/Decrypt.php b/src/Decrypt.php index aac7d68..3f17ee8 100644 --- a/src/Decrypt.php +++ b/src/Decrypt.php @@ -34,7 +34,7 @@ private function __construct( ->sensitivity() ->frame() ->map(static fn($limits) => [ - $pair[0]->toString().$pair[1]->toString().$limits->pack(), + $pair[0]->kdfHeader($pair[1]->toString(), $limits), $pair[1]->toString(), $pair[0], ]), diff --git a/src/Encrypt.php b/src/Encrypt.php index 6b42285..1666f75 100644 --- a/src/Encrypt.php +++ b/src/Encrypt.php @@ -33,12 +33,7 @@ public function __invoke(Sequence $chunks): Sequence $salt, $version->sensitivity(), ); - $kdfHeader = \sprintf( - '%s%s%s', - $version->toString(), - $salt, - $version->sensitivity()->pack(), - ); + $kdfHeader = $version->kdfHeader($salt); /** * @var string $header diff --git a/src/Version.php b/src/Version.php index f81c9a0..d68fe0d 100644 --- a/src/Version.php +++ b/src/Version.php @@ -45,6 +45,21 @@ public function algorithm(): Algorithm }; } + /** + * @return non-empty-string + */ + public function kdfHeader(string $salt, ?Sensitivity $sensitivity = null): string + { + $sensitivity ??= $this->sensitivity(); + + return \sprintf( + '%s%s%s', + $this->toString(), + $salt, + $sensitivity->pack(), + ); + } + /** * @return non-empty-string */