Я пытаюсь разработать очень простой код для шифрования и дешифрования простого текста. Проблема заключается в том, что при запуске кода .final () моего createDecipherIV вызывает эту ошибку в заголовке.
Я пытался играть с разной кодировкой (Binary vs Hex, base 64 и т. Д.)
узел: '10 .15.3 '
openssl: '1.1.0j'
Это электронный проект, хотя я не знаю, какое влияние это может оказать
const crypto = require('crypto');
let sessionKey = crypto.randomBytes(256/8).toString('hex');
class encryption {
constructor() {
this.encryptionOptions = {
algorithm: 'aes-256-cbc',
iv: crypto.randomBytes(16),
key: String,
}
}
encryptMem(memItem){
this.encryptionOptions['key'] = Buffer.from(sessionKey,'hex');
var cipher = crypto.createCipher(this.encryptionOptions['algorithm'], this.encryptionOptions['key'], this.encryptionOptions['iv']);
var cipherText = cipher.update(memItem,'utf8','hex');
cipherText += cipher.final('hex');
return this.encryptionOptions['iv'].toString('hex') + cipherText;
}
decryptMem(memObject){
this.encryptionOptions['key'] = Buffer.from(sessionKey,'hex');
var _iv = Buffer.from(memObject.slice(0,32),'hex')
var _data = memObject.slice(32)
var _decode = crypto.createDecipheriv(this.encryptionOptions['algorithm'], this.encryptionOptions['key'], _iv);
var _decoded = _decode.update(_data,'hex','utf8');
_decoded += _decode.final('utf8')
return _decoded;
}
}
Пример кода
e = new encryption
encryption {encryptionOptions: {…}}
val = e.encryptMem("test")
"adcd1f5876ca02a4420b61df5dfdaa9be3080108020df42dfc630951ffabe0ac"
e.decryptMem(val)
\lib\encrypt.js:25
internal/crypto/cipher.js:172 Uncaught Error: error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT
at Decipheriv.final (internal/crypto/cipher.js:172)
at encryption.decryptMem (\lib\encrypt.js:26)
at <anonymous>:1:3
final @ internal/crypto/cipher.js:172
decryptMem @ \lib\encrypt.js:26
(anonymous) @ VM433:1
Куда как надо просто вернуть "тест
РЕДАКТИРОВАТЬ Как указано в ответе, createCipher необходимо изменить на createCipheriv
Ниже приведен некоторый сокращенный код, который также должен правильно создавать новый iv при каждом вызове шифрования, а не просто при вызове класса
const crypto = require('crypto');
let sessionKey = crypto.randomBytes(256/8).toString('hex');
class encryption {
constructor(key = null){
this.algorithm = 'aes-256-cbc';
this.key = key || Buffer.from(sessionKey,'hex');
}
encrypt(plainText){
var iv = crypto.randomBytes(16);
var cipher = crypto.createCipheriv(this.algorithm,this.key,iv);
var cipherText = cipher.update(plainText,'utf8','hex') + cipher.final('hex');
return iv.toString('hex') + cipherText;
}
decrypt(cipherText){
var iv = Buffer.from(cipherText.slice(0,32),'hex');
var data = cipherText.slice(32);
var decode = crypto.createDecipheriv(this.algorithm,this.key,iv);
var decoded = decode.update(data,'hex','utf8') + decode.final('utf8');
return decoded;
}
}