AES encryption in php and then decryption with Javascript (cryptojs)

Lyubomir Lyubenov picture Lyubomir Lyubenov · Aug 3, 2012 · Viewed 11.3k times · Source

I'm searching for a way to make a 2 way encryption of a simple text (5 to 6 numbers and/or characters). The catch is that i want to make the encryption in php and then decrypt it via Javascript. For php i've tested using mcrypt_encode and have gotten it to work, hence when i try to decrypt it with javascript (i'm using the Crypto-js library - http://code.google.com/p/crypto-js/ ) i get no results. Here is the php code i'm using:

$key = "oijhd981727783hy18274";
$text = "1233";
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC,$iv);
echo base64_encode($crypttext);

and then here is the Javascript code i'm using:

var encrypted = CryptoJS.enc.Base64.parse("LiJU5oYHXRSNsrjMtCr5o2ev7yDFGZId85gh9MEXPeg=");
var key = 'oijhd981727783hy18274';
var decrypted = CryptoJS.AES.decrypt(encrypted, key);
document.write( decrypted.toString(CryptoJS.enc.Utf8) );

As i'm just testing, i copy/paste the output from the php straight into the JS and see if it would return any results, however that doesnt happen. As i'm new to the encryption/decryption part i might be missing something. Any suggestions will be greatly appreciated.

On a side note, as i read a lot of suggestions here about using other types of communication to transfer the data, that would not be possible in this case, as i need to pass this string to a third party software, which will bring it over on a secure area, where i have access to edit only the javascript, this is why i'm trying to encrypt the text in php and place it inside the website's source, from where the third party software will read it as it is encrypted and will transfer it to the secure section, where i will need to decrypt it back via Javascript (i dont have access to php there).

Answer

Lyubomir Lyubenov picture Lyubomir Lyubenov · Aug 3, 2012

So, after some more digging i came to the following online encryptor/decryptor which led me to the gibberish-aes at GitHub repository.

Inside one of the comments on the first link i found that this JS library has a php equivalent, which seems to be working reasonably well and is fairly easy to deploy: https://github.com/ivantcholakov/gibberish-aes-php

So thanks to Lars for the answer he provided, i would encourage him to open the repository, i'm sure he'll make someone's life a little bit easier :)