<?php
namespace App\Traits;
use Illuminate\Support\Facades\Crypt;
trait Encryptable
{
protected function encryptValue($value)
{
$key = env('SALT_KEY'); // Replace this with your actual salt key
$cipher = 'AES-128-CBC';
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($value, $cipher, $key, OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, true);
$ciphertext = base64_encode($iv . $hmac . $ciphertext_raw);
return $ciphertext;
}
protected function decryptValue($value)
{
$key = env('SALT_KEY'); // Replace this with your actual salt key
$cipher = 'AES-128-CBC';
$c = base64_decode($value);
$ivlen = openssl_cipher_iv_length($cipher);
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, 32);
$ciphertext_raw = substr($c, $ivlen + 32);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, true);
return hash_equals($hmac, $calcmac) ? $original_plaintext : null;
}
public function setAttribute($key, $value)
{
if ($this->isEncryptableAttribute($key)) {
$value = $this->encryptValue($value);
}
return parent::setAttribute($key, $value);
}
public function getAttribute($key)
{
$value = parent::getAttribute($key);
if ($this->isEncryptableAttribute($key) && !empty($value)) {
$value = $this->decryptValue($value);
}
return $value;
}
protected function isEncryptableAttribute($key)
{
return in_array($key, $this->encryptable ?? []);
}
}
First you make the traits with your own salt that is in the .env file named as SALT_KEY for better security and then you can use this trait in your model like this:
use HasFactory,Encryptable;
protected $fillable = [
'name', 'description', 'status',
];
protected $encryptable = ['name','description'];