Member-only story

How to encrypt and decrypt a message using the OpenSSL in PHP

Jay Gao
8 min readFeb 24, 2023

--

Here’s an example PHP program to encrypt and decrypt a message using the OpenSSL library:

<?php
// Define the message to be encrypted
$message = "This is a secret message.";

// Generate a random encryption key
$key = openssl_random_pseudo_bytes(16);

// Encrypt the message using AES-128-CBC encryption
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($message, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode($iv.$hmac.$ciphertext_raw);

// Display the encrypted message
echo "Encrypted message: " . $ciphertext . "\n";

// Decrypt the message
$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);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);

// Verify the decrypted message
if (hash_equals($hmac, $calcmac)) {
echo "Decrypted message: " . $original_plaintext . "\n";
} else {
echo "Error: Message authentication failed.\n";
}
?>

Now let’s break it down with more details.

// Generate a random encryption key
$key = openssl_random_pseudo_bytes(16);

--

--

No responses yet