Abul Hasnat
Abul Hasnat

Reputation: 1631

Porting AES decryption from CryptoJS to Php

I am trying to convert a AES decryption function from JavaScript into PHP script. Ignoring the indentation for easy to read.

var enc = 'EK/tvL3RsjOY1j82ILXv7W10bEU83JeaiBhlLmcZIrk=';

var key = 'FSHcT+sfRO/siok2ooweuA==' ;

var y = CryptoJS.AES.decrypt({ciphertext:     CryptoJS.enc.Base64.parse(enc)}, 
CryptoJS.enc.Base64.parse(key), 
{iv: CryptoJS.enc.Hex.parse("2323232323232323")});

var dec = y.toString(CryptoJS.enc.Utf8);

In the PHP I have tried

$iv = mcrypt_create_iv(16, '2323232323232323'); 

$enc = 'EK/tvL3RsjOY1j82ILXv7W10bEU83JeaiBhlLmcZIrk=';

$key = 'FSHcT+sfRO/siok2ooweuA==' ;

$dec = rtrim((mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $enc, MCRYPT_MODE_CBC, $iv)), "\0\3");

In Javascript decrypting working fine but when I execute the PHP it gives me strange charecters.

Upvotes: 1

Views: 264

Answers (2)

webdeb
webdeb

Reputation: 13211

You should use the mcrypt extension (wich is implemented in C), so you don't need to port JS code.

http://php.net/manual/en/book.mcrypt.php

Upvotes: 0

Scott Arciszewski
Scott Arciszewski

Reputation: 34113

Warning: This is Weak Cryptography

  • You're using CBC mode with a constant IV of null bytes (the IV should be randomly generated for each message).
  • You're not authenticating your ciphertext.
  • Naive use of rtrim() exposes your application to padding oracle attacks, which wouldn't be a problem if you were following an Encrypt Then MAC construction.

The Actual Bugs in Your Code

$iv = mcrypt_create_iv(16, '00000000000000000000000000000000'); 

That's not how this function is meant to be used.

string mcrypt_create_iv(int $length, int $source);

For example: mcrypt_create_iv(16, MCRYPT_DEV_URANDOM); will generate 16 bytes of random data from /dev/urandom. It looks like you want str_repeat("\0", 16) here, but as I said above, this is a horrible idea.

You also didn't base64_decode() the key.


I really hope you aren't deploying this code anywhere.

Recommended reading: Write crypto code! Don't publish it! by Talyor Hornby.

Also, if you can avoid using mcrypt, you'll find yourself a lot happier.

Upvotes: 4

Related Questions