diff --git a/Tests/Cipher/SodiumTest.php b/Tests/Cipher/SodiumTest.php index 0f0e049b..d009c2fd 100644 --- a/Tests/Cipher/SodiumTest.php +++ b/Tests/Cipher/SodiumTest.php @@ -8,8 +8,8 @@ namespace Joomla\Crypt\Tests\Cipher; use Joomla\Crypt\Cipher\Sodium; +use Joomla\Crypt\Exception\DecryptionException; use Joomla\Crypt\Key; -use ParagonIE\Sodium\Compat; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Symfony\Polyfill\Util\Binary; @@ -52,51 +52,88 @@ public static function dataStrings(): array } /** - * @testdox Validates data is encrypted and decrypted correctly - * - * @param string $data The decrypted data to validate + * @testdox Validates keys are correctly generated * * @covers \Joomla\Crypt\Cipher\Sodium * @uses \Joomla\Crypt\Key */ - #[DataProvider('dataStrings')] - public function testDataEncryptionAndDecryption($data) + public function testGenerateKey() { $cipher = new Sodium(); $key = $cipher->generateKey(); - $cipher->setNonce(Compat::randombytes_buf(Compat::CRYPTO_BOX_NONCEBYTES)); + // Assert that the key is the correct type. + $this->assertInstanceOf(Key::class, $key); + + // Assert the keys pass validation + $this->assertSame(Binary::strlen($key->getPrivate()), 32); + $this->assertSame(Binary::strlen($key->getPublic()), 32); + + // Assert the key is of the correct type. + $this->assertSame('sodium', $key->getType()); + } + + /** + * @testdox Validates data is encrypted and decrypted correctly with a random nonce per message + * + * @param string $data The decrypted data to validate + */ + #[DataProvider('dataStrings')] + public function testDataEncryptionAndDecryptionWithoutNonce($data) + { + $cipher = new Sodium(); + $key = $cipher->generateKey(); $encrypted = $cipher->encrypt($data, $key); - // Assert that the encrypted value is not the same as the clear text value. $this->assertNotSame($data, $encrypted); + $this->assertSame($data, (new Sodium())->decrypt($encrypted, $key)); + } + + /** + * @testdox Encrypting the same message twice uses a different nonce each time + */ + public function testEncryptUsesAFreshNonceForEveryMessage() + { + $cipher = new Sodium(); + $key = $cipher->generateKey(); + + $first = $cipher->encrypt('The quick brown fox', $key); + $second = $cipher->encrypt('The quick brown fox', $key); - $decrypted = $cipher->decrypt($encrypted, $key); + $this->assertNotSame($first, $second); + $this->assertNotSame(substr($first, 0, SODIUM_CRYPTO_BOX_NONCEBYTES), substr($second, 0, SODIUM_CRYPTO_BOX_NONCEBYTES)); - // Assert the decrypted string is the same value we started with - $this->assertSame($data, $decrypted); + // The nonce is stored in front of the crypto_box ciphertext + $this->assertSame( + 'The quick brown fox', + sodium_crypto_box_open( + substr($first, SODIUM_CRYPTO_BOX_NONCEBYTES), + substr($first, 0, SODIUM_CRYPTO_BOX_NONCEBYTES), + sodium_crypto_box_keypair_from_secretkey_and_publickey($key->getPrivate(), $key->getPublic()) + ) + ); } /** - * @testdox Validates keys are correctly generated - * - * @covers \Joomla\Crypt\Cipher\Sodium - * @uses \Joomla\Crypt\Key + * @testdox Data too short to contain a nonce is rejected */ - public function testGenerateKey() + public function testDecryptRejectsDataWithoutNonce() { $cipher = new Sodium(); $key = $cipher->generateKey(); - // Assert that the key is the correct type. - $this->assertInstanceOf(Key::class, $key); + $this->expectException(DecryptionException::class); + $this->expectExceptionMessage('The encrypted data is too short to contain a nonce.'); - // Assert the keys pass validation - $this->assertSame(Binary::strlen($key->getPrivate()), 32); - $this->assertSame(Binary::strlen($key->getPublic()), 32); + $cipher->decrypt('data', $key); + } - // Assert the key is of the correct type. - $this->assertSame('sodium', $key->getType()); + /** + * @testdox The nonce can no longer be fixed + */ + public function testNonceCannotBeSet() + { + $this->assertFalse(method_exists(Sodium::class, 'setNonce')); } } diff --git a/composer.json b/composer.json index 2ce32ab3..31a2dcbc 100644 --- a/composer.json +++ b/composer.json @@ -6,7 +6,8 @@ "homepage": "https://github.com/joomla-framework/crypt", "license": "GPL-2.0-or-later", "require": { - "php": "^8.3.0" + "php": "^8.3.0", + "symfony/deprecation-contracts": "^2|^3" }, "require-dev": { "defuse/php-encryption": "^2.0", diff --git a/docs/index.md b/docs/index.md index 805bd724..45534879 100644 --- a/docs/index.md +++ b/docs/index.md @@ -3,3 +3,4 @@ * Upgrading * [Updating from v2 to v3](v2-to-v3-update.md) * [Updating from v3 to v4](v3-to-v4-update.md) + * [Updating from v4 to v5](v4-to-v5-update.md) diff --git a/docs/overview.md b/docs/overview.md index 7a7f3ce5..9edbc778 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -105,7 +105,9 @@ URL, a database column or a header. ## The Sodium cipher -`Cipher\Sodium` uses `sodium_crypto_box` and needs a nonce set before use: +`Cipher\Sodium` uses `sodium_crypto_box`. It generates a random 24-byte nonce for every message and +stores it in front of the ciphertext, so encrypting the same message twice gives two different +results and `decrypt()` needs nothing but the key: ```php use Joomla\Crypt\Cipher\Sodium; @@ -113,25 +115,13 @@ use Joomla\Crypt\Cipher\Sodium; $cipher = new Sodium(); $key = $cipher->generateKey(); -$nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES); // 24 bytes -$cipher->setNonce($nonce); - -$ciphertext = $cipher->encrypt('message', $key); +$ciphertext = $cipher->encrypt('message', $key); // nonce . crypto_box ciphertext +$plaintext = $cipher->decrypt($ciphertext, $key); ``` -Two things the package does not do for you, and both are essential: - -* **Generate the nonce.** There is no helper; you must produce 24 random bytes yourself. -* **Vary it per message.** The nonce is stored on the cipher instance and reused for every - `encrypt()` call on it. Reusing a nonce with the same key breaks XSalsa20-Poly1305 completely — - it exposes the XOR of the plaintexts and undermines the authenticator. Create a fresh nonce for - each message and store it alongside the ciphertext: - -```php -$nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES); -$cipher->setNonce($nonce); -$stored = base64_encode($nonce) . ':' . base64_encode($cipher->encrypt($message, $key)); -``` +Releases before 4.1 had no nonce handling of their own: the nonce had to be set with `setNonce()`, +was reused for every message of the instance and was not stored with the ciphertext. `setNonce()` +was removed in 5.0; see the [update guide](v4-to-v5-update.md) for migrating such data. ## The OpenSSL cipher diff --git a/docs/v4-to-v5-update.md b/docs/v4-to-v5-update.md new file mode 100644 index 00000000..504914d7 --- /dev/null +++ b/docs/v4-to-v5-update.md @@ -0,0 +1,39 @@ +# Updating from v4 to v5 + +Release 5.0.0 removes API that was deprecated in 4.x and adds native types to the public API. Each +breaking change has its own section below. + + + + + + + +## `Sodium::setNonce()` removed + +`Cipher\Sodium::setNonce()`, deprecated in 4.1, is gone. Since 4.1 the cipher generates a random +nonce for every message and stores it in front of the ciphertext; a nonce set with `setNonce()` was +reused for every message, which is insecure with `crypto_box`. + +**What to change:** + +* Remove `setNonce()` calls. `encrypt()` and `decrypt()` need nothing but the key. +* Data encrypted with a fixed nonce (with `setNonce()`) cannot be decrypted by the 5.x cipher. + Re-encrypt it while still on 4.x: + + ```php + $legacy = new Sodium(); + $legacy->setNonce($storedNonce); + + $ciphertext = (new Sodium())->encrypt($legacy->decrypt($oldCiphertext, $key), $key); + ``` + + or decrypt it directly with `sodium_crypto_box_open($oldCiphertext, $storedNonce, + sodium_crypto_box_keypair_from_secretkey_and_publickey($key->getPrivate(), $key->getPublic()))`. + + +## Dependency changes + +| Package | v4 (4.0.0) | v5 (5.0.0) | +|---|---|---| +| `php` | `^8.3.0` | `^8.3.0` | diff --git a/src/Cipher/Sodium.php b/src/Cipher/Sodium.php index bae797f0..89033d3d 100644 --- a/src/Cipher/Sodium.php +++ b/src/Cipher/Sodium.php @@ -25,14 +25,6 @@ */ class Sodium implements CipherInterface { - /** - * The message nonce to be used with encryption/decryption - * - * @var string - * @since 1.4.0 - */ - private $nonce; - /** * Method to decrypt a data string. * @@ -52,14 +44,18 @@ public function decrypt($data, Key $key) throw new InvalidKeyTypeException('sodium', $key->getType()); } - if (!$this->nonce) { - throw new DecryptionException('Missing nonce to decrypt data'); + // The nonce is stored in front of the ciphertext + if (\strlen($data) < SODIUM_CRYPTO_BOX_NONCEBYTES) { + throw new DecryptionException('The encrypted data is too short to contain a nonce.'); } + $nonce = substr($data, 0, SODIUM_CRYPTO_BOX_NONCEBYTES); + $data = substr($data, SODIUM_CRYPTO_BOX_NONCEBYTES); + try { $decrypted = sodium_crypto_box_open( $data, - $this->nonce, + $nonce, sodium_crypto_box_keypair_from_secretkey_and_publickey($key->getPrivate(), $key->getPublic()) ); @@ -92,18 +88,17 @@ public function encrypt($data, Key $key) throw new InvalidKeyTypeException('sodium', $key->getType()); } - if (!$this->nonce) { - throw new EncryptionException('Missing nonce to decrypt data'); - } + // Use a random nonce for every message and store it in front of the ciphertext + $nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES); try { - return sodium_crypto_box( + return $nonce . sodium_crypto_box( $data, - $this->nonce, + $nonce, sodium_crypto_box_keypair_from_secretkey_and_publickey($key->getPrivate(), $key->getPublic()) ); } catch (\SodiumException $exception) { - throw new EncryptionException('Could not encrypt file.', $exception->getCode(), $exception); + throw new EncryptionException('Could not encrypt data.', $exception->getCode(), $exception); } } @@ -142,18 +137,4 @@ public static function isSupported(): bool // Part of PHP since 7.2 return true; } - - /** - * Set the nonce to use for encrypting/decrypting messages - * - * @param string $nonce The message nonce - * - * @return void - * - * @since 1.4.0 - */ - public function setNonce($nonce) - { - $this->nonce = $nonce; - } }