使用NodeJS进行对称加密

时间:2016-12-08 16:10:44

标签: node.js encryption

我完全不知道为什么这不起作用,我得到Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt

var crypto = require('crypto');
var key = "ciw7p02f70000ysjon7gztjn7";
var pt = "72721827b4b4ee493ac09c635827c15ce014c3c3";

var encrypt = crypto.createCipher('aes256', key);
encrypt.update(pt, 'utf8', 'hex');
var encrypted = encrypt.final('hex')

var decrypt = crypto.createDecipher('aes256', key);
decrypt.update(encrypted, 'hex', 'utf8')
decrypt.final()

工作解决方案: https://runkit.com/fredyc/symmetric-encryption-with-nodejs

1 个答案:

答案 0 :(得分:11)

通过https://github.com/nodejs/node-v0.x-archive/issues/6386

解决方案
// https://github.com/nodejs/node-v0.x-archive/issues/6386#issuecomment-31817919
var assert = require('assert');
var crypto = require('crypto');

var algorithm = 'aes256';
var inputEncoding = 'utf8';
var outputEncoding = 'hex';

var key = 'ciw7p02f70000ysjon7gztjn7';
var text = '72721827b4b4ee493ac09c635827c15ce014c3c3';

console.log('Ciphering "%s" with key "%s" using %s', text, key, algorithm);

var cipher = crypto.createCipher(algorithm, key);
var ciphered = cipher.update(text, inputEncoding, outputEncoding);
ciphered += cipher.final(outputEncoding);

console.log('Result in %s is "%s"', outputEncoding, ciphered);

var decipher = crypto.createDecipher(algorithm, key);
var deciphered = decipher.update(ciphered, outputEncoding, inputEncoding);
deciphered += decipher.final(inputEncoding);

console.log(deciphered);
assert.equal(deciphered, text, 'Deciphered text does not match!');

使用错误在这里:

// yours (incorrect)
var encrypt = crypto.createCipher('aes256', key);
encrypt.update(pt, 'utf8', 'hex');
var encrypted = encrypt.final('hex')

// correct
var encrypt = crypto.createCipher('aes256', key);
var encrypted = encrypt.update(pt, 'utf8', 'hex');
encrypted += encrypt.final('hex')



// yours (incorrect)
var decrypt = crypto.createDecipher('aes256', key);
decrypt.update(encrypted, 'hex', 'utf8')
decrypt.final()

// correct
var decrypt = crypto.createDecipher('aes256', key);
var decrypted = decrypt.update(encrypted, 'hex', 'utf8')
decrypted += decrypt.final()