From 95980a1bb1199d1254afec0fddceb0f9b605b5df Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Tue, 29 Sep 2026 09:52:29 +0100 Subject: [PATCH 1/4] Support encryption key rotation via an encryption_key list [security] encryption_key now also accepts a list of keys. The first entry is the current key and is used for all encryption; later entries are decrypt-only previous keys, tried in order when the current key fails. A plain string or a single-entry list builds the same single-key Encrypter as before. Empty later entries are ignored. An empty first entry throws rather than promoting a previous key, so an unset env var cannot cause new data to be encrypted with a retired key. Every key is validated at construction. Co-Authored-By: Claude Opus 5.5 --- src/Encryption/RotatingEncrypter.php | 87 +++++++++++++++ .../Services/EncryptionService.php | 67 +++++++++++- .../Encryption/RotatingEncrypterTest.php | 62 +++++++++++ .../Services/EncryptionServiceTest.php | 101 +++++++++++++++++- 4 files changed, 310 insertions(+), 7 deletions(-) create mode 100644 src/Encryption/RotatingEncrypter.php create mode 100644 tests/Cubex/Encryption/RotatingEncrypterTest.php diff --git a/src/Encryption/RotatingEncrypter.php b/src/Encryption/RotatingEncrypter.php new file mode 100644 index 0000000..e283e79 --- /dev/null +++ b/src/Encryption/RotatingEncrypter.php @@ -0,0 +1,87 @@ +_current = $current; + $this->_previous = []; + foreach($previous as $encrypter) + { + $this->_addPrevious($encrypter); + } + } + + protected function _addPrevious(Encrypter $encrypter) + { + $this->_previous[] = $encrypter; + } + + public function encrypt($value, $serialize = true) + { + return $this->_current->encrypt($value, $serialize); + } + + public function decrypt($payload, $unserialize = true) + { + try + { + return $this->_current->decrypt($payload, $unserialize); + } + catch(DecryptException $e) + { + foreach($this->_previous as $encrypter) + { + try + { + return $encrypter->decrypt($payload, $unserialize); + } + catch(DecryptException $previousFailure) + { + } + } + throw $e; + } + } + + /** + * The current encryption key + * + * @return string|null + */ + public function getKey() + { + return method_exists($this->_current, 'getKey') + ? $this->_current->getKey() : null; + } +} diff --git a/src/ServiceManager/Services/EncryptionService.php b/src/ServiceManager/Services/EncryptionService.php index 61568ed..4634b0d 100644 --- a/src/ServiceManager/Services/EncryptionService.php +++ b/src/ServiceManager/Services/EncryptionService.php @@ -2,13 +2,25 @@ namespace Cubex\ServiceManager\Services; use Cubex\Cubex; +use Cubex\Encryption\RotatingEncrypter; use Illuminate\Encryption\Encrypter; class EncryptionService extends AbstractServiceProvider { + const DEFAULT_KEY = 'mR?u7DP30sj5Djdf'; + /** * Register the service * + * [security] encryption_key is either a single key, or a list of keys for + * rotation: + * + * encryption_key[] = + * encryption_key[] = + * + * The first entry encrypts; later entries are decrypt-only previous keys, + * see RotatingEncrypter for the security implications. + * * @param array $parameters * * @return mixed @@ -19,15 +31,66 @@ public function register(array $parameters = null) 'encrypter', function (Cubex $cubex) { - return new Encrypter( + return static::createEncrypter( $cubex->getConfiguration()->getItem( 'security', 'encryption_key', - 'mR?u7DP30sj5Djdf' + self::DEFAULT_KEY ) ); }, true ); } + + /** + * @param string|string[] $keys a key, or a list of keys with the current + * key first. Empty previous keys are ignored. + * + * @return \Illuminate\Contracts\Encryption\Encrypter + * + * @throws \RuntimeException when the current key is empty or any key is not + * a valid length for the cipher + */ + public static function createEncrypter($keys) + { + if(!is_array($keys)) + { + return new Encrypter($keys); + } + + $keys = array_values($keys); + if(empty($keys)) + { + return new Encrypter(self::DEFAULT_KEY); + } + + $current = (string)$keys[0]; + $previous = array_values( + array_filter(array_map('strval', array_slice($keys, 1)), 'strlen') + ); + + // An empty first entry is usually an unset environment variable. It is + // rejected rather than replaced by the next entry, which would encrypt + // new data with a key that is being retired. + if($current === '') + { + throw new \RuntimeException( + 'The first encryption_key entry is the current key and must not be empty.' + ); + } + + $currentEncrypter = new Encrypter($current); + if(empty($previous)) + { + return $currentEncrypter; + } + + $previousEncrypters = []; + foreach($previous as $key) + { + $previousEncrypters[] = new Encrypter($key); + } + return new RotatingEncrypter($currentEncrypter, $previousEncrypters); + } } diff --git a/tests/Cubex/Encryption/RotatingEncrypterTest.php b/tests/Cubex/Encryption/RotatingEncrypterTest.php new file mode 100644 index 0000000..b39eda0 --- /dev/null +++ b/tests/Cubex/Encryption/RotatingEncrypterTest.php @@ -0,0 +1,62 @@ +_rotating()->encrypt('value'); + $this->assertEquals('value', (new Encrypter(self::CURRENT))->decrypt($payload)); + } + + public function testDecryptsCurrentKey() + { + $rotating = $this->_rotating(); + $this->assertEquals('value', $rotating->decrypt($rotating->encrypt('value'))); + $this->assertEquals( + 'raw', + $rotating->decrypt($rotating->encrypt('raw', false), false) + ); + } + + public function testDecryptsPreviousKeys() + { + $rotating = $this->_rotating(); + $this->assertEquals( + 'older', + $rotating->decrypt((new Encrypter(self::OLDER))->encrypt('older')) + ); + $this->assertEquals( + 'oldest', + $rotating->decrypt((new Encrypter(self::OLDEST))->encrypt('oldest', false), false) + ); + } + + public function testThrowsWhenNoKeyMatches() + { + $payload = (new Encrypter('unknown-key-0004'))->encrypt('value'); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + $this->_rotating()->decrypt($payload); + } + + public function testGetKeyReturnsCurrentKey() + { + $this->assertEquals(self::CURRENT, $this->_rotating()->getKey()); + } +} diff --git a/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php b/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php index 7dbaf89..a546173 100644 --- a/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php +++ b/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php @@ -2,29 +2,120 @@ namespace CubexTest\Cubex\ServiceManager\Services; use Cubex\Cubex; +use Cubex\Encryption\RotatingEncrypter; use Cubex\ServiceManager\Services\EncryptionService; +use Illuminate\Encryption\Encrypter; use Packaged\Config\Provider\ConfigSection; use Packaged\Config\Provider\Test\TestConfigProvider; use PHPUnit\Framework\TestCase; class EncryptionServiceTest extends TestCase { - public function testRegisterCreatesEncrypter() + const CURRENT = 'current-key-0001'; + const OLDER = 'older-key-000002'; + + protected function _encrypter($key = null) { + $config = new TestConfigProvider(); + if($key !== null) + { + $config->addItem('security', 'encryption_key', $key); + } $cubex = new Cubex(); - $cubex->configure(new TestConfigProvider()); + $cubex->configure($config); $encryptionService = new EncryptionService(); + $encryptionService->boot($cubex, new ConfigSection()); + $encryptionService->register(); + return $cubex->make('encrypter'); + } + public function testRegisterCreatesEncrypter() + { + $encryptionService = new EncryptionService(); $this->assertInstanceOf( '\Cubex\ServiceManager\IServiceProvider', $encryptionService ); - $encryptionService->boot($cubex, new ConfigSection()); + $encrypter = $this->_encrypter(); + $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); + $this->assertEquals(EncryptionService::DEFAULT_KEY, $encrypter->getKey()); + } - $encryptionService->register(); + public function testStringKey() + { + $encrypter = $this->_encrypter(self::CURRENT); + $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + } - $encrypter = $cubex->make('encrypter'); + public function testSingleEntryArrayMatchesString() + { + $encrypter = $this->_encrypter([self::CURRENT]); $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + + $encrypter = $this->_encrypter([self::CURRENT, '', null]); + $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + } + + public function testEmptyArrayUsesDefaultKey() + { + $this->assertEquals( + EncryptionService::DEFAULT_KEY, + $this->_encrypter([])->getKey() + ); + } + + public function testArrayRotatesKeys() + { + $encrypter = $this->_encrypter([self::CURRENT, '', self::OLDER]); + $this->assertInstanceOf(RotatingEncrypter::class, $encrypter); + + // first entry encrypts + $payload = $encrypter->encrypt('new'); + $this->assertEquals('new', (new Encrypter(self::CURRENT))->decrypt($payload)); + + // later entries decrypt + $this->assertEquals( + 'old', + $encrypter->decrypt((new Encrypter(self::OLDER))->encrypt('old')) + ); + } + + public function testArrayThrowsWhenNoKeyMatches() + { + $encrypter = $this->_encrypter([self::CURRENT, self::OLDER]); + $payload = (new Encrypter('unknown-key-0004'))->encrypt('value'); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + $encrypter->decrypt($payload); + } + + public function testEmptyFirstEntryWithPreviousKeysThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('current key'); + $this->_encrypter(['', self::OLDER]); + } + + public function testEmptyOnlyEntryThrows() + { + $this->expectException('\RuntimeException'); + $this->_encrypter(['']); + } + + public function testInvalidPreviousKeyLengthThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('correct key lengths'); + $this->_encrypter([self::CURRENT, 'too-short']); + } + + public function testInvalidCurrentKeyLengthThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('correct key lengths'); + $this->_encrypter(['too-short', self::OLDER]); } } From b569c5c878540a1a013c55cf6966b2db5f83b32a Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Tue, 29 Sep 2026 09:57:40 +0100 Subject: [PATCH 2/4] Make key rotation part of a single Cubex Encrypter Replace RotatingEncrypter with Cubex\Encryption\Encrypter, which extends Illuminate's Encrypter and accepts either a key or a list of keys. The first key encrypts and is tried first on decrypt; later keys are decrypt-only fallbacks. EncryptionService always binds it, so string and list config share one class and instanceof Illuminate's Encrypter holds. Co-Authored-By: Claude Opus 5.5 --- src/Encryption/Encrypter.php | 91 ++++++++++++ src/Encryption/RotatingEncrypter.php | 87 ------------ .../Services/EncryptionService.php | 70 +-------- tests/Cubex/Encryption/EncrypterTest.php | 133 ++++++++++++++++++ .../Encryption/RotatingEncrypterTest.php | 62 -------- .../Services/EncryptionServiceTest.php | 79 +++-------- 6 files changed, 248 insertions(+), 274 deletions(-) create mode 100644 src/Encryption/Encrypter.php delete mode 100644 src/Encryption/RotatingEncrypter.php create mode 100644 tests/Cubex/Encryption/EncrypterTest.php delete mode 100644 tests/Cubex/Encryption/RotatingEncrypterTest.php diff --git a/src/Encryption/Encrypter.php b/src/Encryption/Encrypter.php new file mode 100644 index 0000000..10c4a7f --- /dev/null +++ b/src/Encryption/Encrypter.php @@ -0,0 +1,91 @@ +_fallbacks[] = new IlluminateEncrypter($fallback, $cipher); + } + } + } + + public function decrypt($payload, $unserialize = true) + { + try + { + return parent::decrypt($payload, $unserialize); + } + catch(DecryptException $e) + { + foreach($this->_fallbacks as $fallback) + { + try + { + return $fallback->decrypt($payload, $unserialize); + } + catch(DecryptException $fallbackFailure) + { + } + } + throw $e; + } + } +} diff --git a/src/Encryption/RotatingEncrypter.php b/src/Encryption/RotatingEncrypter.php deleted file mode 100644 index e283e79..0000000 --- a/src/Encryption/RotatingEncrypter.php +++ /dev/null @@ -1,87 +0,0 @@ -_current = $current; - $this->_previous = []; - foreach($previous as $encrypter) - { - $this->_addPrevious($encrypter); - } - } - - protected function _addPrevious(Encrypter $encrypter) - { - $this->_previous[] = $encrypter; - } - - public function encrypt($value, $serialize = true) - { - return $this->_current->encrypt($value, $serialize); - } - - public function decrypt($payload, $unserialize = true) - { - try - { - return $this->_current->decrypt($payload, $unserialize); - } - catch(DecryptException $e) - { - foreach($this->_previous as $encrypter) - { - try - { - return $encrypter->decrypt($payload, $unserialize); - } - catch(DecryptException $previousFailure) - { - } - } - throw $e; - } - } - - /** - * The current encryption key - * - * @return string|null - */ - public function getKey() - { - return method_exists($this->_current, 'getKey') - ? $this->_current->getKey() : null; - } -} diff --git a/src/ServiceManager/Services/EncryptionService.php b/src/ServiceManager/Services/EncryptionService.php index 4634b0d..2411082 100644 --- a/src/ServiceManager/Services/EncryptionService.php +++ b/src/ServiceManager/Services/EncryptionService.php @@ -2,8 +2,7 @@ namespace Cubex\ServiceManager\Services; use Cubex\Cubex; -use Cubex\Encryption\RotatingEncrypter; -use Illuminate\Encryption\Encrypter; +use Cubex\Encryption\Encrypter; class EncryptionService extends AbstractServiceProvider { @@ -13,14 +12,11 @@ class EncryptionService extends AbstractServiceProvider * Register the service * * [security] encryption_key is either a single key, or a list of keys for - * rotation: + * rotation, see Encrypter: * * encryption_key[] = * encryption_key[] = * - * The first entry encrypts; later entries are decrypt-only previous keys, - * see RotatingEncrypter for the security implications. - * * @param array $parameters * * @return mixed @@ -31,66 +27,14 @@ public function register(array $parameters = null) 'encrypter', function (Cubex $cubex) { - return static::createEncrypter( - $cubex->getConfiguration()->getItem( - 'security', - 'encryption_key', - self::DEFAULT_KEY - ) + $key = $cubex->getConfiguration()->getItem( + 'security', + 'encryption_key', + self::DEFAULT_KEY ); + return new Encrypter($key === [] ? self::DEFAULT_KEY : $key); }, true ); } - - /** - * @param string|string[] $keys a key, or a list of keys with the current - * key first. Empty previous keys are ignored. - * - * @return \Illuminate\Contracts\Encryption\Encrypter - * - * @throws \RuntimeException when the current key is empty or any key is not - * a valid length for the cipher - */ - public static function createEncrypter($keys) - { - if(!is_array($keys)) - { - return new Encrypter($keys); - } - - $keys = array_values($keys); - if(empty($keys)) - { - return new Encrypter(self::DEFAULT_KEY); - } - - $current = (string)$keys[0]; - $previous = array_values( - array_filter(array_map('strval', array_slice($keys, 1)), 'strlen') - ); - - // An empty first entry is usually an unset environment variable. It is - // rejected rather than replaced by the next entry, which would encrypt - // new data with a key that is being retired. - if($current === '') - { - throw new \RuntimeException( - 'The first encryption_key entry is the current key and must not be empty.' - ); - } - - $currentEncrypter = new Encrypter($current); - if(empty($previous)) - { - return $currentEncrypter; - } - - $previousEncrypters = []; - foreach($previous as $key) - { - $previousEncrypters[] = new Encrypter($key); - } - return new RotatingEncrypter($currentEncrypter, $previousEncrypters); - } } diff --git a/tests/Cubex/Encryption/EncrypterTest.php b/tests/Cubex/Encryption/EncrypterTest.php new file mode 100644 index 0000000..0d4d617 --- /dev/null +++ b/tests/Cubex/Encryption/EncrypterTest.php @@ -0,0 +1,133 @@ +assertInstanceOf(IlluminateEncrypter::class, new Encrypter(self::CURRENT)); + $this->assertInstanceOf(IlluminateEncrypter::class, $this->_rotating()); + } + + public function testStringKeyUnchanged() + { + $encrypter = new Encrypter(self::CURRENT); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + $payload = $encrypter->encrypt('value'); + $this->assertEquals('value', (new IlluminateEncrypter(self::CURRENT))->decrypt($payload)); + $this->assertEquals( + 'value', + $encrypter->decrypt((new IlluminateEncrypter(self::CURRENT))->encrypt('value')) + ); + } + + public function testStringKeyNoMatchThrows() + { + $payload = (new IlluminateEncrypter(self::OLDER))->encrypt('value'); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + (new Encrypter(self::CURRENT))->decrypt($payload); + } + + public function testFirstEntryEncrypts() + { + $encrypter = $this->_rotating(); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + $payload = $encrypter->encrypt('value'); + $this->assertEquals('value', (new IlluminateEncrypter(self::CURRENT))->decrypt($payload)); + $this->assertEquals('value', $encrypter->decrypt($payload)); + $this->assertEquals('raw', $encrypter->decryptString($encrypter->encryptString('raw'))); + } + + public function testFallbackKeysDecrypt() + { + $encrypter = $this->_rotating(); + $this->assertEquals( + 'older', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('older')) + ); + $this->assertEquals( + 'oldest', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDEST))->encrypt('oldest', false), false) + ); + } + + public function testNoKeyMatchesThrows() + { + $payload = (new IlluminateEncrypter('unknown-key-0004'))->encrypt('value'); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + $this->_rotating()->decrypt($payload); + } + + public function testEmptyFallbacksIgnored() + { + $encrypter = new Encrypter([self::CURRENT, '', null, self::OLDER]); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + $this->assertEquals( + 'older', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('older')) + ); + } + + public function testSingleEntryArrayMatchesString() + { + $encrypter = new Encrypter([self::CURRENT]); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + $payload = (new IlluminateEncrypter(self::OLDER))->encrypt('value'); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + $encrypter->decrypt($payload); + } + + public function testEmptyFirstEntryThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('current key'); + new Encrypter(['', self::OLDER]); + } + + public function testAllEmptyThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('current key'); + new Encrypter(['', '']); + } + + public function testInvalidFallbackKeyLengthThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('correct key lengths'); + new Encrypter([self::CURRENT, 'too-short']); + } + + public function testInvalidCurrentKeyLengthThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('correct key lengths'); + new Encrypter(['too-short', self::OLDER]); + } + + public function testCipherAppliesToAllKeys() + { + $current = str_repeat('a', 32); + $older = str_repeat('b', 32); + $encrypter = new Encrypter([$current, $older], 'AES-256-CBC'); + $this->assertEquals( + 'older', + $encrypter->decrypt((new IlluminateEncrypter($older, 'AES-256-CBC'))->encrypt('older')) + ); + $this->expectException('\RuntimeException'); + new Encrypter([$current, self::OLDER], 'AES-256-CBC'); + } +} diff --git a/tests/Cubex/Encryption/RotatingEncrypterTest.php b/tests/Cubex/Encryption/RotatingEncrypterTest.php deleted file mode 100644 index b39eda0..0000000 --- a/tests/Cubex/Encryption/RotatingEncrypterTest.php +++ /dev/null @@ -1,62 +0,0 @@ -_rotating()->encrypt('value'); - $this->assertEquals('value', (new Encrypter(self::CURRENT))->decrypt($payload)); - } - - public function testDecryptsCurrentKey() - { - $rotating = $this->_rotating(); - $this->assertEquals('value', $rotating->decrypt($rotating->encrypt('value'))); - $this->assertEquals( - 'raw', - $rotating->decrypt($rotating->encrypt('raw', false), false) - ); - } - - public function testDecryptsPreviousKeys() - { - $rotating = $this->_rotating(); - $this->assertEquals( - 'older', - $rotating->decrypt((new Encrypter(self::OLDER))->encrypt('older')) - ); - $this->assertEquals( - 'oldest', - $rotating->decrypt((new Encrypter(self::OLDEST))->encrypt('oldest', false), false) - ); - } - - public function testThrowsWhenNoKeyMatches() - { - $payload = (new Encrypter('unknown-key-0004'))->encrypt('value'); - $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); - $this->_rotating()->decrypt($payload); - } - - public function testGetKeyReturnsCurrentKey() - { - $this->assertEquals(self::CURRENT, $this->_rotating()->getKey()); - } -} diff --git a/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php b/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php index a546173..cd52a8a 100644 --- a/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php +++ b/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php @@ -2,9 +2,9 @@ namespace CubexTest\Cubex\ServiceManager\Services; use Cubex\Cubex; -use Cubex\Encryption\RotatingEncrypter; +use Cubex\Encryption\Encrypter; use Cubex\ServiceManager\Services\EncryptionService; -use Illuminate\Encryption\Encrypter; +use Illuminate\Encryption\Encrypter as IlluminateEncrypter; use Packaged\Config\Provider\ConfigSection; use Packaged\Config\Provider\Test\TestConfigProvider; use PHPUnit\Framework\TestCase; @@ -31,35 +31,17 @@ protected function _encrypter($key = null) public function testRegisterCreatesEncrypter() { - $encryptionService = new EncryptionService(); $this->assertInstanceOf( '\Cubex\ServiceManager\IServiceProvider', - $encryptionService + new EncryptionService() ); $encrypter = $this->_encrypter(); - $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); + $this->assertInstanceOf(Encrypter::class, $encrypter); + $this->assertInstanceOf(IlluminateEncrypter::class, $encrypter); $this->assertEquals(EncryptionService::DEFAULT_KEY, $encrypter->getKey()); } - public function testStringKey() - { - $encrypter = $this->_encrypter(self::CURRENT); - $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); - $this->assertEquals(self::CURRENT, $encrypter->getKey()); - } - - public function testSingleEntryArrayMatchesString() - { - $encrypter = $this->_encrypter([self::CURRENT]); - $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); - $this->assertEquals(self::CURRENT, $encrypter->getKey()); - - $encrypter = $this->_encrypter([self::CURRENT, '', null]); - $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); - $this->assertEquals(self::CURRENT, $encrypter->getKey()); - } - public function testEmptyArrayUsesDefaultKey() { $this->assertEquals( @@ -68,54 +50,27 @@ public function testEmptyArrayUsesDefaultKey() ); } - public function testArrayRotatesKeys() + public function testStringKey() { - $encrypter = $this->_encrypter([self::CURRENT, '', self::OLDER]); - $this->assertInstanceOf(RotatingEncrypter::class, $encrypter); - - // first entry encrypts - $payload = $encrypter->encrypt('new'); - $this->assertEquals('new', (new Encrypter(self::CURRENT))->decrypt($payload)); - - // later entries decrypt - $this->assertEquals( - 'old', - $encrypter->decrypt((new Encrypter(self::OLDER))->encrypt('old')) - ); + $encrypter = $this->_encrypter(self::CURRENT); + $this->assertInstanceOf(Encrypter::class, $encrypter); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); } - public function testArrayThrowsWhenNoKeyMatches() + public function testArrayKeys() { $encrypter = $this->_encrypter([self::CURRENT, self::OLDER]); - $payload = (new Encrypter('unknown-key-0004'))->encrypt('value'); - $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); - $encrypter->decrypt($payload); + $this->assertInstanceOf(Encrypter::class, $encrypter); + $this->assertEquals(self::CURRENT, $encrypter->getKey()); + $this->assertEquals( + 'old', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('old')) + ); } - public function testEmptyFirstEntryWithPreviousKeysThrows() + public function testEmptyFirstEntryThrows() { $this->expectException('\RuntimeException'); - $this->expectExceptionMessage('current key'); $this->_encrypter(['', self::OLDER]); } - - public function testEmptyOnlyEntryThrows() - { - $this->expectException('\RuntimeException'); - $this->_encrypter(['']); - } - - public function testInvalidPreviousKeyLengthThrows() - { - $this->expectException('\RuntimeException'); - $this->expectExceptionMessage('correct key lengths'); - $this->_encrypter([self::CURRENT, 'too-short']); - } - - public function testInvalidCurrentKeyLengthThrows() - { - $this->expectException('\RuntimeException'); - $this->expectExceptionMessage('correct key lengths'); - $this->_encrypter(['too-short', self::OLDER]); - } } From 127258840eb3d4f76e762ecd6d7f6fd3f9a27f2a Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Tue, 29 Sep 2026 10:03:59 +0100 Subject: [PATCH 3/4] Add security.encryption_cipher, per key when a list encryption_cipher defaults to AES-128-CBC. It is either one cipher for every key or a list aligned by index with encryption_key, so a rotation can move to AES-256-CBC while the previous key stays AES-128-CBC. A list must have one entry per key entry, including empty ones; a list with a single string key throws; an empty cipher entry is the default. decrypt() now keeps the first failure while trying each key, so no catch variable goes unused. Co-Authored-By: Claude Opus 5.5 --- src/Encryption/Encrypter.php | 84 +++++++++++++------ .../Services/EncryptionService.php | 18 ++-- tests/Cubex/Encryption/EncrypterTest.php | 78 +++++++++++++++++ .../Services/EncryptionServiceTest.php | 42 +++++++++- 4 files changed, 191 insertions(+), 31 deletions(-) diff --git a/src/Encryption/Encrypter.php b/src/Encryption/Encrypter.php index 10c4a7f..0d61134 100644 --- a/src/Encryption/Encrypter.php +++ b/src/Encryption/Encrypter.php @@ -13,6 +13,10 @@ * and tried first on decrypt. Later keys are decrypt-only fallbacks, tried in * order when the current key fails. * + * The cipher is either one cipher for every key, or a list aligned by index + * with the keys, so a rotation can also change cipher. An empty cipher is the + * default AES-128-CBC. + * * A key is normally rotated because it is compromised, so anything that * decrypts with a fallback key may have been forged by whoever holds that * key. Keep the rotation window short, remove fallback keys once it ends, @@ -22,6 +26,8 @@ */ class Encrypter extends IlluminateEncrypter { + const DEFAULT_CIPHER = 'AES-128-CBC'; + /** * @var IlluminateEncrypter[] */ @@ -30,62 +36,90 @@ class Encrypter extends IlluminateEncrypter /** * @param string|string[] $key a key, or a list of keys with the current * key first. Empty fallback keys are ignored. - * @param string $cipher + * @param string|string[] $cipher a cipher for every key, or a list with one + * entry per key entry (including empty ones) * - * @throws \RuntimeException when the current key is empty in a list, or any - * key is not a valid length for the cipher + * @throws \RuntimeException when the current key is empty in a list, the + * cipher list does not match the key list, or a + * key is not valid for its cipher */ - public function __construct($key, $cipher = 'AES-128-CBC') + public function __construct($key, $cipher = self::DEFAULT_CIPHER) { if(!is_array($key)) { - parent::__construct($key, $cipher); + if(is_array($cipher)) + { + throw new \RuntimeException( + 'A list of encryption ciphers requires a list of encryption keys.' + ); + } + parent::__construct($key, static::_cipher($cipher)); return; } $keys = array_map('strval', array_values($key)); - $current = isset($keys[0]) ? $keys[0] : ''; + if(is_array($cipher)) + { + $ciphers = array_values($cipher); + if(count($ciphers) !== count($keys)) + { + throw new \RuntimeException( + 'The encryption cipher list must have one entry per encryption key.' + ); + } + } + else + { + $ciphers = array_fill(0, count($keys), $cipher); + } // An empty first entry is usually an unset environment variable. It is // rejected rather than replaced by the next entry, which would encrypt // new data with a key that is being retired. - if($current === '') + if(!isset($keys[0]) || $keys[0] === '') { throw new \RuntimeException( 'The first encryption key is the current key and must not be empty.' ); } - parent::__construct($current, $cipher); + parent::__construct($keys[0], static::_cipher($ciphers[0])); - foreach(array_slice($keys, 1) as $fallback) + for($i = 1; $i < count($keys); $i++) { - if($fallback !== '') + if($keys[$i] !== '') { - $this->_fallbacks[] = new IlluminateEncrypter($fallback, $cipher); + $this->_fallbacks[] = new IlluminateEncrypter( + $keys[$i], + static::_cipher($ciphers[$i]) + ); } } } + protected static function _cipher($cipher) + { + $cipher = (string)$cipher; + return $cipher === '' ? self::DEFAULT_CIPHER : $cipher; + } + public function decrypt($payload, $unserialize = true) { - try + $failure = null; + // null is the current key, handled by the parent + foreach(array_merge([null], $this->_fallbacks) as $fallback) { - return parent::decrypt($payload, $unserialize); - } - catch(DecryptException $e) - { - foreach($this->_fallbacks as $fallback) + try + { + return $fallback === null + ? parent::decrypt($payload, $unserialize) + : $fallback->decrypt($payload, $unserialize); + } + catch(DecryptException $e) { - try - { - return $fallback->decrypt($payload, $unserialize); - } - catch(DecryptException $fallbackFailure) - { - } + $failure = $failure ?: $e; } - throw $e; } + throw $failure; } } diff --git a/src/ServiceManager/Services/EncryptionService.php b/src/ServiceManager/Services/EncryptionService.php index 2411082..8221aa1 100644 --- a/src/ServiceManager/Services/EncryptionService.php +++ b/src/ServiceManager/Services/EncryptionService.php @@ -12,10 +12,13 @@ class EncryptionService extends AbstractServiceProvider * Register the service * * [security] encryption_key is either a single key, or a list of keys for - * rotation, see Encrypter: + * rotation. encryption_cipher is optional (default AES-128-CBC), either one + * cipher for every key or a list aligned with encryption_key. See Encrypter. * * encryption_key[] = * encryption_key[] = + * encryption_cipher[] = AES-256-CBC + * encryption_cipher[] = AES-128-CBC * * @param array $parameters * @@ -27,12 +30,17 @@ public function register(array $parameters = null) 'encrypter', function (Cubex $cubex) { - $key = $cubex->getConfiguration()->getItem( + $config = $cubex->getConfiguration(); + $key = $config->getItem('security', 'encryption_key', self::DEFAULT_KEY); + $cipher = $config->getItem( 'security', - 'encryption_key', - self::DEFAULT_KEY + 'encryption_cipher', + Encrypter::DEFAULT_CIPHER + ); + return new Encrypter( + $key === [] ? self::DEFAULT_KEY : $key, + $cipher === [] ? Encrypter::DEFAULT_CIPHER : $cipher ); - return new Encrypter($key === [] ? self::DEFAULT_KEY : $key); }, true ); diff --git a/tests/Cubex/Encryption/EncrypterTest.php b/tests/Cubex/Encryption/EncrypterTest.php index 0d4d617..dbbf3d3 100644 --- a/tests/Cubex/Encryption/EncrypterTest.php +++ b/tests/Cubex/Encryption/EncrypterTest.php @@ -130,4 +130,82 @@ public function testCipherAppliesToAllKeys() $this->expectException('\RuntimeException'); new Encrypter([$current, self::OLDER], 'AES-256-CBC'); } + + public function testDefaultCipherUnchanged() + { + $encrypter = new Encrypter([self::CURRENT, self::OLDER]); + $payload = $encrypter->encrypt('value'); + $this->assertEquals( + 'value', + (new IlluminateEncrypter(self::CURRENT, 'AES-128-CBC'))->decrypt($payload) + ); + } + + public function testCipherPerKey() + { + $current = str_repeat('a', 32); + $encrypter = new Encrypter( + [$current, self::OLDER], + ['AES-256-CBC', 'AES-128-CBC'] + ); + $this->assertEquals( + 'new', + (new IlluminateEncrypter($current, 'AES-256-CBC'))->decrypt($encrypter->encrypt('new')) + ); + $this->assertEquals( + 'old', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('old')) + ); + } + + public function testCipherListStaysAlignedWithEmptyKeys() + { + $current = str_repeat('a', 32); + $encrypter = new Encrypter( + [$current, '', self::OLDER], + ['AES-256-CBC', 'AES-256-CBC', 'AES-128-CBC'] + ); + $this->assertEquals( + 'old', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('old')) + ); + } + + public function testEmptyCipherIsDefault() + { + $encrypter = new Encrypter([self::CURRENT, self::OLDER], ['', null]); + $this->assertEquals( + 'old', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('old')) + ); + $this->assertEquals(self::CURRENT, (new Encrypter(self::CURRENT, ''))->getKey()); + } + + public function testMismatchedCipherListThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('one entry per encryption key'); + new Encrypter([self::CURRENT, self::OLDER], ['AES-128-CBC']); + } + + public function testCipherListWithStringKeyThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('requires a list of encryption keys'); + new Encrypter(self::CURRENT, ['AES-128-CBC']); + } + + public function testUnsupportedCipherThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('supported ciphers'); + new Encrypter([self::CURRENT, self::OLDER], ['AES-128-CBC', 'DES']); + } + + public function testWrongKeyLengthForCipherThrows() + { + $this->expectException('\RuntimeException'); + $this->expectExceptionMessage('correct key lengths'); + new Encrypter([self::CURRENT, self::OLDER], ['AES-256-CBC', 'AES-128-CBC']); + } } diff --git a/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php b/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php index cd52a8a..a226d89 100644 --- a/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php +++ b/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php @@ -14,13 +14,17 @@ class EncryptionServiceTest extends TestCase const CURRENT = 'current-key-0001'; const OLDER = 'older-key-000002'; - protected function _encrypter($key = null) + protected function _encrypter($key = null, $cipher = null) { $config = new TestConfigProvider(); if($key !== null) { $config->addItem('security', 'encryption_key', $key); } + if($cipher !== null) + { + $config->addItem('security', 'encryption_cipher', $cipher); + } $cubex = new Cubex(); $cubex->configure($config); $encryptionService = new EncryptionService(); @@ -73,4 +77,40 @@ public function testEmptyFirstEntryThrows() $this->expectException('\RuntimeException'); $this->_encrypter(['', self::OLDER]); } + + public function testStringCipher() + { + $key = str_repeat('a', 32); + $encrypter = $this->_encrypter($key, 'AES-256-CBC'); + $this->assertEquals( + 'value', + (new IlluminateEncrypter($key, 'AES-256-CBC'))->decrypt($encrypter->encrypt('value')) + ); + } + + public function testArrayCipher() + { + $key = str_repeat('a', 32); + $encrypter = $this->_encrypter( + [$key, self::OLDER], + ['AES-256-CBC', 'AES-128-CBC'] + ); + $this->assertEquals( + 'new', + (new IlluminateEncrypter($key, 'AES-256-CBC'))->decrypt($encrypter->encrypt('new')) + ); + $this->assertEquals( + 'old', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('old')) + ); + } + + public function testEmptyCipherListUsesDefault() + { + $encrypter = $this->_encrypter(self::CURRENT, []); + $this->assertEquals( + 'value', + (new IlluminateEncrypter(self::CURRENT))->decrypt($encrypter->encrypt('value')) + ); + } } From 5d2d561e9aca4b71acce6e94bb885815ff665084 Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Tue, 29 Sep 2026 10:08:42 +0100 Subject: [PATCH 4/4] Drop illuminate/encryption; infer cipher from key length Cubex\Encryption\Encrypter is now standalone and implements Illuminate\Contracts\Encryption\Encrypter, reading and writing the same payload format as illuminate/encryption 5.x and throwing the contracts' DecryptException/EncryptException. illuminate/contracts is now a direct requirement; illuminate/encryption is require-dev only, for compatibility tests in both directions. Remove security.encryption_cipher: a 16 byte key uses AES-128-CBC and a 32 byte key AES-256-CBC, anything else throws. 16 byte keys behave as before, and 32 byte keys previously threw under the default cipher. Co-Authored-By: Claude Opus 5.5 --- composer.json | 5 +- src/Encryption/Encrypter.php | 236 ++++++++++++----- .../Services/EncryptionService.php | 19 +- tests/Cubex/Encryption/EncrypterTest.php | 238 ++++++++++-------- .../ServiceManager/ServiceManagerTest.php | 2 +- .../Services/EncryptionServiceTest.php | 30 +-- 6 files changed, 324 insertions(+), 206 deletions(-) diff --git a/composer.json b/composer.json index bcad6dc..a71962b 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,7 @@ "illuminate/container": "~5.4", "illuminate/support": "~5.4", "illuminate/cookie": "~5.4", - "illuminate/encryption": "~5.4", + "illuminate/contracts": "~5.4", "monolog/monolog": "~1.10", "packaged/figlet": "~0", "packaged/config": "~1.0", @@ -42,7 +42,8 @@ "mockery/mockery": "~0.9", "guzzlehttp/guzzle": "~6.3", "geoip2/geoip2": "~2.1", - "phpunit/phpunit": "~6.3" + "phpunit/phpunit": "~6.3", + "illuminate/encryption": "~5.4" }, "autoload": { "psr-4": { diff --git a/src/Encryption/Encrypter.php b/src/Encryption/Encrypter.php index 0d61134..182d564 100644 --- a/src/Encryption/Encrypter.php +++ b/src/Encryption/Encrypter.php @@ -2,20 +2,24 @@ namespace Cubex\Encryption; use Illuminate\Contracts\Encryption\DecryptException; -use Illuminate\Encryption\Encrypter as IlluminateEncrypter; +use Illuminate\Contracts\Encryption\EncryptException; +use Illuminate\Contracts\Encryption\Encrypter as EncrypterContract; /** - * Illuminate encrypter that accepts a single key, or a list of keys to allow - * a key to be rotated without invalidating everything encrypted under the - * old key at once. + * AES-CBC encrypter producing and reading the same payloads as + * illuminate/encryption 5.x: base64(json({iv, value, mac})), where value is + * the base64 openssl ciphertext and mac is an HMAC-SHA256 of iv.value keyed + * with the encryption key. + * + * Accepts a single key, or a list of keys to allow a key to be rotated + * without invalidating everything encrypted under the old key at once. * * The first key in a list is the current key: it is used for all encryption * and tried first on decrypt. Later keys are decrypt-only fallbacks, tried in * order when the current key fails. * - * The cipher is either one cipher for every key, or a list aligned by index - * with the keys, so a rotation can also change cipher. An empty cipher is the - * default AES-128-CBC. + * Each key's cipher follows its length: a 16 byte key uses AES-128-CBC and + * a 32 byte key AES-256-CBC, so a rotation can also move to AES-256-CBC. * * A key is normally rotated because it is compromised, so anything that * decrypts with a fallback key may have been forged by whoever holds that @@ -24,54 +28,31 @@ * (e.g. cookie contents). Consumers can re-issue such data so it is * encrypted under the current key. */ -class Encrypter extends IlluminateEncrypter +class Encrypter implements EncrypterContract { - const DEFAULT_CIPHER = 'AES-128-CBC'; - /** - * @var IlluminateEncrypter[] + * [key, cipher] pairs, current key first + * + * @var array[] */ - protected $_fallbacks = []; + protected $_keys = []; /** - * @param string|string[] $key a key, or a list of keys with the current - * key first. Empty fallback keys are ignored. - * @param string|string[] $cipher a cipher for every key, or a list with one - * entry per key entry (including empty ones) + * @param string|string[] $key a key, or a list of keys with the current key + * first. Empty fallback keys are ignored. * - * @throws \RuntimeException when the current key is empty in a list, the - * cipher list does not match the key list, or a - * key is not valid for its cipher + * @throws \RuntimeException when the current key is empty in a list, or a + * key is not 16 or 32 bytes */ - public function __construct($key, $cipher = self::DEFAULT_CIPHER) + public function __construct($key) { if(!is_array($key)) { - if(is_array($cipher)) - { - throw new \RuntimeException( - 'A list of encryption ciphers requires a list of encryption keys.' - ); - } - parent::__construct($key, static::_cipher($cipher)); + $this->_addKey((string)$key); return; } $keys = array_map('strval', array_values($key)); - if(is_array($cipher)) - { - $ciphers = array_values($cipher); - if(count($ciphers) !== count($keys)) - { - throw new \RuntimeException( - 'The encryption cipher list must have one entry per encryption key.' - ); - } - } - else - { - $ciphers = array_fill(0, count($keys), $cipher); - } // An empty first entry is usually an unset environment variable. It is // rejected rather than replaced by the next entry, which would encrypt @@ -83,37 +64,121 @@ public function __construct($key, $cipher = self::DEFAULT_CIPHER) ); } - parent::__construct($keys[0], static::_cipher($ciphers[0])); - - for($i = 1; $i < count($keys); $i++) + foreach($keys as $i => $k) { - if($keys[$i] !== '') + if($i === 0 || $k !== '') { - $this->_fallbacks[] = new IlluminateEncrypter( - $keys[$i], - static::_cipher($ciphers[$i]) - ); + $this->_addKey($k); } } } - protected static function _cipher($cipher) + protected function _addKey($key) + { + $cipher = static::cipherForKey($key); + if($cipher === null) + { + throw new \RuntimeException( + 'Encryption keys must be 16 bytes (AES-128-CBC) or 32 bytes (AES-256-CBC).' + ); + } + $this->_keys[] = [$key, $cipher]; + } + + /** + * @param string $key + * + * @return string|null the cipher for a key of this length, null if none + */ + public static function cipherForKey($key) + { + switch(mb_strlen($key, '8bit')) + { + case 16: + return 'AES-128-CBC'; + case 32: + return 'AES-256-CBC'; + } + return null; + } + + /** + * The current encryption key + * + * @return string + */ + public function getKey() + { + return $this->_keys[0][0]; + } + + /** + * @param mixed $value + * @param bool $serialize + * + * @return string + * + * @throws EncryptException + */ + public function encrypt($value, $serialize = true) + { + list($key, $cipher) = $this->_keys[0]; + $iv = random_bytes(openssl_cipher_iv_length($cipher)); + + $value = openssl_encrypt( + $serialize ? serialize($value) : $value, + $cipher, + $key, + 0, + $iv + ); + if($value === false) + { + throw new EncryptException('Could not encrypt the data.'); + } + + $iv = base64_encode($iv); + $mac = static::_hash($iv, $value, $key); + $json = json_encode(compact('iv', 'value', 'mac')); + if(json_last_error() !== JSON_ERROR_NONE) + { + throw new EncryptException('Could not encrypt the data.'); + } + return base64_encode($json); + } + + /** + * @param string $value + * + * @return string + */ + public function encryptString($value) { - $cipher = (string)$cipher; - return $cipher === '' ? self::DEFAULT_CIPHER : $cipher; + return $this->encrypt($value, false); } + /** + * With $unserialize, the decrypted value is passed to unserialize() + * unrestricted, as illuminate/encryption does. When the payload may come + * from an untrusted source (e.g. a cookie), pass $unserialize = false and + * unserialize with ['allowed_classes' => false]. + * + * @param string $payload + * @param bool $unserialize + * + * @return mixed + * + * @throws DecryptException when no key can decrypt the payload + */ public function decrypt($payload, $unserialize = true) { $failure = null; - // null is the current key, handled by the parent - foreach(array_merge([null], $this->_fallbacks) as $fallback) + foreach($this->_keys as $keyCipher) { try { - return $fallback === null - ? parent::decrypt($payload, $unserialize) - : $fallback->decrypt($payload, $unserialize); + $decrypted = static::_decrypt($payload, $keyCipher[0], $keyCipher[1]); + return $unserialize ? unserialize($decrypted) : $decrypted; } catch(DecryptException $e) { @@ -122,4 +187,61 @@ public function decrypt($payload, $unserialize = true) } throw $failure; } + + /** + * @param string $payload + * + * @return string + */ + public function decryptString($payload) + { + return $this->decrypt($payload, false); + } + + protected static function _decrypt($payload, $key, $cipher) + { + $payload = json_decode(base64_decode($payload), true); + if(!is_array($payload) + || !isset($payload['iv'], $payload['value'], $payload['mac']) + || !is_string($payload['iv']) + || !is_string($payload['value']) + || !is_string($payload['mac']) + || strlen(base64_decode($payload['iv'], true)) + !== openssl_cipher_iv_length($cipher)) + { + throw new DecryptException('The payload is invalid.'); + } + + // Compare HMACs of both MACs under a random key, as illuminate/encryption + // does, so the comparison leaks nothing about the expected MAC. + $bytes = random_bytes(16); + $calculated = hash_hmac( + 'sha256', + static::_hash($payload['iv'], $payload['value'], $key), + $bytes, + true + ); + if(!hash_equals(hash_hmac('sha256', $payload['mac'], $bytes, true), $calculated)) + { + throw new DecryptException('The MAC is invalid.'); + } + + $decrypted = openssl_decrypt( + $payload['value'], + $cipher, + $key, + 0, + base64_decode($payload['iv']) + ); + if($decrypted === false) + { + throw new DecryptException('Could not decrypt the data.'); + } + return $decrypted; + } + + protected static function _hash($iv, $value, $key) + { + return hash_hmac('sha256', $iv . $value, $key); + } } diff --git a/src/ServiceManager/Services/EncryptionService.php b/src/ServiceManager/Services/EncryptionService.php index 8221aa1..613ff3a 100644 --- a/src/ServiceManager/Services/EncryptionService.php +++ b/src/ServiceManager/Services/EncryptionService.php @@ -12,13 +12,11 @@ class EncryptionService extends AbstractServiceProvider * Register the service * * [security] encryption_key is either a single key, or a list of keys for - * rotation. encryption_cipher is optional (default AES-128-CBC), either one - * cipher for every key or a list aligned with encryption_key. See Encrypter. + * rotation. A 16 byte key uses AES-128-CBC, a 32 byte key AES-256-CBC. + * See Encrypter. * * encryption_key[] = * encryption_key[] = - * encryption_cipher[] = AES-256-CBC - * encryption_cipher[] = AES-128-CBC * * @param array $parameters * @@ -30,17 +28,12 @@ public function register(array $parameters = null) 'encrypter', function (Cubex $cubex) { - $config = $cubex->getConfiguration(); - $key = $config->getItem('security', 'encryption_key', self::DEFAULT_KEY); - $cipher = $config->getItem( + $key = $cubex->getConfiguration()->getItem( 'security', - 'encryption_cipher', - Encrypter::DEFAULT_CIPHER - ); - return new Encrypter( - $key === [] ? self::DEFAULT_KEY : $key, - $cipher === [] ? Encrypter::DEFAULT_CIPHER : $cipher + 'encryption_key', + self::DEFAULT_KEY ); + return new Encrypter($key === [] ? self::DEFAULT_KEY : $key); }, true ); diff --git a/tests/Cubex/Encryption/EncrypterTest.php b/tests/Cubex/Encryption/EncrypterTest.php index dbbf3d3..0b9e271 100644 --- a/tests/Cubex/Encryption/EncrypterTest.php +++ b/tests/Cubex/Encryption/EncrypterTest.php @@ -10,33 +10,120 @@ class EncrypterTest extends TestCase const CURRENT = 'current-key-0001'; const OLDER = 'older-key-000002'; const OLDEST = 'oldest-key-00003'; + const KEY_256 = 'current-256-bit-key-000000000001'; protected function _rotating() { return new Encrypter([self::CURRENT, self::OLDER, self::OLDEST]); } - public function testIsIlluminateEncrypter() + public function keyProvider() { - $this->assertInstanceOf(IlluminateEncrypter::class, new Encrypter(self::CURRENT)); - $this->assertInstanceOf(IlluminateEncrypter::class, $this->_rotating()); + return [ + 'AES-128-CBC' => [self::CURRENT, 'AES-128-CBC'], + 'AES-256-CBC' => [self::KEY_256, 'AES-256-CBC'], + ]; + } + + public function testImplementsContract() + { + $this->assertInstanceOf( + '\Illuminate\Contracts\Encryption\Encrypter', + new Encrypter(self::CURRENT) + ); + } + + public function testCipherFollowsKeyLength() + { + $this->assertEquals('AES-128-CBC', Encrypter::cipherForKey(self::CURRENT)); + $this->assertEquals('AES-256-CBC', Encrypter::cipherForKey(self::KEY_256)); + $this->assertNull(Encrypter::cipherForKey('too-short')); + } + + /** + * @dataProvider keyProvider + */ + public function testIlluminatePayloadDecrypts($key, $cipher) + { + $illuminate = new IlluminateEncrypter($key, $cipher); + $ours = new Encrypter($key); + $value = ['a' => 1, 'b' => 'two']; + $this->assertEquals($value, $ours->decrypt($illuminate->encrypt($value))); + $this->assertEquals('raw', $ours->decrypt($illuminate->encrypt('raw', false), false)); + $this->assertEquals('raw', $ours->decryptString($illuminate->encryptString('raw'))); + } + + /** + * @dataProvider keyProvider + */ + public function testIlluminateDecryptsOurPayload($key, $cipher) + { + $illuminate = new IlluminateEncrypter($key, $cipher); + $ours = new Encrypter($key); + $value = ['a' => 1, 'b' => 'two']; + $this->assertEquals($value, $illuminate->decrypt($ours->encrypt($value))); + $this->assertEquals('raw', $illuminate->decrypt($ours->encrypt('raw', false), false)); + $this->assertEquals('raw', $illuminate->decryptString($ours->encryptString('raw'))); + } + + public function testPayloadFormat() + { + $payload = json_decode(base64_decode((new Encrypter(self::CURRENT))->encrypt('v')), true); + $this->assertEquals(['iv', 'value', 'mac'], array_keys($payload)); + $this->assertEquals(16, strlen(base64_decode($payload['iv'], true))); + $this->assertEquals( + hash_hmac('sha256', $payload['iv'] . $payload['value'], self::CURRENT), + $payload['mac'] + ); + } + + public function testTamperedMacThrows() + { + $payload = json_decode(base64_decode((new Encrypter(self::CURRENT))->encrypt('v')), true); + $payload['mac'] = hash_hmac('sha256', 'forged', self::CURRENT); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + $this->expectExceptionMessage('MAC is invalid'); + (new Encrypter(self::CURRENT))->decrypt(base64_encode(json_encode($payload))); + } + + public function testTamperedValueThrows() + { + $payload = json_decode(base64_decode((new Encrypter(self::CURRENT))->encrypt('v')), true); + $payload['value'] = base64_encode('forged'); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + (new Encrypter(self::CURRENT))->decrypt(base64_encode(json_encode($payload))); + } + + public function invalidPayloadProvider() + { + return [ + 'not base64 json' => ['not a payload'], + 'missing mac' => [base64_encode(json_encode(['iv' => base64_encode(str_repeat('a', 16)), 'value' => 'x']))], + 'short iv' => [base64_encode(json_encode(['iv' => base64_encode('a'), 'value' => 'x', 'mac' => 'y']))], + 'array value' => [base64_encode(json_encode(['iv' => base64_encode(str_repeat('a', 16)), 'value' => [], 'mac' => 'y']))], + ]; + } + + /** + * @dataProvider invalidPayloadProvider + */ + public function testInvalidPayloadThrows($payload) + { + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + $this->expectExceptionMessage('payload is invalid'); + $this->_rotating()->decrypt($payload); } public function testStringKeyUnchanged() { $encrypter = new Encrypter(self::CURRENT); $this->assertEquals(self::CURRENT, $encrypter->getKey()); - $payload = $encrypter->encrypt('value'); - $this->assertEquals('value', (new IlluminateEncrypter(self::CURRENT))->decrypt($payload)); - $this->assertEquals( - 'value', - $encrypter->decrypt((new IlluminateEncrypter(self::CURRENT))->encrypt('value')) - ); + $this->assertEquals('value', $encrypter->decrypt($encrypter->encrypt('value'))); } public function testStringKeyNoMatchThrows() { - $payload = (new IlluminateEncrypter(self::OLDER))->encrypt('value'); + $payload = (new Encrypter(self::OLDER))->encrypt('value'); $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); (new Encrypter(self::CURRENT))->decrypt($payload); } @@ -47,8 +134,8 @@ public function testFirstEntryEncrypts() $this->assertEquals(self::CURRENT, $encrypter->getKey()); $payload = $encrypter->encrypt('value'); $this->assertEquals('value', (new IlluminateEncrypter(self::CURRENT))->decrypt($payload)); - $this->assertEquals('value', $encrypter->decrypt($payload)); - $this->assertEquals('raw', $encrypter->decryptString($encrypter->encryptString('raw'))); + $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + (new IlluminateEncrypter(self::OLDER))->decrypt($payload); } public function testFallbackKeysDecrypt() @@ -64,10 +151,24 @@ public function testFallbackKeysDecrypt() ); } - public function testNoKeyMatchesThrows() + public function testMixedCipherRotation() + { + $encrypter = new Encrypter([self::KEY_256, self::OLDER]); + $this->assertEquals( + 'new', + (new IlluminateEncrypter(self::KEY_256, 'AES-256-CBC'))->decrypt($encrypter->encrypt('new')) + ); + $this->assertEquals( + 'old', + $encrypter->decrypt((new IlluminateEncrypter(self::OLDER, 'AES-128-CBC'))->encrypt('old')) + ); + } + + public function testNoKeyMatchesThrowsFirstFailure() { - $payload = (new IlluminateEncrypter('unknown-key-0004'))->encrypt('value'); + $payload = (new Encrypter('unknown-key-0004'))->encrypt('value'); $this->expectException('\Illuminate\Contracts\Encryption\DecryptException'); + $this->expectExceptionMessage('MAC is invalid'); $this->_rotating()->decrypt($payload); } @@ -104,108 +205,29 @@ public function testAllEmptyThrows() new Encrypter(['', '']); } - public function testInvalidFallbackKeyLengthThrows() + public function testEmptyStringKeyThrows() { $this->expectException('\RuntimeException'); - $this->expectExceptionMessage('correct key lengths'); - new Encrypter([self::CURRENT, 'too-short']); + $this->expectExceptionMessage('16 bytes'); + new Encrypter(''); } - public function testInvalidCurrentKeyLengthThrows() + public function badKeyProvider() { - $this->expectException('\RuntimeException'); - $this->expectExceptionMessage('correct key lengths'); - new Encrypter(['too-short', self::OLDER]); - } - - public function testCipherAppliesToAllKeys() - { - $current = str_repeat('a', 32); - $older = str_repeat('b', 32); - $encrypter = new Encrypter([$current, $older], 'AES-256-CBC'); - $this->assertEquals( - 'older', - $encrypter->decrypt((new IlluminateEncrypter($older, 'AES-256-CBC'))->encrypt('older')) - ); - $this->expectException('\RuntimeException'); - new Encrypter([$current, self::OLDER], 'AES-256-CBC'); - } - - public function testDefaultCipherUnchanged() - { - $encrypter = new Encrypter([self::CURRENT, self::OLDER]); - $payload = $encrypter->encrypt('value'); - $this->assertEquals( - 'value', - (new IlluminateEncrypter(self::CURRENT, 'AES-128-CBC'))->decrypt($payload) - ); - } - - public function testCipherPerKey() - { - $current = str_repeat('a', 32); - $encrypter = new Encrypter( - [$current, self::OLDER], - ['AES-256-CBC', 'AES-128-CBC'] - ); - $this->assertEquals( - 'new', - (new IlluminateEncrypter($current, 'AES-256-CBC'))->decrypt($encrypter->encrypt('new')) - ); - $this->assertEquals( - 'old', - $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('old')) - ); - } - - public function testCipherListStaysAlignedWithEmptyKeys() - { - $current = str_repeat('a', 32); - $encrypter = new Encrypter( - [$current, '', self::OLDER], - ['AES-256-CBC', 'AES-256-CBC', 'AES-128-CBC'] - ); - $this->assertEquals( - 'old', - $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('old')) - ); - } - - public function testEmptyCipherIsDefault() - { - $encrypter = new Encrypter([self::CURRENT, self::OLDER], ['', null]); - $this->assertEquals( - 'old', - $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('old')) - ); - $this->assertEquals(self::CURRENT, (new Encrypter(self::CURRENT, ''))->getKey()); - } - - public function testMismatchedCipherListThrows() - { - $this->expectException('\RuntimeException'); - $this->expectExceptionMessage('one entry per encryption key'); - new Encrypter([self::CURRENT, self::OLDER], ['AES-128-CBC']); - } - - public function testCipherListWithStringKeyThrows() - { - $this->expectException('\RuntimeException'); - $this->expectExceptionMessage('requires a list of encryption keys'); - new Encrypter(self::CURRENT, ['AES-128-CBC']); - } - - public function testUnsupportedCipherThrows() - { - $this->expectException('\RuntimeException'); - $this->expectExceptionMessage('supported ciphers'); - new Encrypter([self::CURRENT, self::OLDER], ['AES-128-CBC', 'DES']); + return [ + 'short current' => [['too-short', self::OLDER]], + 'short fallback' => [[self::CURRENT, 'too-short']], + '24 byte key' => [str_repeat('a', 24)], + ]; } - public function testWrongKeyLengthForCipherThrows() + /** + * @dataProvider badKeyProvider + */ + public function testBadKeyLengthThrows($key) { $this->expectException('\RuntimeException'); - $this->expectExceptionMessage('correct key lengths'); - new Encrypter([self::CURRENT, self::OLDER], ['AES-256-CBC', 'AES-128-CBC']); + $this->expectExceptionMessage('16 bytes'); + new Encrypter($key); } } diff --git a/tests/Cubex/ServiceManager/ServiceManagerTest.php b/tests/Cubex/ServiceManager/ServiceManagerTest.php index 3da0ef4..b47300e 100644 --- a/tests/Cubex/ServiceManager/ServiceManagerTest.php +++ b/tests/Cubex/ServiceManager/ServiceManagerTest.php @@ -137,7 +137,7 @@ public function testServiceAliases() $manager->setCubex($cubex); $manager->boot(); $encrypter = $cubex->make('encrypter'); - $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); + $this->assertInstanceOf('\Illuminate\Contracts\Encryption\Encrypter', $encrypter); } } diff --git a/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php b/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php index a226d89..072d6ef 100644 --- a/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php +++ b/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php @@ -14,17 +14,13 @@ class EncryptionServiceTest extends TestCase const CURRENT = 'current-key-0001'; const OLDER = 'older-key-000002'; - protected function _encrypter($key = null, $cipher = null) + protected function _encrypter($key = null) { $config = new TestConfigProvider(); if($key !== null) { $config->addItem('security', 'encryption_key', $key); } - if($cipher !== null) - { - $config->addItem('security', 'encryption_cipher', $cipher); - } $cubex = new Cubex(); $cubex->configure($config); $encryptionService = new EncryptionService(); @@ -42,7 +38,7 @@ public function testRegisterCreatesEncrypter() $encrypter = $this->_encrypter(); $this->assertInstanceOf(Encrypter::class, $encrypter); - $this->assertInstanceOf(IlluminateEncrypter::class, $encrypter); + $this->assertInstanceOf('\Illuminate\Contracts\Encryption\Encrypter', $encrypter); $this->assertEquals(EncryptionService::DEFAULT_KEY, $encrypter->getKey()); } @@ -78,23 +74,16 @@ public function testEmptyFirstEntryThrows() $this->_encrypter(['', self::OLDER]); } - public function testStringCipher() + public function test256BitKeys() { $key = str_repeat('a', 32); - $encrypter = $this->_encrypter($key, 'AES-256-CBC'); + $encrypter = $this->_encrypter($key); $this->assertEquals( 'value', (new IlluminateEncrypter($key, 'AES-256-CBC'))->decrypt($encrypter->encrypt('value')) ); - } - public function testArrayCipher() - { - $key = str_repeat('a', 32); - $encrypter = $this->_encrypter( - [$key, self::OLDER], - ['AES-256-CBC', 'AES-128-CBC'] - ); + $encrypter = $this->_encrypter([$key, self::OLDER]); $this->assertEquals( 'new', (new IlluminateEncrypter($key, 'AES-256-CBC'))->decrypt($encrypter->encrypt('new')) @@ -104,13 +93,4 @@ public function testArrayCipher() $encrypter->decrypt((new IlluminateEncrypter(self::OLDER))->encrypt('old')) ); } - - public function testEmptyCipherListUsesDefault() - { - $encrypter = $this->_encrypter(self::CURRENT, []); - $this->assertEquals( - 'value', - (new IlluminateEncrypter(self::CURRENT))->decrypt($encrypter->encrypt('value')) - ); - } }