Thursday, November 22, 2012

Encrypt and decrypt string using AES 128 and PKCS7 algorithm using Php

Encrypt and decrypt string using AES algorithm executed by PHP script is given below:


<?php
function encrypt($key, $to_encrypt)
{
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
    $pad = $iv_size - (strlen($to_encrypt) % $iv_size);
    $to_encrypt = str_pad($to_encrypt, ($iv_size * (floor(strlen($to_encrypt) / $iv_size) + 1)), chr($pad));
    return base64_encode($iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $to_encrypt, MCRYPT_MODE_CBC, $iv));
}

function decrypt($key, $to_decrypt)
{
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = substr($to_decrypt, 0, $iv_size);
    $to_decrypt = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, substr($to_decrypt, $iv_size), MCRYPT_MODE_CBC, $iv);
    $pad = ord($to_decrypt[strlen($to_decrypt) - 1]);
    return substr($to_decrypt, 0, -$pad);
}

$key = "1111111111111111";

$str = "Value to be encrypt";
$enc = encrypt($key, $str);
$dec = decrypt($key, base64_decode($enc));

echo "Original=" . $str;
echo "<BR>Encrypted=" . $enc;
echo "<BR>Decrypted=" . $dec;

Below is output:

Original=Value to be encrypt
Encrypted=fyqhmBCGLVXcT5tvq38G/MAlpgP2FYq29wgC7KIMT8jt6Z45cq63oJeY8kGgv9QP
Decrypted=Value to be encrypt
 
 

1 comment: