2016-12-08 86 views
2
的NodeJS

對稱加密,我完全糊塗了,爲什麼這不工作,我得到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

回答

4

解決方案通過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() 
+0

謝謝,沒想到在nodejs歸檔裏找到了答案:D – FredyC

+0

我討厭這麼說,但是......谷歌,先打了。 :) – Tomalak

+0

我想我也找到了它,但我完全不相信它可能是相關的,因爲它已經3歲:) – FredyC