Example Using PHP Mcrypt

Monday, February 16, 2009

Unlike md5 hash, mcrypt gives you option to decrypt the encrypted data. This is is useful when you need to decrypt the ecryted data at some point. Mcrypt library offers more than 30 ciphers to use in encryption and the possibility of passphrase that can decrypt data.

Let's get to the code

<?php
$data = 'your data to be encrypted';
$key = 'secret passphrase to encrypt';
$cipher = "MCRYPT_SERPENT_256";
$mode = "MCRYPT_MODE_CBC";

function m_encrypt($data, $key, $cipher, $mode){
 return (string) 
  base64_encode(
   mcrypt_encrypt(
    $cipher,
    substr(md5($key),0,mcrypt_get_key_size($cipher, $mode)),
    $data,
    $mode,
    substr(md5($key),0,mcrypt_get_block_size($cipher, $mode))
   )
  );
}

function m_decrypt($data, $key, $cipher, $mode){
 return (string)
   mcrypt_decrypt(
    $cipher,
    substr(md5($key),0,mcrypt_get_key_size($cipher, $mode)),
    base64_decode($data),
    $mode,
    substr(md5($key),0,mcrypt_get_block_size($cipher, $mode))
   );
}
?>


The mcrypt() function requires several parameter
  • The data to be encrypted
  • The passphrase to encrypt and unlock data
  • The cipher to encrypt the data, which is the specific algorithm to encrypt the data. There are many options like MCRYPT_SERPENT_256, MCRYPT_TWOFISH192, MCRYPT_RC2, MCRYPT_DES, and MCRYPT_LOKI97. You can find these options in phpinfo() page if mcrypt is available
  • The mode to encrypt the data, there are several modes like Electronic Codebook and Cipher Feedback. The script above using MCRYPT_MODE_CBC, Cipher Block Chaining
  • Initialization vector, alias IV, or a seed, and additional bit of binary data to seed the encryption algorithm, simply to make the algorithm harder to crack
  • The length of the string needed for the key and IV. Use mcrypt_get_key_size() and mcrypt_get_block_size functions to find the appropriate lengthm then trim the key value with substr() function. If the key is shorter than the required value, mcrypt will pads it with zeros
Feel free to experimenting with various encryption methods with the script to understand it better. Hope it helps.

0 comments: