2-way encryption with AES 256bit (CBC) in PHP

PHP-Class for encryption of text. I use it for safe storage of information in databases.

The key should be secret and personal to each user, the IV is public and is prepended in front of the encrypted string with a “:” as the delimiter.

You could also use a “site-master-key” as a constant in a php file, so if someone gets a hold of your database they would not be able to decrypt it without that key.

<?php
/**
 * abCrypt utilizes openssl to encrypt and decrypt textstrings
 *
 * This project started as a way to encrypt user information which is stored in the database.
 *
 * @package asbraCMS
 * @subpackage abCrypt
 * @author Nimpen J. Nordström <j@asbra.nu>
 * @copyright 2018 ASBRA AB
 */

/**
 * abCrypt is a class for encrypting and decrypting textstrings using openssl
 *
 * @param string $encryption_key The encryption in HEX
 */
class abCrypt
{
	/** @var string $key Hex encoded binary key for encryption and decryption */
	public $key = '';

	/** @var string $encrypt_method Method to use for encryption */
	public	$encrypt_method = 'AES-256-CBC';

	/**
	 * Construct our object and set encryption key, if exists.
	 *
	 * @param string $encryption_key Users binary encryption key in HEX encoding
	 */
	function __construct ( $encryption_key = false )
	{
		if ( $key = hex2bin ( $encryption_key ) )
		{
			$this->key = $key;
		}
		else
		{
			echo "Key in construct does not appear to be HEX-encoded...";
		}
	}

	public function encrypt ( $string )
	{
		$new_iv = bin2hex ( random_bytes ( openssl_cipher_iv_length ( $this->encrypt_method ) ) );

		if ( $encrypted = base64_encode ( openssl_encrypt ( $string, $this->encrypt_method, $this->key, 0, $new_iv ) ) )
		{
			return $new_iv.':'.$encrypted;
		}
		else
		{
			return false;
		}
	}

	public function decrypt ( $string )
	{
		$parts     = explode(':', $string );
		$iv        = $parts[0];
		$encrypted = $parts[1];

		if ( $decrypted = openssl_decrypt ( base64_decode ( $encrypted ), $this->encrypt_method, $this->key, 0, $iv ) )
		{
			return $decrypted;
		}
		else
		{
			return false;
		}
	}
}

The syntax goes something like this:

# Generate a key for encryption
$hex_key = bin2hex ( random_bytes ( 16 ) ); 

# Initiate a new class object
$abCrypt = new abCrypt($hex_key);

# Perform encryption
$encrypted_txt = $abCrypt->encrypt('Text to encrypt');

# And decryption
echo $abCrypt->decrypt($encrypted_txt);

5 comments

  1. Thanks for the script, nice and clear, but I’m getting “( ! ) Warning: openssl_encrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating in /encryption.class.php on line 52

    Line: 52
    if ( $encrypted = base64_encode ( openssl_encrypt ( $string, $this->encrypt_method, $this->key, 0, $new_iv ) ) )

Leave a Reply to haytham Cancel reply

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