【CakePHP3】データを暗号化してテーブルに保存する!
CakePHP3でデータを暗号化してテーブル(Model)に保存する方法です。
以下の「encr()」でデータを暗号化して保存しています。「decr()」ではデータを復号化して表示しています。
use Cake\Utility\Security;
use Cake\Core\Configure;
class SaveController extends AppController
{
public function encr()
{
$key = Configure::read('key');
$salt = Configure::read('salt');
//データを用意
$name = 'yukarin';
$age = '17';
$age = Security::encrypt($age, $key, $salt); //暗号化!
$data = compact("name", "age");
//保存
$entity = $this->Users->newEntity();
$entity = $this->Users->patchEntity($entity, $data);
$this->Users->save($entity);
}
public function decr()
{
$key = Configure::read('key');
$salt = Configure::read('salt');
//復号化して読み込み
$user = $this->Users->find()->where(['name' => 'yukarin'])->first();
$user->age = Security::decrypt($user->age, $key, $salt); //復号化!
debug($user);
}
}グローバル定数の「暗号鍵key」と「salt」は「/config/bootstrap.php」内で定義しています。
Configure::write('key','HOGEhogeHOGEhogeHOGEhogeHOGEhoge');
Configure::write('salt','PIYOpiyoPIYOpiyoPIYOpiyoPIYOpiyo');ちなみに、データを暗号化するとBinaryデータになります。なのでSQLのデータ型は「varbinary(255)」とかにしないと保存できないので、ご注意ください。
もっと詳しい情報はCakePHP公式ページにのっています。
http://book.cakephp.org/3.0/ja/core-libraries/security.html
以上