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
它是不安全的存儲在數據庫什麼的IV?我的用戶知道他們的關鍵,但不是IV。處理IV的最佳方式是什麼? – Paul
沒關係,只是存儲它。 – Paul
我花了兩天的時間來解決這個問題,但找到你的答案,它幾乎工作,但使用$ encrypted = base64_decode(「data_base64」)時出錯。 openssl_decrypt添加無法解碼base64的錯誤,我已經刪除了$ encrypted = base64_decode(「data_base64」),只是在$ encrypted =「data_base64」中生效並且工作完美 – webmak10