How to encrypt a string with a private key/salt in PHP

By 31st July 2019 August 22nd, 2019 Tutourial & Tips

Its useful to encrypt a certain string and and then unlock the message by decryption using a private key/salt.

$token = "The quick brown fox jumps over the lazy dog.";
echo "|| OORIGINAL TEXT :::. \n";
echo $token;
echo  "\n \n";

$enc_key = "PP45YnKdD";


echo "|| SECRET KEY :::. \n";
echo $enc_key;
echo  "\n \n";


$cipher_method = 'aes-128-ctr';
$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
$crypted_token = openssl_encrypt($token, $cipher_method, $enc_key, 0, $enc_iv) . "::" . bin2hex($enc_iv);
unset($token, $cipher_method, $enc_key, $enc_iv);

echo "|| ENCRYPTED TEXT :::. \n";
echo $crypted_token;
echo  "\n \n";


list($crypted_token, $enc_iv) = explode("::", $crypted_token);;
$cipher_method = 'aes-128-ctr';
$enc_key = "PP45YnKdD";
$token = openssl_decrypt($crypted_token, $cipher_method, $enc_key, 0, hex2bin($enc_iv));
unset($crypted_token, $cipher_method, $enc_key, $enc_iv);

echo "|| DECRYPTED TEXT :::. \n";
echo  $token;

Sample Output:

|| OORIGINAL TEXT :::. 
The quick brown fox jumps over the lazy dog.
 
|| SECRET KEY :::. 
PP45YnKdD
 
|| ENCRYPTED TEXT :::. 
DySOqmrR4Xa2fs6ZXJOuU/wDjM0EJQtWb822WMhKD0O9agrih9ch3E845rk=::89ac6d9e082b0f6f1c1dfd1371737d90
 
|| DECRYPTED TEXT :::. 
The quick brown fox jumps over the lazy dog.