使用Javascript(cryptojs)加密,使用php openssl解密,无法重新创建消息密钥

时间:2018-05-12 04:59:52

标签: php cryptojs

我无法通过使用php解密的cryptoj来加密邮件。

在javascript方面,创建加密的代码是:

var keySize = 256;
var ivSize = 128;
var saltSize = 256;
var iterations = 100;

var message = "This is my test";
var password = "thepassword";


function encrypt(msg, pass) {

// Generate salt, key and iv
var salt = CryptoJS.lib.WordArray.random(saltSize / 8);

var key = CryptoJS.PBKDF2(pass, salt, {
    keySize: 256 / 32,
    iterations: iterations
});

console.log('Message key: ' + key);

var iv = CryptoJS.lib.WordArray.random(ivSize / 8);


// encrypt message
var encrypted = CryptoJS.AES.encrypt(msg, key, {
    iv: iv,
    padding: CryptoJS.pad.Pkcs7,
    mode: CryptoJS.mode.CBC

});

// convert encrypted message to hex
var encryptedHex = base64ToHex(encrypted.toString());

// Prepare result to transmit
var base64result = hexToBase64(salt + iv + encryptedHex);

return base64result;

}

这会创建一个字符串,如:

  

g281MRrrEdiysHSAolnMmy3Au3yYkb2TK1t7iF4dv8X2k9Fod1DkOt / LF8eLgX8OxRvkSOMqtrcGEMaCL7A8YVBcugcirNg44HcWGWt + HFA =

当我把它带到php时,我可以正确地拉回发送的部分(盐,iv,消息),但不能解码消息。

$text_key = 'thepassword';
$cipher = "aes-256-cbc";


$received_message = $_REQUEST['message'];

// Decode message and pull out pieces:
$decoded = base64_decode($received_message);

$hex_version = bin2hex($decoded);

// Pull out salt, iv and encrypted message
$salt = substr($hex_version, 0,64);
$iv = substr($hex_version, 64,32);
$encrypted_string = substr($hex_version, 96);

// Message key
$generated_key = bin2hex(openssl_pbkdf2($text_key, $salt, 32, 100, 'sha256'));

// Decode Message
$result = openssl_decrypt($text_encoded, $cipher, $generated_key, $options=0, hex2bin($iv));

但是,如果我用javascript控制台中显示的键替换$ generated_key,则消息会成功解密。

我在PHP中生成密钥的错误做法是什么?

1 个答案:

答案 0 :(得分:0)

创建例程以运行openssl_pbkdf2和hash_pbkdf2函数的所有可能算法后,发现hash_pbkdf2函数是将创建密钥的函数:

$generated_key = hex2bin(hash_pbkdf2('sha1', $text_key, hex2bin($salt), 100, 64, FALSE));

一旦确定了正确的算法和大小,解密就会按预期工作。