1

我不能crypto去上班。

  • 视窗 7 64 位
  • node.js v0.10.18

加密似乎有效:

var fs = require('fs');

var img = new Buffer (fs.readFileSync('./image.png'), 'binary');

var crypto = require('crypto')
   , key = 'salt_from_the_user_document'
   , plaintext = img
   , cipher = crypto.createCipher('aes-256-cbc', key)
   , decipher = crypto.createDecipher('aes-256-cbc', key);

cipher.update(plaintext, 'binary', 'base64');
var encryptBinary = cipher.final('base64')
console.log('encrypted :', encryptBinary);

...但解密不是。

decipher.update(encryptBinary, 'base64', 'binary');
var decryptBinary = decipher.final('binary');
console.log('decrypted :', decryptBinary);

node-efs相同的解密问题。

var efs = require('efs').init('aes-128-cbc', 'password');

// encrypt and write file
efs.writeFileSync('/tmp/example', 'hello world');

// decrypt and read file
efs.readFileSync('/tmp/example');

file-encryptor相同的问题。

这有效(仅适用于字符串):

var crypto = require('crypto')
 , key = 'salt_from_the_user_document'
 , plaintext = 'password'
 , 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);
4

1 回答 1

0

调用update也返回加密数据,调用final只返回其余部分。因此,您需要将每个调用update的输出连接到最后添加final. 加密和解密(顺便说一下,还有散列)都是如此。

因此,它需要是这样的:

var encrypted = cipher.update(plaintext, 'binary', 'base64');
encrypted += cipher.final('base64');

然后它会工作。

请注意,updatefinal功能已被弃用,加密模块现在也是基于流的,您可能希望切换到更现代的方法。

于 2013-09-24T22:21:34.483 回答