AES-256-CBC Mcrypt-PHP解密和Crypto-JS加密

时间:2014-01-17 08:01:38

标签: javascript php encryption aes cryptojs

我正在尝试使用CryptoJS在Javascript中加密并在PHP中解密。 JS代码是:

var salt = CryptoJS.lib.WordArray.random(128/8); 
var key256Bits500Iterations = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 256/32, iterations: 500 });
var iv  = CryptoJS.enc.Hex.parse('101112131415161718191a1b1c1d1e1f'); // just chosen for an example, usually random as well

encrypted = CryptoJS.AES.encrypt("Message", key512Bits1000Iterations, { iv: iv });  
var data_base64 = crypted.ciphertext.toString(CryptoJS.enc.Base64);
var iv_base64   = crypted.iv.toString(CryptoJS.enc.Base64);
var key_base64  = crypted.key.toString(CryptoJS.enc.Base64);

PHP如下:

$encrypted = base64_decode($data_base64);
$iv = base64_decode($iv_base64);
$key = base64_decode($key_base64); 

    $plaintext = mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv);
echo ($plaintext);  

这不会返回正确的答案。

我不确定事情进展顺利!我需要做自己的IV,但如果我只是说:

CryptoJS.AES.Encrypt("Message", "Secret Passphrase");
var data_base64 = crypted.ciphertext.toString(CryptoJS.enc.Base64);
var iv_base64   = crypted.iv.toString(CryptoJS.enc.Base64);
var key_base64  = crypted.key.toString(CryptoJS.enc.Base64);

它成功地在PHP代码中工作 - 只有key_base64不是可以更改的东西,它必须是用户记住的...然后它给了我一个盐从密码短语中获取密钥输入和IDK如何使用CryptoJS设法获得它

1 个答案:

答案 0 :(得分:15)

如果您只是在那里修改一些拼写错误,那么您的代码将会起作用

<强> JS

    <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
    <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/pbkdf2.js"></script>
    <script>
        var salt = CryptoJS.lib.WordArray.random(128/8); 
        var key256Bits500Iterations = CryptoJS.PBKDF2("Secret Passphrase", salt, { keySize: 256/32, iterations: 500 });
        var iv  = CryptoJS.enc.Hex.parse('101112131415161718191a1b1c1d1e1f'); // just chosen for an example, usually random as well

        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);
    </script>

<强> PHP

    <?php
        $encrypted = base64_decode("data_base64"); // data_base64 from JS
        $iv        = base64_decode("iv_base64");   // iv_base64 from JS
        $key       = base64_decode("key_base64");  // key_base64 from JS

        $plaintext = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv ), "\t\0 " );