Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 60 additions & 23 deletions Tests/Cipher/SodiumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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'));
}
}
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
26 changes: 8 additions & 18 deletions docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,33 +105,23 @@ 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;

$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

Expand Down
39 changes: 39 additions & 0 deletions docs/v4-to-v5-update.md
Original file line number Diff line number Diff line change
@@ -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.

<!-- Section: Crypt requires a cipher and a key -->


<!-- Section: native parameter and return types -->


## `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` |
43 changes: 12 additions & 31 deletions src/Cipher/Sodium.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -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())
);

Expand Down Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -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;
}
}
Loading