A simple way to encrypt/decrypt data in php

In this post, we will focus on how can we encrypt/decrypt store (text/JSON) using PHP. This may be useful in cases where we need to store and retrieve sensitive data in filesystem instead of a database. We will be seeing only the encryption and decryption portion. The generated content can be saved in file using file_put_contents() and read using file_get_contents().

We will be using OpenSSL Functions functions available in PHP. In this example, we will use ‘AES-256-CBC-HMAC-SHA256’ cipher method. You can get a list of available cipher methods using openssl_get_cipher_methods().

Next, we need to generate Initialization Vector (IV) that will be used on openssl_encrypt(). Although we can proceed without initialization vector, it is generally not recommended.

 


  //get the length of IV for the selected cipher method
  $ivlength = openssl_cipher_iv_length('AES-256-CBC-HMAC-SHA256');
  //Generate a pseudo random string of required length.
  $iv = openssl_random_pseudo_bytes($ivlength);


Encrypting


  $encryptedString = base64_encode(openssl_encrypt($string, 'AES-256-CBC-HMAC-SHA256', $key, OPENSSL_RAW_DATA, $iv));
  // $string = string to be encoded
  // $key = the encryption key defined above.
  // $iv = Initialization Vector generated above.


NOTE: The value of $key and $iv must be same in while encrypting and decrypting.

Decrypting


$decrypted = openssl_decrypt(base64_decode($data), 'AES-256-CBC-HMAC-SHA256', $key, OPENSSL_RAW_DATA, $iv); 


Leave a Reply

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