Encryption & Decryption Using Mcrypt In PHP


Read {count} times since 2020

Mcrypt is a replacement of Unix‘s popular command crypt. It is a file encryption tool. Mcrypt uses modern algorithms for encrypting. Hence it is considered as secure and safe. To encrypt a string, Mcrypt requires a key to encrypt and decrypt. This key have a critical role in encryption and decryption. In this post I’ll be giving out two functions that will encrypt and decrypt based on a key.

The Key

We should use the same key for both encryption and decryption. Note that the key length should not exceed 25 characters.

For this post, we are going to take

a_key_in_2014

as the key. The variable $key contains the key in the functions used for encryption and decryption.

Encryption

This small function will encrypt any string :

function encrypt($value){
  if($value == ''){
    return false;
  }else{
    $key     = "a_key_in_2014";
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv      = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $crypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $value, MCRYPT_MODE_ECB, $iv);
    return urlencode(trim(base64_encode($crypted)));
  }
}

Usage

You can encrypt a string just like this :

<?
echo encrypt("subinsb.com");
?>

The above will print out the encrypted string :

Rl3PeBCve4vjjwu1SgzFvvj%2BG3Prl2TDN2AmXrWKSqw%3D

As you can see, it’s hard to figure out the original string from above.

Decryption

This small function will decrypt strings that are encoded with the same key :

function decrypt($value){
  $key = "a_key_in_2014";
  $value = urldecode($value);
  if($value == "" || base64_encode(base64_decode($value)) != $value){
    return $value;
  }else{
    $crypttext = base64_decode($value);
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_ECB, $iv);
    return trim($decrypted);
  }
}

Usage

The decryption is also easy :

echo decrypt("Rl3PeBCve4vjjwu1SgzFvvj%2BG3Prl2TDN2AmXrWKSqw%3D");

And the above code will output “subinsb.com” which was the original string.

You can use this functions wherever you want. This trick is used in Open for encrypting and decrypting.

Show Comments