Image

Knowledge base → An example of a php script for encrypting and decrypting text

[Scripts]
Date of publication: 10.10.2023

Here is an example of a script tested on PHP 8.1 for encrypting and decrypting a text string based on openssl.

nano encrypt-decrypt.php
<?php 

define('ENCRYPTION_KEY', '<mark>my-secret-key-there-2121</mark>');

// Encrypt
$plaintext = "<output>Test string for encryption in php 8.1</output>";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, ENCRYPTION_KEY, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, ENCRYPTION_KEY, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
<output>echo $ciphertext.'<br>';</output>
 
// Decrypt
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$plaintext = openssl_decrypt($ciphertext_raw, $cipher, ENCRYPTION_KEY, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, ENCRYPTION_KEY, $as_binary=true);
if (hash_equals($hmac, $calcmac))
{
    <output>echo $plaintext;</output>
}

?>

The first line is the result of encryption, and the second line is decryption. Moreover, if we refresh the page without changing the phrase, we will always get a different result, but when decrypted it will be the same.

To separate these functions into different files, you will need to transfer the key in the ENCRYPTION_KEY parameter.





No Comments Yet