加密解密出错

时间:2013-04-04 08:20:57

标签: javascript node.js cryptography node-modules node-crypto

为什么以下代码会在加密中引发DecipherFinal错误 -

  var crypto = require('crypto');
  c=new Date;
  x= (c.getTime()+"."+c.getMilliseconds()).toString()+".uIn";
  key = 'sevsolut'
        , plaintext = x
        , cipher = crypto.createCipher('aes-256-cbc', key)
        , decipher = crypto.createDecipher('aes-256-cbc', key);
  cipher.update(plaintext, 'utf8', 'base64');
  var encryptedPassword = cipher.final('base64')

  decipher.update(encryptedPassword, 'base64', 'utf8');
  var decryptedPassword = decipher.final('utf8');

  console.log('encrypted :', encryptedPassword);
  console.log('decrypted :', decryptedPassword);

1 个答案:

答案 0 :(得分:2)

您需要从更新中获取输出:

var crypto = require('crypto');
c=new Date();
x= (c.getTime()+"."+c.getMilliseconds()).toString()+".uIn";
key = "sevsolut"
      , plaintext = x
      , cipher = crypto.createCipher('aes-256-cbc', key)
      , decipher = crypto.createDecipher('aes-256-cbc', key);
var encryptedPassword = cipher.update(plaintext, 'utf8', 'base64');
encryptedPassword += cipher.final('base64')

var decryptedPassword = decipher.update(encryptedPassword, 'base64', 'utf8');
decryptedPassword += decipher.final('utf8');

console.log('encrypted :', encryptedPassword);
console.log('decrypted :', decryptedPassword);