Laravel 8 - Encrypted and Decrypted Data using openssl_encrypt

  5598 views   6 months ago Laravel

In this article, I will share with you how to encrypted and decrypted data using openssl_encrypt function with example. as you know data security is very important part in web application when you working on the large application. in laravel you can done it very simple way. you can encrypt and decrypt your data by using openssl_encrypt() function. here i share with simple example forr how to make your data very secure and not anyone encrypted without your hash key.

Encrypt Data Example

$encrypt_method = "AES-256-CBC";
$secret_key = '7aE3OKIZxusugQdpk3gwNi9x63MRAFLgkMJ4nyil88ZYMyjqTSE3FIo8L5KJghfi';
$secret_iv = '7aE3OKIZxusugQdpk3gwNi9x63MRAFLgkMJ4nyil88ZYMyjqTSE3FIo8L5KJghfi';
// hash
$key = hash('sha256', $secret_key);

// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);

$string = $input['card_no'].'-'.$input['ccExpiryMonth'].'-'.$input['ccExpiryYear'].'-'.$input['cvvNumber'];
// encrypt token;
$encryptToken = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$encryptToken = base64_encode($encryptToken);
// decrypt token
$decryptToken = openssl_decrypt(base64_decode($encryptToken), $encrypt_method, $key, 0, $iv);
// output
dd($decryptToken);

Decrypt Data Example

$frameware = $tokens;
$encrypt_method = "AES-256-CBC";
$secret_key = '7aE3OKIZxusugQdpk3gwNi9x63MRAFLgkMJ4nyil88ZYMyjqTSE3FIo8L5KJghfi';
$secret_iv = '7aE3OKIZxusugQdpk3gwNi9x63MRAFLgkMJ4nyil88ZYMyjqTSE3FIo8L5KJghfi';
// hash
$key = hash('sha256', $secret_key);

// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
// decrypt token
$decryptToken = openssl_decrypt(base64_decode($frameware), $encrypt_method, $key, 0, $iv);
// convert in array
$decryptTokenArray = json_decode($decryptToken, 1);
// output
dd($decryptTokenArray);

it will help you lot.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]

Related Articles