使用加密时,NodeJS解密失败。有什么问题

时间:2018-10-25 05:20:44

标签: node.js encryption aes

var decipher = Crypto.createDecipheriv('aes-256-cfb', 'testtesttesttesttesttest', 'testtesttesttest')

Error: Invalid key length
    at new Decipheriv (crypto.js:267:16)
    at Object.createDecipheriv (crypto.js:627:10)

这是我得到的错误。我要去哪里错了?

2 个答案:

答案 0 :(得分:1)

如果我们尝试另一种方法?如本例所示:

function encryptdata(key, text) {

  const hash = crypto.createHash('sha256');
                   hash.update(key);
  const keyBytes = hash.digest();

  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv('aes-256-cfb', keyBytes, iv);
  let enc = [iv, cipher.update(text, 'utf8')];
  enc.push(cipher.final());
  return Buffer.concat(enc).toString('base64');
}

答案 1 :(得分:1)

密钥的长度必须恰好为32个字节。 请尝试下面的代码,看看是否有效。

var crypto = require('crypto');
var key = 'testtesttesttesttesttesttesttest';

try{
var cipher = crypto.createCipheriv('aes-256-cfb', key, 'testtesttesttest');
var encryptedData = cipher.update("hello", 'utf8', 'hex') + cipher.final('hex');
console.log(encryptedData);

var decipher = crypto.createDecipheriv('aes-256-cfb', key, 'testtesttesttest');
var decryptedData = decipher.update(encryptedData, 'hex', 'utf8') + decipher.final('utf8');
console.log(decryptedData);
} catch(exception) {
    console.error(exception);
}