I've problem with decryption data encrypted in cryptojs. Sometimes it works sometimes not, if works it returns "Message", but if dosent it returns garbage.
var salt = CryptoJS.lib.WordArray.random(128/8);
var key256Bits500Iterations = CryptoJS.PBKDF2("password", salt, { keySize: 256/32, iterations: 5 });
var iv = CryptoJS.enc.Hex.parse('1011121c1d1e1f');
var encrypted = CryptoJS.AES.encrypt("Message", key256Bits500Iterations, { iv: iv });
var data_base64 = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
var iv_base64 = encrypted.iv.toString(CryptoJS.enc.Base64);
var key_base64 = encrypted.key.toString(CryptoJS.enc.Base64);
PHP
$encrypted = base64_decode($_POST['data']); /
$iv = base64_decode($_POST['iv']);
$key = base64_decode($_POST['key']);
$plaintext = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, rtrim($key, "\t0円\r\n "), rtrim($encrypted, "\t0円\r\n "), MCRYPT_MODE_CBC, $iv ), "\t0円\r\n ");
I would like to stay on cryptoJS.
-
garbage is normal if you're doing something wrong in the decryption. you can use any key you want for decryption, but only ONE key will give you the original plaintext again.Marc B– Marc B2014年12月12日 21:25:43 +00:00Commented Dec 12, 2014 at 21:25
-
Your IV is too short. It should be 16 bytes or 32 hex characters. You should proabably use a random IV. If you're sending the key with the data, why even bother encrypting it?Artjom B.– Artjom B.2014年12月13日 00:29:53 +00:00Commented Dec 13, 2014 at 0:29
-
It's just for testing, firstly im just trying to create workable php<>javascript encryption. Also tried now to generated 32char iv, and error still occurs, sometimes it works sometimes not.user3949666– user39496662014年12月13日 06:40:30 +00:00Commented Dec 13, 2014 at 6:40
2 Answers 2
Finally i've ended with: http://wiki.birth-online.de/snippets/php/aes-rijndael http://wiki.birth-online.de/snippets/javascript/aes-rijndael
but it still needed some tweaking so:
$crypted = rtrim($_POST['msg'],'\t0円\r\n ');
$crypted = str_replace(" ","+",$crypted);
$password = 'itsmysecret';
$blocksize = 256;
$decrypted = AES::decrypt($crypted, $password, $blocksize);
Now it works.
Comments
You shouldn't rtrim the key. The key may contain any byte value, including the ones you just trimmed away. Older versions happily fill the key up with 0 valued bytes, so that means that the key may differ from the one used in the CryptoJS source.
Sending the key with the ciphertext doesn't make sense. Instead it is best to use PBKDF2 in PHP as well and calculate the key from a password.
Finally, note that PHP mcrypt defaults to zero padding, unpad using PKCS#7 instead. The comments for mcrypt on the help pages contain a good PKCS#7 implementation to perform the unpadding.