drtwqc3744 2018-05-12 04:59
浏览 132
已采纳

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

I'm having trouble getting a message encrypted with cryptojs decrypted with php.

On the javascript side, the code to create the encryption is:

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;

}

This creates a string like:

g281MRrrEdiysHSAolnMmy3Au3yYkb2TK1t7iF4dv8X2k9Fod1DkOt/LF8eLgX8OxRvkSOMqtrcGEMaCL7A8YVBcugcirNg44HcWGWt+hfA=

When I bring that into php, I can correctly pull back the pieces sent (salt, iv, message), but can't decode the message.

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

If I replace $generated_key with the key displayed in the javascript console, however, the message decrypts successfully.

What am I doing incorrectly to generate the key in php?

  • 写回答

1条回答 默认 最新

  • dongyinju5977 2018-05-15 03:12
    关注

    After creating a routine to run through all possible algorithms for openssl_pbkdf2 and the hash_pbkdf2 functions, discovered that the hash_pbkdf2 function is the one that will create the key:

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

    Once the right algorithm and size was in place, the decryption works as expected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作