techsemicolon / laravel-app-key-rotation
一个辅助库,用于在旋转Laravel APP_KEY时重新加密现有加密数据
Requires
- php: >=5.4.0
- illuminate/support: 5.2.x|5.3.x|5.4.x|5.5.x|5.6.x|5.7.x|5.8.x
This package is auto-updated.
Last update: 2024-09-15 06:40:49 UTC
README
一个辅助库,用于在旋转Laravel APP_KEY时重新加密现有加密数据
APP_KEY 用于保护您的用户会话和其他加密数据的安全!如果未设置应用程序密钥,则用户会话和其他加密数据将不安全。信或不信,这是一个重大的安全风险。
为了给您提供更具体的背景,Laravel 之前存在一个安全问题
如果您的应用程序加密密钥落入恶意人士之手,该人士可以使用加密密钥创建cookie值,并利用PHP对象序列化和反序列化内固有的漏洞,例如在您的应用程序中调用任意类方法。
因此,定期旋转APP_KEY非常重要。了解更多
如何使用此包
当现有应用程序中的APP_KEY更改时,您使用Crypt外观或encrypt()辅助函数加密的任何数据将无法解密,因为加密使用APP_KEY。
因此,当您运行php artisan key:generate
以在密钥轮换中生成新密钥时,您需要首先使用旧APP_KEY解密旧加密数据,然后使用新生成的APP_KEY重新加密。
安装
composer require techsemicolon/laravel-app-key-rotation
使用方法
您可以通过传递旧APP_KEY来实例化ReEncrypter
类。为此,在您旋转APP_KEY到新密钥之前,保留旧APP_KEY的安全备份以供参考非常重要。
// This is your old APP_KEY $oldAppKey = "your_old_app_key"; // Instantiate ReEncrypter $eeEncrypter = new ReEncrypter($oldAppKey); // Re-cncrypt the oldEncryptedPayload value $newEncryptedPayload = $eeEncrypter->encrypt($oldEncryptedPayload);
##建议
当您通过新的加密有效载荷值更新数据库时,请确保您还有一个列,用于存储旧的加密有效载荷值作为备份。这是为了防止在密钥轮换过程中发生数据丢失。
##示例
让我们假设我们在users
表中有一个名为bank_account_number
的列,该列以加密字符串的形式存储。我们在同一表中还有一个名为old_bank_account_number
的列,用于存储旧的加密有效载荷作为备份。
我们可以创建一个命令php artisan encryption:rotate
<?php namespace App\Console\Commands; use App\User; use Techsemicolon\KeyRotation\ReEncrypter; class EncryptionRotateCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'encryption:rotate {--oldappkey= : Old app key}'; /** * The console command description. * * @var string */ protected $description = 'Re-encrypt when APP_KEY is rotated'; /** * Create a new command instance. * */ public function __construct() { parent::__construct(); } /** * Function to re-encrypt when APP_KEY is rotated/changed * * @param string $oldAppKey * @param mixed $value */ public function handle() { // This is your old APP_KEY $oldAppKey = $this->option('oldappkey'); // Instantiate ReEncrypter $eeEncrypter = new ReEncrypter($oldAppKey); User::all()->each(function($user) use($eeEncrypter){ // Stored value in a backup column $user->old_bank_account_number = $user->bank_account_number; // Re-cncrypt the old encrypted payload value $user->bank_account_number = $eeEncrypter->encrypt($user->bank_account_number); $user->save(); }); $this->info('Encryption completed with newly rotated key'); } }
有关laravel APP_KEY轮换的原因和方法的更多详细信息,请点击此处
许可证
此包是开源软件,许可协议为MIT许可证