Harry Forbess
Harry Forbess

Reputation: 2134

mcrypt_decrypt PHP proper usage

I think my PHP intall might have problems. When I try to do this I get

Warning: mcrypt_decrypt() [function.mcrypt-decrypt]: Module initialization failed

I am writing a small snippet of code that will decrypt the following string encrypted with AES-128 using mode ECB.

Key (encoded in base64): aXJhbmRvbXNlY3VyZWtleQ==

Encrypted string> (encoded in base64): 3l6xiNdgRG+PkBw5M0lawvJ/fmuTZPRhEcbtqAmOpDI=

I keep getting module errors.

This is what I have tried:

<?PHP
$retval = mcrypt_decrypt( "AES-128",
    base64_decode( "aXJhbmRvbXNlY3VyZWtleQ=="), 
    base64_decode( "3l6xiNdgRG+PkBw5M0lawvJ/fmuTZPRhEcbtqAmOpDI") ,
    "ECB");

echo $retval;
?> 

here is my relevant phpinfo. I dont see AES-128 . Maybe thats the problem.

    mcrypt
    mcrypt support  enabled
    Version     2.5.8
    Api No  20021217
    Supported ciphers   cast-128 gost rijndael-128 twofish arcfour      cast-256           loki97      rijndael-192 saferplus wake blowfish-compat des rijndael-256 serpent xtea blowfish enigma rc2 tripledes
    Supported modes     cbc cfb ctr ecb ncfb nofb ofb stream 

Upvotes: 3

Views: 11484

Answers (1)

drew010
drew010

Reputation: 69927

You are close, there are 2 small problems.

First, AES-128 is not a valid cipher constant from mcrypt. AES is really rijndael which you have support for. The mcrypt cipher constant for AES-128 is MCRYPT_RIJNDAEL_128 which is the string rijndael-128. Second, the mcrypt mode must be lowercase.

Changing your code to:

<?php
$retval = mcrypt_decrypt( "rijndael-128",
    base64_decode( "aXJhbmRvbXNlY3VyZWtleQ=="), 
    base64_decode( "3l6xiNdgRG+PkBw5M0lawvJ/fmuTZPRhEcbtqAmOpDI") ,
    "ecb");

echo $retval;

yields the correct output of: Is 3 random enough?

Personally, I'd go with the mcrypt constants rather than the actual strings, so replace rijndael-128 with MCRYPT_RIJNDAEL_128 and ecb with MCRYPT_MODE_ECB.

On a side note, consider using CBC with an IV instead of ECB if you are encrypting lots of sensitive information.

Mcrypt can easily create IVs for you with the proper lengths. Sample code:

$ivsize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv     = mcrypt_create_iv($ivsize);

Use this IV when encrypting and decrypting. You can pass the IV along with your data as a base64 encoded string for portability.

Upvotes: 5

Related Questions