Skip to content

Commit

Permalink
Encryption (#49962)
Browse files Browse the repository at this point in the history
This PR allows you to specify multiple previous_keys which are old encryption keys you are rotating out. All newly encrypted strings will be encrypted using the app.key like normal. On decryption, the current key will be tried first. If that key is not able to decrypt the data, decryption will be attempted with previous keys. Of course, if all keys fail to decrypt the data, the process will fail like normal.
  • Loading branch information
taylorotwell authored Feb 3, 2024
1 parent 4346406 commit 41d1f60
Show file tree
Hide file tree
Showing 7 changed files with 98 additions and 17 deletions.
6 changes: 5 additions & 1 deletion config-stubs/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,13 @@
|
*/

'cipher' => 'AES-256-CBC',

'key' => env('APP_KEY'),

'cipher' => 'AES-256-CBC',
'previous_keys' => [
// Previous encryption keys to be used for decryption...
],

/*
|--------------------------------------------------------------------------
Expand Down
6 changes: 5 additions & 1 deletion config/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,13 @@
|
*/

'cipher' => 'AES-256-CBC',

'key' => env('APP_KEY'),

'cipher' => 'AES-256-CBC',
'previous_keys' => [
// Previous encryption keys to be used for decryption...
],

/*
|--------------------------------------------------------------------------
Expand Down
12 changes: 8 additions & 4 deletions src/Illuminate/Cookie/CookieValuePrefix.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,17 @@ public static function remove($cookieValue)
*
* @param string $cookieName
* @param string $cookieValue
* @param string $key
* @param array $keys
* @return string|null
*/
public static function validate($cookieName, $cookieValue, $key)
public static function validate($cookieName, $cookieValue, array $keys)
{
$hasValidPrefix = str_starts_with($cookieValue, static::create($cookieName, $key));
foreach ($keys as $key) {
$hasValidPrefix = str_starts_with($cookieValue, static::create($cookieName, $key));

return $hasValidPrefix ? static::remove($cookieValue) : null;
if ($hasValidPrefix) {
return static::remove($cookieValue);
}
}
}
}
2 changes: 1 addition & 1 deletion src/Illuminate/Cookie/Middleware/EncryptCookies.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ protected function validateValue(string $key, $value)
{
return is_array($value)
? $this->validateArray($key, $value)
: CookieValuePrefix::validate($key, $value, $this->encrypter->getKey());
: CookieValuePrefix::validate($key, $value, $this->encrypter->getAllKeys());
}

/**
Expand Down
71 changes: 62 additions & 9 deletions src/Illuminate/Encryption/Encrypter.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ class Encrypter implements EncrypterContract, StringEncrypter
*/
protected $key;

/**
* The previous / legacy encryption keys.
*
* @var array
*/
protected $previousKeys = [];

/**
* The algorithm used for encryption.
*
Expand Down Expand Up @@ -113,7 +120,7 @@ public function encrypt($value, $serialize = true)

$mac = self::$supportedCiphers[strtolower($this->cipher)]['aead']
? '' // For AEAD-algorithms, the tag / MAC is returned by openssl_encrypt...
: $this->hash($iv, $value);
: $this->hash($iv, $value, $this->key);

$json = json_encode(compact('iv', 'value', 'mac', 'tag'), JSON_UNESCAPED_SLASHES);

Expand Down Expand Up @@ -159,9 +166,15 @@ public function decrypt($payload, $unserialize = true)
// Here we will decrypt the value. If we are able to successfully decrypt it
// we will then unserialize it and return it out to the caller. If we are
// unable to decrypt this value we will throw out an exception message.
$decrypted = \openssl_decrypt(
$payload['value'], strtolower($this->cipher), $this->key, 0, $iv, $tag ?? ''
);
foreach ($this->getAllKeys() as $key) {
$decrypted = \openssl_decrypt(
$payload['value'], strtolower($this->cipher), $key, 0, $iv, $tag ?? ''
);

if ($decrypted !== false) {
break;
}
}

if ($decrypted === false) {
throw new DecryptException('Could not decrypt the data.');
Expand All @@ -188,11 +201,12 @@ public function decryptString($payload)
*
* @param string $iv
* @param mixed $value
* @param string $key
* @return string
*/
protected function hash($iv, $value)
protected function hash($iv, $value, $key)
{
return hash_hmac('sha256', $iv.$value, $this->key);
return hash_hmac('sha256', $iv.$value, $key);
}

/**
Expand Down Expand Up @@ -258,9 +272,17 @@ protected function validPayload($payload)
*/
protected function validMac(array $payload)
{
return hash_equals(
$this->hash($payload['iv'], $payload['value']), $payload['mac']
);
foreach ($this->getAllKeys() as $key) {
$valid = hash_equals(
$this->hash($payload['iv'], $payload['value'], $key), $payload['mac']
);

if ($valid === true) {
return true;
}
}

return false;
}

/**
Expand Down Expand Up @@ -289,4 +311,35 @@ public function getKey()
{
return $this->key;
}

/**
* Get the current encryption key and all previous encryption keys.
*
* @return array
*/
public function getAllKeys()
{
return [$this->key, ...$this->previousKeys];
}

/**
* Set the previous / legacy encryption keys that should be utilized if decryption fails.
*
* @param array $key
* @return $this
*/
public function previousKeys(array $keys)
{
foreach ($keys as $key) {
if (! static::supported($key, $this->cipher)) {
$ciphers = implode(', ', array_keys(self::$supportedCiphers));

throw new RuntimeException("Unsupported cipher or incorrect key length. Supported ciphers are: {$ciphers}.");
}
}

$this->previousKeys = $keys;

return $this;
}
}
6 changes: 5 additions & 1 deletion src/Illuminate/Encryption/EncryptionServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ protected function registerEncrypter()
$this->app->singleton('encrypter', function ($app) {
$config = $app->make('config')->get('app');

return new Encrypter($this->parseKey($config), $config['cipher']);
return (new Encrypter($this->parseKey($config), $config['cipher']))
->previousKeys(array_map(
fn ($key) => $this->parseKey(['key' => $key]),
$config['previous_keys'] ?? []
));
});
}

Expand Down
12 changes: 12 additions & 0 deletions tests/Encryption/EncrypterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,18 @@ public function testRawStringEncryption()
$this->assertSame('foo', $e->decryptString($encrypted));
}

public function testRawStringEncryptionWithPreviousKeys()
{
$previous = new Encrypter(str_repeat('b', 16));
$previousValue = $previous->encryptString('foo');

$new = new Encrypter(str_repeat('a', 16));
$new->previousKeys([str_repeat('b', 16)]);

$decrypted = $new->decryptString($previousValue);
$this->assertSame('foo', $decrypted);
}

public function testEncryptionUsingBase64EncodedKey()
{
$e = new Encrypter(random_bytes(16));
Expand Down

0 comments on commit 41d1f60

Please sign in to comment.