这个简单的NodeJS加密功能有什么问题?

Den*_*tor 2 encryption aes node.js

我正在尝试使用url查询字符串的零填充来执行AES CBC加密.我正在使用NodeJS的核心加密模块.它适用于http://www.blackoutrugby.com/game/help.documentation.php#category=35

我有钥匙和IV.在测试以下函数时,我没有得到完全返回的字符串.我相信这与填充有关,但我不确定如何正确应用它.

如果它是填充,任何人都可以告诉我应该如何应用它?如果不是我在哪里错了?此用户案例中的cipher.final()也是重要的?

更新: 我现在已经包含了cipher.final(),二进制格式的工作正常,但base64给了我截断的结果.https://github.com/denishoctor/BlackoutRugbyNode/blob/master/crypto2.js是我的完整示例代码.以下是加密功能:

function cryptoTest(data, key, iv, format) {
   var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
   var cipherChunks = [];
   cipherChunks.push(cipher.update(data, 'utf8', format));
   cipherChunks.push(cipher.final());

   var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
   var plainChunks = [];
   for (var i = 0;i < cipherChunks.length;i++) {
        plainChunks.push(decipher.update(cipherChunks[i], format, 'utf8'));
   }
   plainChunks.push(decipher.final());

   return {
       "encrypted": cipherChunks.join(''),
       "decrypted": plainChunks.join('')
   };
}
Run Code Online (Sandbox Code Playgroud)

谢谢,
丹尼斯

Pet*_*ons 5

您没有将cipher.final返回的密文放入解密中.这是一个简化的例子.您需要从每次调用cipher.update以及cipher.final收集返回值,并确保将每个对象放入decipher.update.

更新:这是一个可以正常使用binaryhex作为密文的编码的版本,但失败了base64.我不知道为什么会这样,但如果你对十六进制没问题那应该可以正常工作.

更新2:看起来像base64节点本身的错误.查看类似问题的答案.

    var crypto = require('crypto');

    var data = "I am the clear text data";
    console.log('Original cleartext: ' + data);
    var algorithm = 'aes-128-cbc';
    var key = 'mysecretkey';
    var clearEncoding = 'utf8';
    var cipherEncoding = 'hex';
    //If the next line is uncommented, the final cleartext is wrong.
    //cipherEncoding = 'base64';
    var cipher = crypto.createCipher(algorithm, key);
    var cipherChunks = [];
    cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
    cipherChunks.push(cipher.final(cipherEncoding));
    console.log(cipherEncoding + ' ciphertext: ' + cipherChunks.join(''));
    var decipher = crypto.createDecipher(algorithm, key);
    var plainChunks = [];
    for (var i = 0;i < cipherChunks.length;i++) {
      plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));

    }
    plainChunks.push(decipher.final(clearEncoding));
    console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));
Run Code Online (Sandbox Code Playgroud)