Olá, estou tentando fazer uma criptografia AES-256-cbc, e estou tendo dificuldade para criar uma Key e um IV... Tentei utilizar
crypto.randomBytes(32)
crypto.randomBytes(16)
O 32 para key, e o 16 para IV. Dessa forma o encrypt_token funciona sem problemas, mas o decrypt_token acontece um erro:
internal/crypto/cipher.js:174
const ret = this[kHandle].final();
^
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
at Decipheriv.final (internal/crypto/cipher.js:174:29)
at decrypt_token (/home/joao/test.js:95:16)
at Object.<anonymous> (/home/joao/test.js:101:29)
at Module._compile (internal/modules/cjs/loader.js:1118:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1138:10)
at Module.load (internal/modules/cjs/loader.js:982:32)
at Function.Module._load (internal/modules/cjs/loader.js:875:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
library: 'digital envelope routines',
function: 'EVP_DecryptFinal_ex',
reason: 'bad decrypt',
code: 'ERR_OSSL_EVP_BAD_DECRYPT'
}
Segue o código:
var crypto = require('crypto'),
key = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
iv = 'AAAAAAAAAAAAAAAA';
function encrypt_token(data) {
var encipher = crypto.createCipheriv('aes-256-cbc', key, iv),
buffer = Buffer.concat([
encipher.update(data),
encipher.final()
]);
return buffer.toString('base64');
}
function decrypt_token(data) {
var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv),
buffer = Buffer.concat([
decipher.update(Buffer.from(data, 'base64')),
decipher.final()
]);
return buffer.toString();
}
console.log('encriptado: ', encrypt_token('dmyz.org'));
console.log('decriptado: ', decrypt_token('FSfhJ/gk3iEJOPVLyFVc2Q=='));
Att.