使用Salt,密码和类型在PHP中解密?

时间:2014-01-15 06:24:55

标签: javascript php encryption aes

当我运行Crypto-JS的加密函数时,我得到了base64编码的以下内容:

var crypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase",  {mode: CryptoJS.mode.CBC}).toString();
==>  "U2FsdGVkX19HKyOimD43Bl4ww/I40M+NQrscjti3ZnA="

我将来如何在PHP中解密这个问题?我尝试过使用openSSL,mcrypt等,似乎没什么用 - 我想我不知道如何处理base64编码,salting,VI等等......某些地方出了问题。

1 个答案:

答案 0 :(得分:4)

<强> JS

    // encrypt data with CryptoJS

    var crypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");

    // get additional info from CryptoJS ecnrypted data

    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"); // data_base64 from JS
    $iv        = base64_decode("iv_base64");   // iv_base64 from JS
    $key       = base64_decode("key_base64");  // key_base64 from JS

    /* MCRYPT */
    $plaintext = mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $iv );

    // remove padding added by crypt algorithms
    $plaintext = rtrim($plaintext, "\t\0 "); // remove tab-, zero- and space-padding

    /***************************************/
    /* OPENSSL */
    $plaintext = openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
    // or
    $plaintext = openssl_decrypt("data_base64", 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv); // works with base64 encoded data from JS