2014-01-15 78 views
0

當我運行的Crypto-JS的加密功能,我給出的base64編碼如下:使用Salt,密碼和類型在PHP中解密?

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

如何在未來的解密方法這PHP?我曾嘗試過使用openSSL,mcrypt等,但似乎沒有什麼工作 - 我想我不知道如何處理base64編碼,salting,VI和其他東西......某處出了問題。

回答

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 
+0

它是不安全的存儲在數據庫什麼的IV?我的用戶知道他們的關鍵,但不是IV。處理IV的最佳方式是什麼? – Paul

+0

沒關係,只是存儲它。 – Paul

+0

我花了兩天的時間來解決這個問題,但找到你的答案,它幾乎工作,但使用$ encrypted = base64_decode(「data_base64」)時出錯。 openssl_decrypt添加無法解碼base64的錯誤,我已經刪除了$ encrypted = base64_decode(「data_base64」),只是在$ encrypted =「data_base64」中生效並且工作完美 – webmak10