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
70 changes: 32 additions & 38 deletions system/Encryption/Handlers/SodiumHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use CodeIgniter\Encryption\Exceptions\EncryptionException;
use SensitiveParameter;
use SodiumException;

/**
* SodiumHandler uses libsodium in encryption.
Expand Down Expand Up @@ -43,34 +44,31 @@ class SodiumHandler extends BaseHandler
*/
public function encrypt(#[SensitiveParameter] $data, #[SensitiveParameter] $params = null)
{
// Allow key override
$key = $params !== null
? (is_array($params) && isset($params['key']) ? $params['key'] : $params)
: $this->key;

// Allow blockSize override
$blockSize = (is_array($params) && isset($params['blockSize']))
? $params['blockSize']
: $this->blockSize;
$key = $this->key;
$blockSize = $this->blockSize;

if ($params !== null) {
if (is_array($params)) {
$key = $params['key'] ?? $key;
$blockSize = $params['blockSize'] ?? $blockSize;
} else {
$key = $params;
}
}

if (empty($key)) {
if (empty($key) || strlen((string) $key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
throw EncryptionException::forNeedsStarterKey();
}

// create a nonce for this operation
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // 24 bytes

// add padding before we encrypt the data
if ($blockSize <= 0) {
throw EncryptionException::forEncryptionFailed();
}

$data = sodium_pad($data, $blockSize);
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$data = sodium_pad($data, $blockSize);

// encrypt message and combine with nonce
$ciphertext = $nonce . sodium_crypto_secretbox($data, $nonce, $key);

// cleanup buffers
sodium_memzero($data);
sodium_memzero($key);
Comment thread
michalsn marked this conversation as resolved.

Expand All @@ -82,45 +80,41 @@ public function encrypt(#[SensitiveParameter] $data, #[SensitiveParameter] $para
*/
public function decrypt($data, #[SensitiveParameter] $params = null)
{
// Allow key override
$key = $params !== null
? (is_array($params) && isset($params['key']) ? $params['key'] : $params)
: $this->key;

// Allow blockSize override
$blockSize = (is_array($params) && isset($params['blockSize']))
? $params['blockSize']
: $this->blockSize;
$key = $this->key;
$blockSize = $this->blockSize;

if ($params !== null) {
if (is_array($params)) {
$key = $params['key'] ?? $key;
$blockSize = $params['blockSize'] ?? $blockSize;
} else {
$key = $params;
}
}

if (empty($key)) {
if (empty($key) || strlen((string) $key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
throw EncryptionException::forNeedsStarterKey();
}

if (mb_strlen($data, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
// message was truncated
throw EncryptionException::forAuthenticationFailed();
}

// Extract info from encrypted data
$nonce = self::substr($data, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = self::substr($data, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);

// decrypt data
$data = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);

if ($data === false) {
// message was tampered in transit
throw EncryptionException::forAuthenticationFailed(); // @codeCoverageIgnore
if ($data === false || $blockSize <= 0) {
throw EncryptionException::forAuthenticationFailed();
}

// remove extra padding during encryption
if ($blockSize <= 0) {
try {
$data = sodium_unpad($data, $blockSize);
} catch (SodiumException) {
throw EncryptionException::forAuthenticationFailed();
}

$data = sodium_unpad($data, $blockSize);

// cleanup buffers
sodium_memzero($ciphertext);
sodium_memzero($key);
Comment thread
michalsn marked this conversation as resolved.

Expand Down
53 changes: 53 additions & 0 deletions tests/system/Encryption/Handlers/SodiumHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,4 +151,57 @@ public function testInternalKeyNotModifiedByParams(): void

$this->assertSame($message, $encrypter->decrypt($encoded, ['key' => $differentKey]));
}

public function testNullKeyOverrideFallsBackToInstanceKey(): void
{
/** @var SodiumHandler $encrypter */
$encrypter = $this->encryption->initialize($this->config);

$ciphertext = $encrypter->encrypt('message', ['key' => null]);

$this->assertSame('message', $encrypter->decrypt($ciphertext, ['key' => null]));
}

public function testInvalidKeyLengthThrowsEncryptionException(): void
{
$this->expectException(EncryptionException::class);
/** @var SodiumHandler $encrypter */
$encrypter = $this->encryption->initialize($this->config);

$encrypter->encrypt('message', str_repeat('a', 31));
}

public function testMismatchedBlockSizeThrowsEncryptionException(): void
{
$this->expectException(EncryptionException::class);
/** @var SodiumHandler $encrypter */
$encrypter = $this->encryption->initialize($this->config);

$ciphertext = $encrypter->encrypt('message', ['blockSize' => 16]);

$encrypter->decrypt($ciphertext, ['blockSize' => 32]);
}

public function testDecryptTamperedMessageThrowsException(): void
{
$this->expectException(EncryptionException::class);
$encrypter = $this->encryption->initialize($this->config);

$ciphertext = $encrypter->encrypt('message');

$ciphertext[0] = $ciphertext[0] === 'a' ? 'b' : 'a';

$encrypter->decrypt($ciphertext);
}

public function testOverrideKeyAsStringWorks(): void
{
$encrypter = $this->encryption->initialize($this->config);
$newKey = sodium_crypto_secretbox_keygen();

$ciphertext = $encrypter->encrypt('message', $newKey);
$decrypted = $encrypter->decrypt($ciphertext, $newKey);

$this->assertSame('message', $decrypted);
}
}
Loading