我正在使用Javascript库CryptoJS从客户端到服务器端进行加密:
function encrypt(msg, pass) {
var salt = CryptoJS.lib.WordArray.random(128/8);
var key = CryptoJS.SHA256(pass);
key = key.toString().substr(0,32);
var iv = CryptoJS.lib.WordArray.random(128/8);
var encrypted = CryptoJS.AES.encrypt(msg, key, {
iv: iv,
//padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC
});
var transitmessage = salt.toString() + iv.toString() + encrypted.toString();
window.location.href="test_cbc.php?action=decrypt&msg=" + transitmessage;
}
在服务器端:
<?php
if(!empty($_GET["action"]) && $_GET["action"]=="decrypt"){
$msg=$_GET["msg"];
echo "<pre>";
$_salt=substr($msg, 0, 32);
$_iv = substr($msg, 32, 32);
$_enc = substr($msg, 64);
$salt = pack("H*", $_salt);
$iv = pack("H*", $_iv);
$encrypted = substr(base64_decode($_enc),16);
$key = hash("SHA256", "helloworld");
$decrypted = openssl_decrypt($encrypted,"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv);
//$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, trim($encrypted), MCRYPT_MODE_CBC, $iv);
echo $decrypted;
echo "</pre>";
}
如果我使用openssl_decrypt,则$ decrypted为空。如果我使用mcrypt,则会得到无法读取的字符。
我的代码有误吗?