From 3e90a4a8306b5100f32cd5d9cc2cc908dd047e6b Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Tue, 29 Sep 2026 10:18:27 +0100 Subject: [PATCH 1/2] Replace the encrypter with XChaCha20-Poly1305 and key rotation Add Cubex\Encryption: EncrypterInterface (string in, string out) and an XChaCha20-Poly1305 implementation. Payloads are base64url of a version byte, a random 24 byte nonce and the ciphertext with tag; the version is bound as additional data. Cipher keys are derived with HKDF-SHA256 from configured keys of at least 16 bytes. security.encryption_key may be a list: the first key encrypts, later keys only decrypt. An empty first entry throws instead of promoting an old key. Payloads written by illuminate/encryption (Cubex 2.6) still decrypt through Legacy\IlluminateFallbackEncrypter, which is decrypt-only and can be removed once they have expired. 'encrypter' is now an adapter implementing Illuminate's encrypter contract, unserializing with allowed_classes disabled. illuminate/encryption moves to require-dev for compatibility tests; illuminate/contracts is required directly. Sodium is suggested, and checked when an encrypter is constructed. Co-Authored-By: Claude Opus 5.5 --- composer.json | 9 +- src/Encryption/DecryptException.php | 6 + src/Encryption/Encrypter.php | 144 ++++++++++++++ src/Encryption/EncrypterInterface.php | 22 +++ src/Encryption/IlluminateEncrypterAdapter.php | 70 +++++++ .../Legacy/IlluminateFallbackEncrypter.php | 132 +++++++++++++ .../Services/EncryptionService.php | 39 +++- tests/Cubex/Encryption/EncrypterTest.php | 187 ++++++++++++++++++ .../IlluminateEncrypterAdapterTest.php | 74 +++++++ .../IlluminateFallbackEncrypterTest.php | 105 ++++++++++ .../ServiceManager/ServiceManagerTest.php | 2 +- .../Services/EncryptionServiceTest.php | 76 ++++++- 12 files changed, 845 insertions(+), 21 deletions(-) create mode 100644 src/Encryption/DecryptException.php create mode 100644 src/Encryption/Encrypter.php create mode 100644 src/Encryption/EncrypterInterface.php create mode 100644 src/Encryption/IlluminateEncrypterAdapter.php create mode 100644 src/Encryption/Legacy/IlluminateFallbackEncrypter.php create mode 100644 tests/Cubex/Encryption/EncrypterTest.php create mode 100644 tests/Cubex/Encryption/IlluminateEncrypterAdapterTest.php create mode 100644 tests/Cubex/Encryption/Legacy/IlluminateFallbackEncrypterTest.php diff --git a/composer.json b/composer.json index fc11e77..ca510d1 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,12 @@ "mockery/mockery": "~0.9", "guzzlehttp/guzzle": "~6.3", "geoip2/geoip2": "~2.1", - "phpunit/phpunit": "~9" + "phpunit/phpunit": "~9", + "illuminate/encryption": "~5.4" + }, + "suggest": { + "ext-sodium": "Required to use Cubex\\Encryption", + "paragonie/sodium_compat": "Pure-PHP fallback when ext-sodium is unavailable" }, "autoload": { "psr-4": { diff --git a/src/Encryption/DecryptException.php b/src/Encryption/DecryptException.php new file mode 100644 index 0000000..1e60ebc --- /dev/null +++ b/src/Encryption/DecryptException.php @@ -0,0 +1,6 @@ +_keys[] = hash_hkdf('sha256', $key, static::KEY_BYTES, static::KDF_INFO); + } + } + + protected static function _sodiumAvailable(): bool + { + // paragonie/sodium_compat defines the same functions + return function_exists('sodium_crypto_aead_xchacha20poly1305_ietf_encrypt'); + } + + /** + * @param string|string[] $keys + * + * @return string[] the non-empty keys, current key first + * + * @throws \InvalidArgumentException when the current key is empty + */ + public static function normaliseKeys($keys): array + { + $keys = array_map('strval', is_array($keys) ? array_values($keys) : [$keys]); + + // 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(!isset($keys[0]) || $keys[0] === '') + { + throw new \InvalidArgumentException( + 'The first encryption key is the current key and must not be empty.' + ); + } + return array_values(array_filter($keys, 'strlen')); + } + + public function encrypt(string $plaintext): string + { + $nonce = random_bytes(static::NONCE_BYTES); + $ciphertext = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt( + $plaintext, + static::VERSION, + $nonce, + $this->_keys[0] + ); + return rtrim(strtr(base64_encode(static::VERSION . $nonce . $ciphertext), '+/', '-_'), '='); + } + + public function decrypt(string $payload): string + { + $binary = false; + if(strlen($payload) % 4 !== 1 && preg_match('/^[A-Za-z0-9_-]*$/', $payload)) + { + $binary = base64_decode(strtr($payload, '-_', '+/'), true); + } + if($binary === false) + { + throw new DecryptException('The payload is not valid base64url.'); + } + + $headerBytes = 1 + static::NONCE_BYTES; + if(strlen($binary) < $headerBytes + static::TAG_BYTES) + { + throw new DecryptException('The payload is too short.'); + } + $version = $binary[0]; + if($version !== static::VERSION) + { + throw new DecryptException('The payload version is not supported.'); + } + + $nonce = substr($binary, 1, static::NONCE_BYTES); + $ciphertext = substr($binary, $headerBytes); + foreach($this->_keys as $key) + { + $plaintext = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt($ciphertext, $version, $nonce, $key); + if($plaintext !== false) + { + return $plaintext; + } + } + throw new DecryptException('The payload could not be decrypted with any configured key.'); + } +} diff --git a/src/Encryption/EncrypterInterface.php b/src/Encryption/EncrypterInterface.php new file mode 100644 index 0000000..5eff1b5 --- /dev/null +++ b/src/Encryption/EncrypterInterface.php @@ -0,0 +1,22 @@ +_encrypter = $encrypter; + } + + public function getEncrypter(): EncrypterInterface + { + return $this->_encrypter; + } + + public function encrypt($value, $serialize = true) + { + return $this->_encrypter->encrypt($serialize ? serialize($value) : (string)$value); + } + + public function decrypt($payload, $unserialize = true) + { + try + { + $plaintext = $this->_encrypter->decrypt((string)$payload); + } + catch(DecryptException $e) + { + throw new IlluminateDecryptException($e->getMessage(), 0, $e); + } + + if(!$unserialize) + { + return $plaintext; + } + + $value = @unserialize($plaintext, ['allowed_classes' => false]); + if($value === false && $plaintext !== serialize(false)) + { + throw new IlluminateDecryptException('The payload could not be unserialized.'); + } + return $value; + } + + public function encryptString($value) + { + return $this->encrypt($value, false); + } + + public function decryptString($payload) + { + return $this->decrypt($payload, false); + } +} diff --git a/src/Encryption/Legacy/IlluminateFallbackEncrypter.php b/src/Encryption/Legacy/IlluminateFallbackEncrypter.php new file mode 100644 index 0000000..d26f35e --- /dev/null +++ b/src/Encryption/Legacy/IlluminateFallbackEncrypter.php @@ -0,0 +1,132 @@ +_encrypter = $encrypter; + foreach(Encrypter::normaliseKeys($keys) as $key) + { + $cipher = static::cipherForKey($key); + if($cipher !== null) + { + $this->_legacyKeys[] = [$key, $cipher]; + } + } + } + + /** + * @param string $key + * + * @return string|null the cipher Illuminate used for a key of this length + */ + public static function cipherForKey(string $key) + { + switch(strlen($key)) + { + case 16: + return 'AES-128-CBC'; + case 32: + return 'AES-256-CBC'; + } + return null; + } + + public function encrypt(string $plaintext): string + { + return $this->_encrypter->encrypt($plaintext); + } + + public function decrypt(string $payload): string + { + $legacy = static::_legacyPayload($payload); + if($legacy === null) + { + return $this->_encrypter->decrypt($payload); + } + + foreach($this->_legacyKeys as list($key, $cipher)) + { + $plaintext = static::_legacyDecrypt($legacy, $key, $cipher); + if($plaintext !== null) + { + return $plaintext; + } + } + throw new DecryptException('The payload could not be decrypted with any configured key.'); + } + + /** + * @param string $payload + * + * @return array|null the decoded payload, if it is in the legacy format + */ + protected static function _legacyPayload(string $payload) + { + $decoded = json_decode(base64_decode($payload, true) ?: '', true); + if(is_array($decoded) + && isset($decoded['iv'], $decoded['value'], $decoded['mac']) + && is_string($decoded['iv']) + && is_string($decoded['value']) + && is_string($decoded['mac'])) + { + return $decoded; + } + return null; + } + + /** + * @return string|null the plaintext, or null when this key does not match + */ + protected static function _legacyDecrypt(array $payload, string $key, string $cipher) + { + $iv = base64_decode($payload['iv'], true); + if($iv === false || strlen($iv) !== openssl_cipher_iv_length($cipher)) + { + return null; + } + + $expected = hash_hmac('sha256', $payload['iv'] . $payload['value'], $key); + if(!hash_equals($expected, $payload['mac'])) + { + return null; + } + + $plaintext = openssl_decrypt($payload['value'], $cipher, $key, 0, $iv); + return $plaintext === false ? null : $plaintext; + } +} diff --git a/src/ServiceManager/Services/EncryptionService.php b/src/ServiceManager/Services/EncryptionService.php index 61568ed..335500e 100644 --- a/src/ServiceManager/Services/EncryptionService.php +++ b/src/ServiceManager/Services/EncryptionService.php @@ -2,30 +2,53 @@ namespace Cubex\ServiceManager\Services; use Cubex\Cubex; -use Illuminate\Encryption\Encrypter; +use Cubex\Encryption\Encrypter; +use Cubex\Encryption\EncrypterInterface; +use Cubex\Encryption\IlluminateEncrypterAdapter; +use Cubex\Encryption\Legacy\IlluminateFallbackEncrypter; class EncryptionService extends AbstractServiceProvider { + const DEFAULT_KEY = 'mR?u7DP30sj5Djdf'; + /** * Register the service * + * Binds EncrypterInterface, and 'encrypter' as Illuminate's encrypter + * contract. [security] encryption_key is either a single key, or a list of + * keys for rotation with the current key first, see Encrypter: + * + * encryption_key[] = + * encryption_key[] = + * + * Payloads written by Cubex 2.6 (illuminate/encryption) still decrypt, see + * IlluminateFallbackEncrypter. + * * @param array $parameters * * @return mixed */ public function register(array $parameters = null) { + $this->getCubex()->bind( + EncrypterInterface::class, + function (Cubex $cubex) + { + $keys = $cubex->getConfiguration()->getItem('security', 'encryption_key', self::DEFAULT_KEY); + if($keys === []) + { + $keys = self::DEFAULT_KEY; + } + return new IlluminateFallbackEncrypter(new Encrypter($keys), $keys); + }, + true + ); + $this->getCubex()->bind( 'encrypter', function (Cubex $cubex) { - return new Encrypter( - $cubex->getConfiguration()->getItem( - 'security', - 'encryption_key', - 'mR?u7DP30sj5Djdf' - ) - ); + return new IlluminateEncrypterAdapter($cubex->make(EncrypterInterface::class)); }, true ); diff --git a/tests/Cubex/Encryption/EncrypterTest.php b/tests/Cubex/Encryption/EncrypterTest.php new file mode 100644 index 0000000..e5fe09a --- /dev/null +++ b/tests/Cubex/Encryption/EncrypterTest.php @@ -0,0 +1,187 @@ +assertInstanceOf(EncrypterInterface::class, $encrypter); + foreach(['', 'value', random_bytes(1000)] as $plaintext) + { + $this->assertSame($plaintext, $encrypter->decrypt($encrypter->encrypt($plaintext))); + } + } + + public function testPayloadFormat() + { + $payload = (new Encrypter(self::CURRENT))->encrypt('value'); + $this->assertMatchesRegularExpression('/^[A-Za-z0-9_-]+$/', $payload); + $binary = self::_decode($payload); + $this->assertSame(Encrypter::VERSION, $binary[0]); + $this->assertSame(1 + 24 + strlen('value') + 16, strlen($binary)); + } + + public function testNonceIsRandom() + { + $encrypter = new Encrypter(self::CURRENT); + $this->assertNotSame($encrypter->encrypt('value'), $encrypter->encrypt('value')); + } + + public function testSmallerThanIlluminate() + { + $plaintext = serialize('a typical cookie value of some length'); + $ours = strlen((new Encrypter(self::OLDER))->encrypt($plaintext)); + $illuminate = strlen((new IlluminateEncrypter(self::OLDER))->encrypt($plaintext, false)); + // 57 plaintext bytes: 108 vs 272 + $this->assertLessThan($illuminate / 2, $ours); + } + + public function testRotation() + { + $old = new Encrypter(self::OLDER); + $rotating = new Encrypter([self::CURRENT, '', self::OLDER]); + $this->assertSame('old', $rotating->decrypt($old->encrypt('old'))); + + $payload = $rotating->encrypt('new'); + $this->assertSame('new', (new Encrypter(self::CURRENT))->decrypt($payload)); + $this->expectException(DecryptException::class); + $old->decrypt($payload); + } + + public function testWrongKeyThrows() + { + $payload = (new Encrypter(self::OLDER))->encrypt('value'); + $this->expectException(DecryptException::class); + $this->expectExceptionMessage('any configured key'); + (new Encrypter(self::CURRENT))->decrypt($payload); + } + + public function tamperProvider() + { + return [ + 'version' => [0], + 'nonce' => [5], + 'ciphertext' => [26], + 'tag' => [-1], + ]; + } + + /** + * @dataProvider tamperProvider + */ + public function testTamperingThrows(int $offset) + { + $encrypter = new Encrypter(self::CURRENT); + $binary = self::_decode($encrypter->encrypt('value')); + $offset = $offset < 0 ? strlen($binary) + $offset : $offset; + $binary[$offset] = chr(ord($binary[$offset]) ^ 1); + $this->expectException(DecryptException::class); + $encrypter->decrypt(self::_encode($binary)); + } + + public function testVersionIsAuthenticated() + { + // A payload claiming the current version must have been sealed with it + $encrypter = new Encrypter(self::CURRENT); + $binary = self::_decode($encrypter->encrypt('value')); + $key = hash_hkdf('sha256', self::CURRENT, 32, Encrypter::KDF_INFO); + $nonce = substr($binary, 1, 24); + $forged = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt('value', "\x02", $nonce, $key); + $this->expectException(DecryptException::class); + $encrypter->decrypt(self::_encode(Encrypter::VERSION . $nonce . $forged)); + } + + public function malformedProvider() + { + return [ + 'not base64url' => ['not a payload!', 'base64url'], + 'padded' => ['AQ==', 'base64url'], + 'bad length' => ['AAAAA', 'base64url'], + 'too short' => [self::_encode("\x01short"), 'too short'], + 'bad version' => [self::_encode("\x02" . str_repeat('a', 60)), 'version'], + ]; + } + + /** + * @dataProvider malformedProvider + */ + public function testMalformedPayloadThrows(string $payload, string $message) + { + $this->expectException(DecryptException::class); + $this->expectExceptionMessage($message); + (new Encrypter(self::CURRENT))->decrypt($payload); + } + + public function testIlluminatePayloadIsNotAccepted() + { + $payload = (new IlluminateEncrypter(self::OLDER))->encrypt('value'); + $this->expectException(DecryptException::class); + (new Encrypter(self::OLDER))->decrypt($payload); + } + + public function invalidKeyProvider() + { + return [ + 'empty string' => ['', 'must not be empty'], + 'empty list' => [[], 'must not be empty'], + 'empty first entry' => [['', self::OLDER], 'must not be empty'], + 'all empty' => [['', ''], 'must not be empty'], + 'short current key' => ['fifteen-bytes!!', 'at least 16 bytes'], + 'short previous key' => [[self::CURRENT, 'short'], 'at least 16 bytes'], + ]; + } + + /** + * @dataProvider invalidKeyProvider + */ + public function testInvalidKeysThrow($keys, string $message) + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage($message); + new Encrypter($keys); + } + + public function testNormaliseKeys() + { + $this->assertSame([self::CURRENT], Encrypter::normaliseKeys(self::CURRENT)); + $this->assertSame( + [self::CURRENT, self::OLDER], + Encrypter::normaliseKeys(['x' => self::CURRENT, '', null, self::OLDER]) + ); + } + + public function testMissingSodiumThrows() + { + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('ext-sodium or paragonie/sodium_compat'); + new NoSodiumEncrypter(self::CURRENT); + } +} + +class NoSodiumEncrypter extends Encrypter +{ + protected static function _sodiumAvailable(): bool + { + return false; + } +} diff --git a/tests/Cubex/Encryption/IlluminateEncrypterAdapterTest.php b/tests/Cubex/Encryption/IlluminateEncrypterAdapterTest.php new file mode 100644 index 0000000..ab5652a --- /dev/null +++ b/tests/Cubex/Encryption/IlluminateEncrypterAdapterTest.php @@ -0,0 +1,74 @@ +_adapter(); + $this->assertInstanceOf(\Illuminate\Contracts\Encryption\Encrypter::class, $adapter); + $this->assertInstanceOf(Encrypter::class, $adapter->getEncrypter()); + } + + public function testSerializedRoundTrip() + { + $adapter = $this->_adapter(); + foreach([['a' => 1], 'string', 42, false, null] as $value) + { + $this->assertSame($value, $adapter->decrypt($adapter->encrypt($value))); + } + } + + public function testRawRoundTrip() + { + $adapter = $this->_adapter(); + $this->assertSame('raw', $adapter->decrypt($adapter->encrypt('raw', false), false)); + $this->assertSame('raw', $adapter->decryptString($adapter->encryptString('raw'))); + $this->assertSame('raw', (new Encrypter(self::KEY))->decrypt($adapter->encryptString('raw'))); + } + + public function testObjectsAreNotInstantiated() + { + $adapter = $this->_adapter(); + $payload = $adapter->encrypt(new AdapterTestObject()); + $value = $adapter->decrypt($payload); + $this->assertInstanceOf(\__PHP_Incomplete_Class::class, $value); + $this->assertSame(0, AdapterTestObject::$woken); + } + + public function testDecryptFailureThrowsContractException() + { + $this->expectException(DecryptException::class); + $this->_adapter()->decrypt('not a payload!'); + } + + public function testUnserializeFailureThrows() + { + $adapter = $this->_adapter(); + $this->expectException(DecryptException::class); + $this->expectExceptionMessage('unserialized'); + $adapter->decrypt($adapter->encrypt('not serialized', false)); + } +} + +class AdapterTestObject +{ + public static $woken = 0; + + public function __wakeup() + { + static::$woken++; + } +} diff --git a/tests/Cubex/Encryption/Legacy/IlluminateFallbackEncrypterTest.php b/tests/Cubex/Encryption/Legacy/IlluminateFallbackEncrypterTest.php new file mode 100644 index 0000000..976ab4d --- /dev/null +++ b/tests/Cubex/Encryption/Legacy/IlluminateFallbackEncrypterTest.php @@ -0,0 +1,105 @@ + [self::KEY_128, 'AES-128-CBC'], + 'AES-256-CBC' => [self::KEY_256, 'AES-256-CBC'], + ]; + } + + /** + * @dataProvider legacyKeyProvider + */ + public function testDecryptsIlluminatePayloads(string $key, string $cipher) + { + $illuminate = new IlluminateEncrypter($key, $cipher); + $encrypter = $this->_encrypter([self::NEW_KEY, $key]); + $this->assertSame('raw', $encrypter->decrypt($illuminate->encrypt('raw', false))); + $this->assertSame(serialize(['a' => 1]), $encrypter->decrypt($illuminate->encrypt(['a' => 1]))); + + // single key upgrade without rotation + $this->assertSame('raw', $this->_encrypter($key)->decrypt($illuminate->encryptString('raw'))); + } + + /** + * @dataProvider legacyKeyProvider + */ + public function testNeverWritesLegacyFormat(string $key, string $cipher) + { + $encrypter = $this->_encrypter($key); + $payload = $encrypter->encrypt('value'); + $this->assertSame('value', (new Encrypter($key))->decrypt($payload)); + $this->expectException(\Illuminate\Contracts\Encryption\DecryptException::class); + (new IlluminateEncrypter($key, $cipher))->decrypt($payload, false); + } + + public function testDecryptsCurrentFormat() + { + $encrypter = $this->_encrypter([self::NEW_KEY, self::KEY_128]); + $this->assertSame('v', $encrypter->decrypt((new Encrypter(self::KEY_128))->encrypt('v'))); + $this->assertSame('v', $encrypter->decrypt($encrypter->encrypt('v'))); + } + + public function testUnknownLegacyKeyThrows() + { + $payload = (new IlluminateEncrypter('unknown-key-0004'))->encrypt('value'); + $this->expectException(DecryptException::class); + $this->_encrypter([self::NEW_KEY, self::KEY_128])->decrypt($payload); + } + + public function testKeysOfOtherLengthsAreNotLegacyKeys() + { + $this->assertSame('AES-128-CBC', IlluminateFallbackEncrypter::cipherForKey(self::KEY_128)); + $this->assertSame('AES-256-CBC', IlluminateFallbackEncrypter::cipherForKey(self::KEY_256)); + $this->assertNull(IlluminateFallbackEncrypter::cipherForKey(self::NEW_KEY)); + } + + public function tamperProvider() + { + return [ + 'mac' => ['mac', str_repeat('0', 64)], + 'value' => ['value', base64_encode('forged-ciphertext')], + 'iv' => ['iv', base64_encode('short')], + ]; + } + + /** + * @dataProvider tamperProvider + */ + public function testTamperedLegacyPayloadThrows(string $field, string $value) + { + $payload = json_decode(base64_decode((new IlluminateEncrypter(self::KEY_128))->encrypt('v')), true); + $payload[$field] = $value; + $this->expectException(DecryptException::class); + $this->_encrypter(self::KEY_128)->decrypt(base64_encode(json_encode($payload))); + } + + public function testUndecryptableLegacyCiphertextThrows() + { + // valid MAC over a value that is not valid ciphertext + $iv = base64_encode(random_bytes(16)); + $value = base64_encode('not-a-block'); + $mac = hash_hmac('sha256', $iv . $value, self::KEY_128); + $this->expectException(DecryptException::class); + $this->_encrypter(self::KEY_128)->decrypt(base64_encode(json_encode(compact('iv', 'value', 'mac')))); + } +} diff --git a/tests/Cubex/ServiceManager/ServiceManagerTest.php b/tests/Cubex/ServiceManager/ServiceManagerTest.php index a660937..4a142b6 100644 --- a/tests/Cubex/ServiceManager/ServiceManagerTest.php +++ b/tests/Cubex/ServiceManager/ServiceManagerTest.php @@ -136,7 +136,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 7dbaf89..d549d88 100644 --- a/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php +++ b/tests/Cubex/ServiceManager/Services/EncryptionServiceTest.php @@ -2,29 +2,85 @@ namespace CubexTest\Cubex\ServiceManager\Services; use Cubex\Cubex; +use Cubex\Encryption\Encrypter; +use Cubex\Encryption\EncrypterInterface; +use Cubex\Encryption\IlluminateEncrypterAdapter; +use Cubex\Encryption\Legacy\IlluminateFallbackEncrypter; use Cubex\ServiceManager\Services\EncryptionService; +use Illuminate\Encryption\Encrypter as IlluminateEncrypter; use Packaged\Config\Provider\ConfigSection; use Packaged\Config\Provider\Test\TestConfigProvider; use PHPUnit\Framework\TestCase; class EncryptionServiceTest extends TestCase { - public function testRegisterCreatesEncrypter() + const NEW_KEY = 'a-new-key-of-any-length-over-16'; + const OLD_KEY = 'older-key-000002'; + + protected function _cubex($keys = null): Cubex { + $config = new TestConfigProvider(); + if($keys !== null) + { + $config->addItem('security', 'encryption_key', $keys); + } $cubex = new Cubex(); - $cubex->configure(new TestConfigProvider()); + $cubex->configure($config); $encryptionService = new EncryptionService(); - - $this->assertInstanceOf( - '\Cubex\ServiceManager\IServiceProvider', - $encryptionService - ); - $encryptionService->boot($cubex, new ConfigSection()); - $encryptionService->register(); + return $cubex; + } + public function testRegisterCreatesEncrypter() + { + $this->assertInstanceOf('\Cubex\ServiceManager\IServiceProvider', new EncryptionService()); + + $cubex = $this->_cubex(); $encrypter = $cubex->make('encrypter'); - $this->assertInstanceOf('\Illuminate\Encryption\Encrypter', $encrypter); + $this->assertInstanceOf(IlluminateEncrypterAdapter::class, $encrypter); + $this->assertInstanceOf(\Illuminate\Contracts\Encryption\Encrypter::class, $encrypter); + $this->assertInstanceOf(IlluminateFallbackEncrypter::class, $cubex->make(EncrypterInterface::class)); + $this->assertSame($cubex->make(EncrypterInterface::class), $encrypter->getEncrypter()); + } + + public function defaultKeyProvider() + { + return ['missing' => [null], 'empty list' => [[]]]; + } + + /** + * @dataProvider defaultKeyProvider + */ + public function testDefaultKey($keys) + { + $core = $this->_cubex($keys)->make(EncrypterInterface::class); + $this->assertSame('v', (new Encrypter(EncryptionService::DEFAULT_KEY))->decrypt($core->encrypt('v'))); + $legacy = (new IlluminateEncrypter(EncryptionService::DEFAULT_KEY))->encrypt('v', false); + $this->assertSame('v', $core->decrypt($legacy)); + } + + public function testStringKey() + { + $core = $this->_cubex(self::NEW_KEY)->make(EncrypterInterface::class); + $this->assertSame('v', (new Encrypter(self::NEW_KEY))->decrypt($core->encrypt('v'))); + } + + public function testKeyList() + { + $cubex = $this->_cubex([self::NEW_KEY, self::OLD_KEY]); + $core = $cubex->make(EncrypterInterface::class); + $this->assertSame('v', (new Encrypter(self::NEW_KEY))->decrypt($core->encrypt('v'))); + $this->assertSame('v', $core->decrypt((new Encrypter(self::OLD_KEY))->encrypt('v'))); + + // an existing cookie written by Cubex 2.6 through EncryptCookies + $cookie = (new IlluminateEncrypter(self::OLD_KEY))->encrypt(['id' => 5]); + $this->assertSame(['id' => 5], $cubex->make('encrypter')->decrypt($cookie)); + } + + public function testEmptyFirstKeyThrows() + { + $this->expectException(\InvalidArgumentException::class); + $this->_cubex(['', self::OLD_KEY])->make('encrypter'); } } From 24187be4ce51fb4457212ff223e90270c7d94bf4 Mon Sep 17 00:00:00 2001 From: Tom Kay Date: Tue, 29 Sep 2026 10:18:52 +0100 Subject: [PATCH 2/2] Correct payload size comment Co-Authored-By: Claude Opus 5.5 --- tests/Cubex/Encryption/EncrypterTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Cubex/Encryption/EncrypterTest.php b/tests/Cubex/Encryption/EncrypterTest.php index e5fe09a..364fe2c 100644 --- a/tests/Cubex/Encryption/EncrypterTest.php +++ b/tests/Cubex/Encryption/EncrypterTest.php @@ -52,7 +52,7 @@ public function testSmallerThanIlluminate() $plaintext = serialize('a typical cookie value of some length'); $ours = strlen((new Encrypter(self::OLDER))->encrypt($plaintext)); $illuminate = strlen((new IlluminateEncrypter(self::OLDER))->encrypt($plaintext, false)); - // 57 plaintext bytes: 108 vs 272 + // 45 plaintext bytes: 115 vs 244 $this->assertLessThan($illuminate / 2, $ours); }