【发布时间】:2016-09-14 07:42:41
【问题描述】:
我正在尝试使用 Node 的 mycrypt 模块将旧 PHP 应用程序中的加密功能重新创建到新的 Node JS 应用程序中。
我的目标是确保给定相同的原始字符串和盐,下面的 PHP 脚本生成与 Node 脚本相同的加密值。
PHP
<?php
$string = 'This is my password';
$salt = 'sodiumChloride12';
$encrypted = base64_encode(
mcrypt_encrypt(
MCRYPT_RIJNDAEL_128,
$salt,
$string,
MCRYPT_MODE_ECB,
mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND)
)
);
echo "Encrypted: $encrypted\n";
它产生:
Encrypted: iOKEAxaE4vIeWXBem01gHr2wdof7ZO2dld3BuR9l3Nw=
JavaScript
var mcrypt = require('mcrypt');
var MCrypt = mcrypt.MCrypt;
// Set algorithm and mode
var rijndaelEcb = new MCrypt('rijndael-128', 'ecb');
// Set up salt and IV
var salt = 'sodiumChloride12';
var iv = rijndaelEcb.generateIv();
rijndaelEcb.open(salt, iv);
/** ENCRYPTION **/
var cipher = rijndaelEcb.encrypt('This is my password');
var cipherConcat = Buffer.concat([iv, cipher]).toString('base64');
console.log('Encrypted: ' + cipherConcat);
/** DECRYPTION **/
// Convert back from base64
var ivAndCipherText = new Buffer(cipherConcat, 'base64');
// Undo concat of IV
var ivSize = rijndaelEcb.getIvSize();
iv = new Buffer(ivSize);
var cipherText = new Buffer(ivAndCipherText.length - ivSize);
ivAndCipherText.copy(iv, 0, 0, ivSize);
ivAndCipherText.copy(cipherText, 0, ivSize);
var plaintext = rijndaelEcb.decrypt(cipherText).toString();
console.log('Decrypted: ' + plaintext);
Node 版本产生:
Encrypted: 834aJoVRxla/fGNACUAVFYjihAMWhOLyHllwXptNYB69sHaH+2TtnZXdwbkfZdzc
Decrypted: This is my password
基于它解密原始短语的事实,我知道调用按预期工作,但加密输出与 PHP 脚本中的不同。解密逻辑来自this answer,但我更关心的是让加密以同样的方式工作。
我在 Node 中的 IV 与在 PHP 中的做法不同吗?
我查看了this question,但它使用crypto 模块而不是我正在使用的mcrypt 模块。
【问题讨论】:
标签: javascript php node.js encryption mcrypt