From b04ada7ae2205e31958ee93ede901f4ffd188896 Mon Sep 17 00:00:00 2001 From: Hannes Papenberg Date: Thu, 12 Nov 2026 22:59:08 +0100 Subject: [PATCH] Use a random nonce per message in the Sodium cipher Cipher\Sodium used the nonce set through setNonce() for every message of the instance and did not store it, so encrypting two messages with the same key reused the nonce, which breaks XSalsa20-Poly1305. Without a nonce set, encrypt() now generates a random nonce per message and prepends it to the ciphertext, and decrypt() splits it off. Until now that case threw an exception, so existing callers are unaffected. setNonce() is deprecated and only kept to decrypt data encrypted with a fixed nonce. Nonces of the wrong length are rejected with a clear message. Co-Authored-By: Claude Opus 5.5 --- Tests/Cipher/SodiumTest.php | 114 +++++++++++++++++++++++++++++++++++- composer.json | 3 +- docs/overview.md | 33 ++++++----- src/Cipher/Sodium.php | 47 ++++++++++++--- 4 files changed, 173 insertions(+), 24 deletions(-) diff --git a/Tests/Cipher/SodiumTest.php b/Tests/Cipher/SodiumTest.php index 0f0e049b..f57e90a5 100644 --- a/Tests/Cipher/SodiumTest.php +++ b/Tests/Cipher/SodiumTest.php @@ -8,9 +8,12 @@ namespace Joomla\Crypt\Tests\Cipher; use Joomla\Crypt\Cipher\Sodium; +use Joomla\Crypt\Exception\DecryptionException; +use Joomla\Crypt\Exception\EncryptionException; use Joomla\Crypt\Key; use ParagonIE\Sodium\Compat; use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\IgnoreDeprecations; use PHPUnit\Framework\TestCase; use Symfony\Polyfill\Util\Binary; @@ -52,7 +55,7 @@ public static function dataStrings(): array } /** - * @testdox Validates data is encrypted and decrypted correctly + * @testdox Validates data is encrypted and decrypted correctly with a nonce set by setNonce() * * @param string $data The decrypted data to validate * @@ -60,6 +63,7 @@ public static function dataStrings(): array * @uses \Joomla\Crypt\Key */ #[DataProvider('dataStrings')] + #[IgnoreDeprecations] public function testDataEncryptionAndDecryption($data) { $cipher = new Sodium(); @@ -99,4 +103,112 @@ public function testGenerateKey() // 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); + + $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); + + $this->assertNotSame($first, $second); + $this->assertNotSame(substr($first, 0, SODIUM_CRYPTO_BOX_NONCEBYTES), substr($second, 0, SODIUM_CRYPTO_BOX_NONCEBYTES)); + + // 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 Data encrypted with a fixed nonce by earlier releases can still be decrypted + */ + #[IgnoreDeprecations] + public function testDecryptDataEncryptedWithAFixedNonce() + { + $cipher = new Sodium(); + $key = $cipher->generateKey(); + $nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES); + + $legacy = sodium_crypto_box( + 'The quick brown fox', + $nonce, + sodium_crypto_box_keypair_from_secretkey_and_publickey($key->getPrivate(), $key->getPublic()) + ); + + $cipher->setNonce($nonce); + + $this->assertSame($legacy, $cipher->encrypt('The quick brown fox', $key)); + $this->assertSame('The quick brown fox', $cipher->decrypt($legacy, $key)); + } + + /** + * @testdox Setting a nonce triggers a deprecation + */ + public function testSetNonceTriggersDeprecation() + { + $this->expectUserDeprecationMessage( + 'Since joomla/crypt __DEPLOY_VERSION__: Joomla\Crypt\Cipher\Sodium::setNonce() is deprecated and will be removed in 5.0.' + . ' Do not set a nonce; encrypt() generates a random nonce for every message.' + ); + + (new Sodium())->setNonce(random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES)); + } + + /** + * @testdox A nonce of the wrong length is rejected with a clear message + */ + #[IgnoreDeprecations] + public function testEncryptRejectsANonceOfTheWrongLength() + { + $cipher = new Sodium(); + $key = $cipher->generateKey(); + + $cipher->setNonce('too short'); + + $this->expectException(EncryptionException::class); + $this->expectExceptionMessage('The nonce must be 24 bytes long.'); + + $cipher->encrypt('data', $key); + } + + /** + * @testdox Data too short to contain a nonce is rejected + */ + public function testDecryptRejectsDataWithoutNonce() + { + $cipher = new Sodium(); + $key = $cipher->generateKey(); + + $this->expectException(DecryptionException::class); + $this->expectExceptionMessage('The encrypted data is too short to contain a nonce.'); + + $cipher->decrypt('data', $key); + } } 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/overview.md b/docs/overview.md index 7a7f3ce5..6ed4bbbe 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,26 +115,29 @@ 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: +Before 4.1 the cipher had no nonce handling of its own: the nonce had to be set with `setNonce()`, +was reused for every message of the instance and was not stored with the ciphertext. Reusing a +nonce with the same key breaks XSalsa20-Poly1305 completely — it exposes the XOR of the plaintexts +and undermines the authenticator. -* **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: +`setNonce()` is deprecated and will be removed in 5.0; calling it triggers an `E_USER_DEPRECATED` +notice. While a nonce is set, the cipher behaves as before: it uses that nonce for every message and +does not store it with the ciphertext. Only use it to decrypt data that was encrypted that way, and +re-encrypt such data without a nonce: ```php -$nonce = random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES); -$cipher->setNonce($nonce); -$stored = base64_encode($nonce) . ':' . base64_encode($cipher->encrypt($message, $key)); +$legacy = new Sodium(); +$legacy->setNonce($storedNonce); + +$ciphertext = (new Sodium())->encrypt($legacy->decrypt($oldCiphertext, $key), $key); ``` +A nonce of the wrong length is rejected with an `EncryptionException` or `DecryptionException`. + ## The OpenSSL cipher > **Do not use `Cipher\OpenSSL` for new work.** Its initialisation vector is fixed at construction diff --git a/src/Cipher/Sodium.php b/src/Cipher/Sodium.php index bae797f0..b16e48df 100644 --- a/src/Cipher/Sodium.php +++ b/src/Cipher/Sodium.php @@ -28,6 +28,8 @@ class Sodium implements CipherInterface /** * The message nonce to be used with encryption/decryption * + * When no nonce is set, a random nonce is generated for every message and stored in front of the ciphertext. + * * @var string * @since 1.4.0 */ @@ -52,14 +54,27 @@ public function decrypt($data, Key $key) throw new InvalidKeyTypeException('sodium', $key->getType()); } - if (!$this->nonce) { - throw new DecryptionException('Missing nonce to decrypt data'); + if ($this->nonce) { + // Data encrypted with a nonce set through the deprecated setNonce() + $nonce = $this->nonce; + } else { + // 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); + } + + if (\strlen($nonce) !== SODIUM_CRYPTO_BOX_NONCEBYTES) { + throw new DecryptionException(\sprintf('The nonce must be %d bytes long.', 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 +107,22 @@ public function encrypt($data, Key $key) throw new InvalidKeyTypeException('sodium', $key->getType()); } - if (!$this->nonce) { - throw new EncryptionException('Missing nonce to decrypt data'); + // Without a nonce set through the deprecated setNonce(), use a random nonce and store it with the ciphertext + $nonce = $this->nonce ?: random_bytes(SODIUM_CRYPTO_BOX_NONCEBYTES); + $prefix = $this->nonce ? '' : $nonce; + + if (\strlen($nonce) !== SODIUM_CRYPTO_BOX_NONCEBYTES) { + throw new EncryptionException(\sprintf('The nonce must be %d bytes long.', SODIUM_CRYPTO_BOX_NONCEBYTES)); } try { - return sodium_crypto_box( + return $prefix . 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); } } @@ -146,14 +165,26 @@ public static function isSupported(): bool /** * Set the nonce to use for encrypting/decrypting messages * + * Once a nonce is set, it is used for every message and not stored with the ciphertext. Reusing a nonce with the + * same key is insecure. Without a nonce, encrypt() generates a random one per message. + * * @param string $nonce The message nonce * * @return void * * @since 1.4.0 + * @deprecated 5.0 Do not set a nonce; encrypt() generates a random nonce for every message. Only use this method + * to decrypt data that was encrypted with a fixed nonce. */ public function setNonce($nonce) { + trigger_deprecation( + 'joomla/crypt', + '__DEPLOY_VERSION__', + '%s() is deprecated and will be removed in 5.0. Do not set a nonce; encrypt() generates a random nonce for every message.', + __METHOD__ + ); + $this->nonce = $nonce; } }