【问题标题】:Encrypt with Javascript (cryptojs), Decrypt with php openssl, can't recreate message key使用 Javascript (cryptojs) 加密,使用 php openssl 解密,无法重新创建消息密钥
【发布时间】:2018-05-12 04:59:51
【问题描述】:

我在获取使用 php 解密的 cryptojs 加密的消息时遇到问题。

在 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));

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

我在 php 中生成密钥时做错了什么?

【问题讨论】:

    标签: php cryptojs


    【解决方案1】:

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

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

    一旦有了正确的算法和大小,解密就会按预期进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-20
      • 2018-02-13
      • 2014-12-16
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2012-12-04
      • 2017-05-04
      相关资源
      最近更新 更多