Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CryptoJS encrypts AES with passphrase but PHP decrypt needs a key

I am using CryptoJS to encrypt a string:

  function doHash(msg){
    msg = String(msg);
    var passphrase = 'aggourakia';
    var hash = CryptoJS.AES.encrypt(msg, passphrase);
    var ciphertext=  hash.ciphertext.toString(); //return ciphertext instead of object
    return ciphertext;      
}

As I understand it, CryptoJS uses the passphrase to generate a key, which is then used to encrypt the data.

However I'd like to decrypt the cipher using a PHP function, or maybe an online tool such as this: http://aesencryption.net/

The issue is that these expect a key, not a passphrase.

How can I supply directly a key to the CryptoJS AES, which I can use on the server-side or any online tool to decrypt?

The thing is, I already have a really hard time finding PHP functions to decrypt AES ciphers already, and this passphrase/key thing is adding to the complexity

like image 899
nicholaswmin Avatar asked Sep 30 '22 14:09

nicholaswmin


1 Answers

If you want to supply the key directly you should supply IV too. The IV (initialization vector) is needed so it can be XOR'ed with the 1st block of the message. Then the ciphertext of the first block is XOR'ed with the 2nd block of the message and so on. This is called cipher-block chaining (CBC).

var key = CryptoJS.enc.Hex.parse('000102030405060708090a0b0c0d0e0f');
var iv  = CryptoJS.enc.Hex.parse('101112131415161718191a1b1c1d1e1f');

var encrypted = CryptoJS.AES.encrypt("Message", key, { iv: iv });

This is from CryptoJS docs https://code.google.com/p/crypto-js/#Custom_Key_and_IV

You can generate keys and IVs with PBKDF2 like @Narf wrote. https://code.google.com/p/crypto-js/#PBKDF2

About PHP: mcrypt has MCRYPT_RIJNDAEL_128 cipher which is AES 128. MCRYPT_RIJNDAEL_192 and MCRYPT_RIJNDAEL_256 are not compatible with AES 192 and AES 256 because AES uses 128 bit block with all key sizes. Rijndael's has a configurable block size. CryptoJS will use 128bit AES if you supply a 128 bit key it will use 256 bit if you use the function that accepts a passphrase.

like image 199
Dmitry Avatar answered Oct 02 '22 13:10

Dmitry