Decrypting AES with Javascript CryptoJS after encrypting with PHP mcrypt

末鹿安然 提交于 2019-11-30 19:59:56

问题


Encrypting in PHP with mcrypt

<?php
$string = 'Secret Message';
$key = 'd4b494e4502a62edd695a903a94c2701';
$iv = '02f30dffbb0d084755f438f7d8be4a7d';

$encrypted = base64_encode(
    mcrypt_encrypt(
        MCRYPT_RIJNDAEL_256,
        $key,
        $string,
        MCRYPT_MODE_CBC,
        $iv
    )
);
//$encrypted results in 'nYoFAiyDARVSI09lH/IPdim5TvE51izVjk6sc2AK9Rg='
?>

Decrypting in Javascript with CryptoJS

<script>
var encrypted = 'nYoFAiyDARVSI09lH/IPdim5TvE51izVjk6sc2AK9Rg=';
var key = CryptoJS.enc.Hex.parse('d4b494e4502a62edd695a903a94c2701');
var iv = CryptoJS.enc.Hex.parse('02f30dffbb0d084755f438f7d8be4a7d');

var decrypted = CryptoJS.AES.decrypt(encrypted,key,{iv:iv,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7});

console.log(decrypted.toString(CryptoJS.enc.Utf8)); //prints an empty string
</script>

I can't figure out how to get the Javascript side to spit out the original text.


回答1:


SOLVED

Note: I found out that "MCRYPT_RIJNDAEL_256" in PHP's mcrypt is NOT included in AES. It uses the Rijndael method, BUT with a 256-bit block size (not included in AES). So, CryptoJS does not handle 256-bit block sizes for Rijndael. Thanks, GregS

Nonetheless, I found an implementation that successfully decrypted the ciphertext I get from running my PHP mcrypt function above, using MCRYPT_RIJNDAEL_256 (Rijndael, 256-bit block size, with 256-bit key/32-byte key).

Here it is: https://code.google.com/p/js-mcrypt/

<script>
var encrypted = 'nYoFAiyDARVSI09lH/IPdim5TvE51izVjk6sc2AK9Rg=';
var key = 'd4b494e4502a62edd695a903a94c2701';
var iv = '02f30dffbb0d084755f438f7d8be4a7d';
var decrypted = mcrypt.Decrypt(atob(encrypted), iv, key, 'rijndael-256', 'cbc');
</script>

I hope this helps someone as I spent a week of my spare time trying to figure this out and almost giving up.



来源:https://stackoverflow.com/questions/26623768/decrypting-aes-with-javascript-cryptojs-after-encrypting-with-php-mcrypt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!