简体   繁体   English

无法使用Node.js v0.10.18 @ Windows 7 64Bit解密

[英]Can't decrypt with node.js v0.10.18 @ Windows 7 64Bit

I can't get crypto to work. 我无法使用crypto

  • windows 7 64Bit Windows 7 64位
  • node.js v0.10.18 node.js v0.10.18

Encryption seems to work: 加密似乎有效:

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);

... but decryption not. ...但是解密不是。

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

Same decryption problem with node-efs . 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');

Same problem with file-encryptor . 文件加密器也有同样的问题。

This works (with strings only): 这有效(仅适用于字符串):

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);

The call to update also returns encrypted data, the call to final only returns the rest. update的调用还返回加密的数据,对final的调用仅返回其余的数据。 Hence you need to concatenate output of each call to update and finally add the output of final . 因此,您需要连接每个调用的输出以进行update并最终添加final的输出。 This is true for encryption as well as for decryption (and hashing, by the way). 对于加密以及解密(顺便说一下,以及哈希)都是如此。

Hence it needs to be something such as: 因此,它必须是这样的:

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

Then it'll work. 这样就可以了。

Please note that the update and final functions are deprecated and the crypto module is now also stream-based and you might want to switch to the more modern approach anyway. 请注意,不赞成使用updatefinal函数,并且crypto模块现在也基于流,并且您可能仍要切换到更现代的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM