Cakephp3で個人情報の暗号復号化

Standard
...
use Cake\Utility\Security;
...
class User extends Entity
{
 ...
 protected function _setAddress($address)
 {
  if (strlen($address) > 0) {
   return bin2hex(Security::encrypt($address, Security::salt()));
  }
 }
 
 protected function _setTel($tel)
 {
  if (strlen($tel) > 0) {
   return bin2hex(Security::encrypt($tel, Security::salt()));
  }
 }
 
 protected function _getAddress($address)
 {
  if (strlen($address) > 0) {
   return Security::decrypt(hex2bin($address), Security::salt());
  }
 }
 
 protected function _getTel($tel)
 {
  if (strlen($tel) > 0) {
   return Security::decrypt(hex2bin($tel), Security::salt());
  }
 }
 ...
}
class UserTable extends Table
{
...
 
 public $encryptedFields = [
  'address',
  'tel'
 ];
 
 public function beforeSave($event, $entity, $options)
 {
  foreach($this->encryptedFields as $fieldName) {
   if($entity->has($fieldName)) {
    $expr = $this->query()->newExpr("HEX( AES_ENCRYPT('".$entity[$fieldName]."', '".Security::salt()."') )");
    $entity->set($fieldName, $expr);
   }
  }
  return true;
 }
 
 public function setFields()
 {
  $select = [
   'user_id',
   'user_name',
   'address' => 'AES_DECRYPT(UNHEX(User.address), "'.Security::salt().'")',
   'tel' => 'AES_DECRYPT(UNHEX(User.tel), "'.Security::salt().'")',
  ];
  return $select;
 }
 
 public function getUserList($where = [])
 {
  $select = $this->setFields();
  $query = $this->find()
        ->select($select)
        ->where(['User.id'=>1]);
  return $query;
 }
 
 public function getConditions($search)
 {
  $where = ['Users.del_flg' => 0];
  foreach ($search as $key => $value) {
   if (isset($value) && $value != '') {
    switch ($key) {
     case 'user_name':
      $where['MstUser.user_name'] = $value;
      break;
     case 'tel':
      $expr = $this->newExpr("AES_DECRYPT(UNHEX(Users.".$key."), '".Security::salt()."') LIKE '%".$value."%'");
      $where[] = $expr;
      break;
    }
   }
  }
  return $where;
 }
...
}
 
 
class UsersController extends CommonAdminController
{
...
 public $search = [
  'user_id' => '',
  'user_name' => '',
  'zip' => '',
  'pref' => ''
 ];
 
 public function index()
 {
  $search = $this->search;
   if ($this->request->is(['get'])) {
    if ($this->request->getQuery()) {
     foreach($this->request->getQuery() as $key => $value) {
      $search[$key] = $value;
     }
    }
   }
 
  $where = $this->Users->getConditions($search);
  $users = $this->paginate($this->Users->getUsersList($where));
  $this->set(compact('users', 'search'));
 }
...
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.