How to Encrypt and Decrypt String in PHP

String encryption functionality is used to make sensitive information safe in the web application. With the encryption feature, the original string is encrypted with Salt/Key and stored. Later the encrypted string is decrypted by the Salt/Key that is used at the time of encryption. The encryption and decryption algorithm can be implemented with a salt key using PHP.

In this code example, we will show you how to encrypt and decrypt string with PHP. Follow the below steps to encrypt and decrypt string with key in PHP.

Generate Salt Key:
Create a random key and secure key with PHP openssl_random_pseudo_bytes() function.

$bytes openssl_random_pseudo_bytes(16); 
$key bin2hex($bytes);

Keep this key safe and use it later in the encryption and decryption operations.

Encrypt String using PHP:
Use PHP openssl_encrypt() function to convert plaintext to ciphertext with a key using an encryption algorithm.

$key 'YOUR_SALT_KEY'// Previously generated safely, ie: openssl_random_pseudo_bytes 

$plaintext "String to be encrypted";

$ivlen openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw openssl_encrypt($plaintext$cipher$key$options=OPENSSL_RAW_DATA$iv);
$hmac hash_hmac('sha256'$ciphertext_raw$key$as_binary=true);

// Encrypted string
$ciphertext base64_encode($iv.$hmac.$ciphertext_raw);

Decrypt String using PHP:
Transform ciphertext back to original plaintext with key using openssl_decrypt() function in PHP.

$key 'YOUR_SALT_KEY'// Previously used in encryption 
$c base64_decode($ciphertext);
$ivlen openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv substr($c0$ivlen);
$hmac substr($c$ivlen$sha2len=32);
$ciphertext_raw substr($c$ivlen+$sha2len);
$original_plaintext openssl_decrypt($ciphertext_raw$cipher$key$options=OPENSSL_RAW_DATA$iv);
$calcmac hash_hmac('sha256'$ciphertext_raw$key$as_binary=true);

if(
hash_equals($hmac$calcmac)){ //PHP 5.6+ Timing attack safe string comparison
  
echo 'Original String: '.$original_plaintext;
}else{
  echo 
'Decryption failed!';
}

Leave a reply

keyboard_double_arrow_up