joacir / cake-aes
使用 AES-256 插件加密和解密 CakePHP 字段
2.0
2024-03-22 18:53 UTC
Requires
- php: >=7.4
- cakephp/cakephp: ^5.0.0
Requires (Dev)
- cakephp/cakephp-codesniffer: ^4.5
- phpstan/phpstan: @stable
- phpunit/phpunit: ^9.5
This package is not auto-updated.
Last update: 2024-09-20 21:12:52 UTC
README
CakePHP 插件,用于在 MySQL/MariaDB 数据库中使用 AES-256 算法加密和解密表字段。此分支适用于 CakePHP 4.2+
安装
将其作为必需依赖项安装
composer require joacir/CakeAes
配置
在您的 Application.php 中启用插件或调用
bin/cake plugin load CakeAes
在 app_local.php 中配置新的安全哈希
'Security' => [
'key' => '34601affc03a12d4b963b6123ab3afcb',
],
- 这将是插件用于加密的密钥。
- 决不要为不同的应用程序使用相同的密钥。
- 一旦生成,决不要更改密钥。
- 密钥必须包含至少 32 位十六进制数字。
将您要加密的字段的表类型字段更改为二进制类型
char(20) -> blob
vachar(200) -> varbinary(200)
text -> blob
- 只有 string 类型有效。请仅使用 VarBinary 或 Blob 类型。
在您的表 initialize() 方法中加载行为
$this->addBehavior('CakeAes.Encrypt', [
'fields' => ['name', 'card', 'phone']
]);
用法
加密字段
无需任何操作,EncryptBehavior 会在设置 fields 时自动进行加密。
解密字段、条件、排序和包含
find() 或 get() 无需更改即可正常工作,在复杂查询中可以使用 decryptField() 或 decryptString()。
$new = $this->Temps->get($temp->id, ['fields' => [
'id',
'name' => $this->Temps->decryptField('Temps.name')
]]);
$temp = $this->Temps->find()
->select(['name' => $this->Temps->decryptField('Temps.name')])
->where(['id' => 2])
->first();
您可以在 conditions 中使用 decryptEq()。
$temp = $this->Temps->find()
->select(['name' => $this->Temps->decryptField('Temps.name')])
->where([$this->Temps->decryptEq('Temps.name', $name)])
->first();
$temp = $this->Temps->find()
->select([
'id',
'name' => $this->Temps->decryptField('Temps.name')
])
->where([$this->Temps->decryptLike('Temps.name', '%Sa%')])
->first();
在 updateAll() 中,您可以使用 encrypt() 进行加密
$name = $this->Temps->encrypt("José");
$fields = ['name' => $name];
$conditions = [
$this->Temps->decryptEq('Temps.name', 'Maria')
];
$this->Temps->updateAll($fields, $conditions);
加密/解密文件
$imageFile = dirname(__FILE__) . DS . 'imagem.jpg';
$Temps->encryptFile($imageFile);
$imageFile = dirname(__FILE__) . DS . 'imagem_crypted.jpg';
$Temps->decryptFile($imageFile);
在控制器中解密文件
加载 Encrypt 组件
public function initialize(): void
{
$this->loadComponent('CakeAes.Encrypt');
}
解密并渲染内容
$imageFile = dirname(__FILE__) . DS . 'imagem_encrypted.jpg';
return $this->Encrypt->decryptRender($imageFile);
解密并下载文件
$imageFile = dirname(__FILE__) . DS . 'imagem_encrypted.jpg';
return $this->Encrypt->decryptDownload($imageFile);