AES Encrypt & Decrypt

ByKarthik Kumar D Kon11th Jun 2019, 2022-07-07T14:10:00+05:30
Read Article
Pause
Resume
Stop
AES Encrypt & Decrypt

Advanced Encryption Standard, where we use AES-256 to encrypt the data with Cipher. Encrypt & Decrypt approach taken is 'Cipher Block Chaining' method 'AES-256-CBC'.

AES Encrypt

  • We would have the 'Secret' stored in a file which is other than the web root.
$key = hash('sha256', $secret, true);
  • Hash the 'Secret' with sha256, this gives you the 'Key' which will be used to openssl encrypt.
  • And Generate the pseudo random bytes as 'IV', so that it would be used during encryption and also be attached to the encrypted data.
$iv = openssl_random_pseudo_bytes(16);
  • Now encrypt the 'String' with openssl encrypt by passing the 'AES-256-CBC' method, 'Key' and 'IV'
$ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
  • 'openssl_encrypt' will Encrypt given data with given method and key, returns a raw or base64 encoded string.
  • 'Hash' the returned 'Cipher' text with sha256 hmac method
$hash = hash_hmac('sha256', $ciphertext, $key, true);
  • Now concatenate the 'IV' & 'Hash' & 'Cipher' and store in the DB as the encrypted value.

AES Decrypt

  • Hash the 'Secret' with sha256, this gives you the 'Key' which will be used to openssl encrypt.
$key = hash('sha256', $password, true);
  • Explode the concatenated string to 'IV' & 'Hash' & 'Cipher'
$iv = substr($ivHashCiphertext, 0, 16);

$hash = substr($ivHashCiphertext, 16, 32);

$ciphertext = substr($ivHashCiphertext, 48);
  • 'openssl_decrypt' will take a raw or base64 encoded string and decrypts it using a given method and key.
  • Now decrypt the 'Cipher' with 'AES-256-CBC' method, 'Key' and 'IV'
openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
  • Return the decrypted 'String'. it is ok, or do i need to change it to excel.

Cheers :)

Labels


Comments

We Need Your Consent
By clicking “Accept Cookies”, you agree to the storing of cookies on your device to enhance your site navigation experience.
I Accept Cookies