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, }) diff --git a/composer.json b/composer.json index f3a0028..2f0502c 100644 --- a/composer.json +++ b/composer.json @@ -15,7 +15,9 @@ "issues": "http://github.com/innmind/encryption/issues" }, "require": { - "php": "~8.5" + "php": "~8.5", + "innmind/immutable": "~6.5", + "innmind/frame": "^1.0.2" }, "autoload": { "psr-4": { 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..fad920b --- /dev/null +++ b/proofs/encryption.php @@ -0,0 +1,137 @@ +proof('Encryption/decryption identity') + ->given( + Set::sequence( + Set::strings(), + ), + Set::strings()->between(1, 4096), + ) + ->test(static function(Assert $assert, $chunks, $password) { + $encrypt = Encrypt::of(Password::of($password)); + $decrypt = Decrypt::of(Password::of($password)); + + $assert->same( + \implode('', $chunks), + Sequence::of(...$chunks) + ->map(Str::of(...)) + ->via($encrypt) + ->via($decrypt) + ->fold(Concat::monoid) + ->toString(), + ); + }); + + yield $prove + ->proof('Encryption does not expose chunks in plain text') + ->given( + Set::sequence( + Set::strings()->atLeast(4), // 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::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)); + } + }); + + 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::of($password->unwrap()))) + ->flatMap( + static fn($encrypted) => Set::integers() + ->between( + 0, + $encrypted + ->unwrap() + ->fold(Concat::monoid) + ->toEncoding(Str\Encoding::ascii) + ->length() - 1, + ) + ->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::of($password))) + ->fold(Concat::monoid) + ->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::of($password)); + $decrypt = Decrypt::of(Password::of($wrongPassword)); + $encrypted = Sequence::of(...$chunks) + ->map(Str::of(...)) + ->via($encrypt); + + $assert->throws( + static fn() => $decrypt($encrypted)->memoize(), + ); + }); +}; diff --git a/src/.gitkeep b/src/.gitkeep deleted file mode 100644 index e69de29..0000000 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..3f134de --- /dev/null +++ b/src/Algorithm/Hash.php @@ -0,0 +1,43 @@ + \SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES, + }; + } + + public function key( + Password $password, + string $salt, + Sensitivity $sensitivity, + ): DerivationKey { + return new DerivationKey(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 new file mode 100644 index 0000000..3f17ee8 --- /dev/null +++ b/src/Decrypt.php @@ -0,0 +1,125 @@ + */ + private Frame $decode; + + private function __construct( + Password $password, + ) { + $this->decode = Frame::chunk(4) + ->map(Version::of(...)) + ->flatMap( + static fn($version) => $version + ->algorithm() + ->salt() + ->frame() + ->map(static fn($salt) => [$version, $salt]), + ) + ->flatMap( + static fn($pair) => $pair[0] + ->sensitivity() + ->frame() + ->map(static fn($limits) => [ + $pair[0]->kdfHeader($pair[1]->toString(), $limits), + $pair[1]->toString(), + $pair[0], + ]), + ) + ->map(static function($tuple) use ($password) { + [$kdfHeader, $salt, $version] = $tuple; + $key = $version->algorithm()->hash()->key( + $password, + $salt, + $version->sensitivity(), + ); + + 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]->unwrap(), + ); + $pair[1]->destroy(); + + return $pair[0]; + }, + ); + }, + ) + ->map(Str::of(...)) + ->map(Decrypt\Header::of(...)) + ->passthrough(); + + /** @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 Str => $chunk->chunk(self::CHUNK), + default => Sequence::of($chunk), + }) + ->aggregate(static fn(Decrypt\Header|Str $a, Str $b) => match (true) { + $a instanceof Str => $a->append($b)->chunk(self::CHUNK), + default => Sequence::of($a, $b), + }) + ->map(Decrypt\Chunk::of(...)) + ->prepend(Sequence::of(Decrypt\Chunk::none())) + ->aggregate(static fn(Decrypt\Chunk|Decrypt\Pull $a, Decrypt\Chunk $b) => $a->and($b)) + ->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(Password $password): self + { + return new self($password); + } +} diff --git a/src/Decrypt/Chunk.php b/src/Decrypt/Chunk.php new file mode 100644 index 0000000..dea2285 --- /dev/null +++ b/src/Decrypt/Chunk.php @@ -0,0 +1,72 @@ + + */ + 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'); + } + + 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 Str)) { + 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..a64fa4e --- /dev/null +++ b/src/Decrypt/Plain.php @@ -0,0 +1,39 @@ +last() && !$this->last) || + ($this->last && !$position->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()); + } +} diff --git a/src/DerivationKey.php b/src/DerivationKey.php new file mode 100644 index 0000000..3b0f567 --- /dev/null +++ b/src/DerivationKey.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); + } +} diff --git a/src/Encrypt.php b/src/Encrypt.php new file mode 100644 index 0000000..1666f75 --- /dev/null +++ b/src/Encrypt.php @@ -0,0 +1,89 @@ + $chunks + * + * @return Sequence + */ + public function __invoke(Sequence $chunks): Sequence + { + $password = $this->password; + + return Sequence::lazy(static function() use ($chunks, $password) { + $version = Version::latest(); + $salt = $version->algorithm()->salt()->new(); + $key = $version->algorithm()->hash()->key( + $password, + $salt, + $version->sensitivity(), + ); + $kdfHeader = $version->kdfHeader($salt); + + /** + * @var string $header + */ + [$state, $header] = \sodium_crypto_secretstream_xchacha20poly1305_init_push($key->unwrap()); + $key->destroy(); + + 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( + 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(...)) + ->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, + }, + ); + }, + ); + + /** @psalm-suppress MixedArgument */ + \sodium_memzero($state); + }) + ->flatMap(static fn($chunks) => $chunks) + ->map(Str::of(...)) + ->map(static fn($chunk) => $chunk->toEncoding(Str\Encoding::ascii)); + } + + 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(); + } +} diff --git a/src/Sensitivity.php b/src/Sensitivity.php new file mode 100644 index 0000000..a62b968 --- /dev/null +++ b/src/Sensitivity.php @@ -0,0 +1,58 @@ +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, + }; + } + + /** + * @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; + }); + } +} diff --git a/src/Version.php b/src/Version.php new file mode 100644 index 0000000..d68fe0d --- /dev/null +++ b/src/Version.php @@ -0,0 +1,72 @@ +toString()) { + "IE@\x01" => self::v1, + }; + } + + /** + * @psalm-pure + */ + public static function latest(): self + { + return self::v1; + } + + public function sensitivity(): Sensitivity + { + return match ($this) { + self::v1 => Sensitivity::moderate, + }; + } + + public function algorithm(): Algorithm + { + return match ($this) { + self::v1 => Algorithm::xchacha20poly1305, + }; + } + + /** + * @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 + */ + public function toString(): string + { + return match ($this) { + self::v1 => "IE@\x01", + }; + } +}