2016-12-08 7 views
2

Я совершенно запутался, почему это не работает, я получаю Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decryptСимметричное шифрование с NodeJS

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

Ненавижу говорить об этом, но ... Google, сначала ударил. :) – Tomalak

+0

Думаю, я тоже это нашел, но я просто не верил, что это может быть уместно, так как ему 3 года :) – FredyC

Смежные вопросы