OpenSSL AES 256 CBC encryption in PHP
define('AES_METHOD', 'AES-256-CBC');
 
class AES256 
{
    public function Encrypt($password, $plainText)
    {
        if(empty($password) || empty($plainText))
        {
            return FALSE;
        }
 
	//generate a random salt
	$Salt = openssl_random_pseudo_bytes(8);
	if($Salt === FALSE){
            return FALSE;
        }
 
	//generate a random initialization vector
	$IV = openssl_random_pseudo_bytes(
                  openssl_cipher_iv_length(
			AES_METHOD));
        if($IV === FALSE){
            return FALSE;
        }
 
	//generate aes key
	$pwd = substr(hash('sha256', $password), 0, 32);
	$Key = openssl_pbkdf2($pwd, $Salt, 32, 5);
	if($Key === FALSE){
            return FALSE;
        }
 
	//encrypt message
        $cipherText = openssl_encrypt($plainText, 
			AES_METHOD, $Key, true, $IV);
 
	//check if encryption failed
        if($cipherText === FALSE){
            return FALSE;
        }
 
	//create something safer than the following code
	//this is just a demonstration
        $IV64 = base64_encode($IV);
	$Salt64 = base64_encode($Salt);
	$Cipher64 = base64_encode($cipherText);
 
	if($IV64 === FALSE || $Salt64 === FALSE || $Cipher64 === FALSE)
	{
	    return FALSE;
	}
 
        return base64_encode($IV64.'^^'.$Cipher64.'**'.$Salt64);
    }
 
    public function Decrypt($password, $cipherText)
    {
        if(empty($password) || empty($cipherText))
        {
            return FALSE;
        }
 
        $decoded = base64_decode($cipherText);
        if($decoded === FALSE){
            return FALSE;
        }
 
	//locate iv value
	$IV = base64_decode(substr($decoded, 0, 
			strpos($decoded, '^^')));
        if($IV === FALSE){
            return FALSE;
        }
 
	//locate salt value
	$encodedSalt = substr($decoded, 
	    strpos($decoded, '**') + 2, strlen($decoded));
	$Salt = base64_decode($encodedSalt);
        if($Salt === FALSE){
            return FALSE;
        }
 
        //locate cipher text
	$ciphertext = base64_decode(substr($decoded, 
		strpos($decoded, '^^') + 2, 
		-(strlen($encodedSalt)+2)));
        if($ciphertext === FALSE){
            return FALSE;
        }
 
	//generate aes key
	$pwd = substr(hash('sha256', $password), 0, 32);
	$Key = openssl_pbkdf2($pwd, $Salt, 32, 5);
	if($Key === FALSE){
            return FALSE;
        }
 
        return openssl_decrypt($ciphertext, AES_METHOD, $Key, true, $IV);
    }
}

Usage:

define('PASSWORD', '1b!0n#2h5j4$u8y4%g5b2n3&f1v0b*2g5h(3nr)8');
 
$encryptor = new AES256();
 
$cipher = $encryptor->Encrypt(PASSWORD, 'Hello, world!');
if($cipher)
{
    echo 'Encrypted: '.$cipher.'<br><br>';
    echo 'Decrypted: '.$encryptor->Decrypt(PASSWORD, $cipher);
}
Categories: PHP Tags: , , ,
%d bloggers like this: