3

我在将 AES 解密用于缓冲区对象时遇到问题,我希望有人知道我做错了什么......

MyExample:我有一个带有 AES_ENCRYPT 用户名和密码的 MySQL 表...

CREATE TABLE Accounts 
(
    id INT(4) NOT NULL AUTO_INCREMENT,
    username VARBINARY(128) NOT NULL,
    password VARBINARY(128) NOT NULL,
    PRIMARY KEY(id)
);

DELIMITER |
CREATE TRIGGER encodeAccounts BEFORE INSERT ON Accounts
FOR EACH ROW BEGIN
    SET NEW.username = AES_ENCRYPT(NEW.username, 'password');
    SET NEW.password = AES_ENCRYPT(NEW.password, 'password');
END;

Node.JS:我正在使用 node-mysql 模块向我的数据发送查询:

SELECT * FROM Accounts;

为密码和用户名返回此类值:

<Buffer 07 86 95 ee 77 df 86 50 ae 18 4c d5 3e 48 42 75>

如何使用 Node.JS 解密方法对其进行解码?我的尝试都失败了...我希望正确选择 AES-128-ECB...

要解读 Node.JS 中的某些内容,应该如下所示:

var decipher = crypto.createDecipher('AES-128-ECB', 'password');
var dec = decipher.update(rows[i].username); // an example, value look like <Buffer ...
dec += decipher.final('utf8');
console.log('dec: ' + dec);

感谢所有帮助:)

4

1 回答 1

10

您的密码必须以与 MySQL 内部执行相同的方式进行转换。必须产生一个 16 字节长度的密码 XORd 以获得更长的密码或用 0 字节填充。这个功能应该做的工作:

function convertCryptKey(strKey) {
    var newKey = new Buffer([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);
    strKey = new Buffer(strKey);
    for(var i=0;i<strKey.length;i++) newKey[i%16]^=strKey[i];
    return newKey;
}

MySQL 兼容的加密- 注意使用带有空 IV 的“createCipheriv”。(createCipher 创建一个自己的 IV,这与 MySQL 中的不同)

var c = crypto.createCipheriv("aes-128-ecb", convertCryptKey("myPassword"), "");
var crypted = c.update('Take a trip at galaxytrek.com :)', 'utf8', 'hex') + c.final('hex');
console.log(crypted.toUpperCase());
>> 92068A5DAECE1E080EF4BA08A45CFF8D2262401F988A9241F1E4CEAAAB80BEAF7E0B50A1D5FD57CA56E92621622F018D

这与以下内容相同:

mysql> select hex(aes_encrypt('Take a trip at galaxytrek.com :)','myPassword'));
+--------------------------------------------------------------------------------------------------+
| hex(aes_encrypt('Take a trip at galaxytrek.com :)','myPassword'))                                |
+--------------------------------------------------------------------------------------------------+
| 92068A5DAECE1E080EF4BA08A45CFF8D2262401F988A9241F1E4CEAAAB80BEAF7E0B50A1D5FD57CA56E92621622F018D |
+--------------------------------------------------------------------------------------------------+

解密

var dc = crypto.createDecipheriv("aes-128-ecb", convertCryptKey("myPassword"), "");
var decrypted = dc.update('92068A5DAECE1E080EF4BA08A45CFF8D2262401F988A9241F1E4CEAAAB80BEAF7E0B50A1D5FD57CA56E92621622F018D', 'hex', 'utf8') + dc.final('utf8');
console.log(decrypted);
>> Take a trip at galaxytrek.com :)
于 2013-06-21T08:33:06.013 回答