I want to encrypt specific field column “Whatsapp” used AES-256, I have read tutorial below
https://stackoverflow.com/questions/32260229/encryption-decryption-of-form-fields-in-cakephp-3/32261210#32261210
next I config and added few files below
\src\Database\Type\CryptedType.php
use Cake\Utility\Security;
class CryptedType extends BaseType
{
public function toDatabase($value, DriverInterface $driver)
{
return Security::encrypt($value, Security::getSalt());
}
public function toPHP($value, DriverInterface $driver)
{
if($value === null) {
return null;
}
return Security::decrypt($value, Security::getSalt());
}
}
in config\bootstrap.php
I have added few line
use Cake\Security\Utility;
Type::map('crypted', 'App\Database\Type\CryptedType');
in \Model\Table\UsersTable.php
I have added some few line
use Cake\Utility\Security;
use Cake\Database\Schema\Table as Schema;
use Cake\Datasource\ResultSetInterface;
use Cake\Datasource\EntityInterface;
use Cake\Collection\CollectionInterface;
class UsersTable extends Table
{
//prtected function untuk encrypt dan decrypt
protected function _initializeSchema(Schema $table)
{
$table->setColumnType('whatsapp', 'crypted');
return $table;
}
//before save to encrypt and output formatters
public $encryptedFields = ['whatsapp'];
public function beforeSave(Event $event, Entity $entity, ArrayObject $options)
{
foreach($this->encryptedFields as $fieldName) {
if($entity->has($fieldName)) {
$entity->set(
$fieldName,
Security::encrypt($entity->get($fieldName), Security::getSalt())
);
}
}
return true;
}
public function beforeFind(Event $event, Query $query, ArrayObject $options, boolean $primary)
{
$query->formatResults(
function($results) {
return $results->map(function ($row) {
foreach($this->encryptedFields as $fieldName) {
if(isset($row[$fieldName])) {
$row[$fieldName] = Security::decrypt($row[$fieldName], Security::getSalt());
}
}
return $row;
});
}
);
}
}
in \config\app.php
I have added key salt
'Security' => [
'salt' => env('SECURITY_SALT','wt1U5MACWJFTXc3b0nkFoZoiLwQGrLgdbHA'),
],
when I run test to see the result, the error message display below
Class "Security" not found
ROOT\config\bootstrap.php
ConnectionManager::setConfig(Configure::consume('Datasources'));
TransportFactory::setConfig(Configure::consume('EmailTransport'));
Mailer::setConfig(Configure::consume('Email'));
Log::setConfig(Configure::consume('Log'));
Security::setSalt(Configure::consume('Security.salt'));
/*
* Setup detectors for mobile and tablet.
* If you don't use these checks you can safely remove this code
Error in: ROOT\config\bootstrap.php, line 167
thanx for someone that I hope to help !