AES-256-CBC坏解密

时间:2016-05-12 16:19:30

标签: node.js cryptography

第1步:使用pbkdf2

创建密钥
var key = crypto.pbkdf2Sync('prancypoodle', 'sherylcrowe', 10000, 32, 'sha512');

使用密码prancy poodle创建一个密钥,将其加密sherylcrowe,迭代10,000次,输出一个32字节长的密钥(AES-256-CBC需要该长度)。

第2步:加密某些内容

var cipher = crypto.createCipheriv('aes-256-cbc', key, 'dogsarefun'.toString("binary"));

var crypted = cipher.update('wherearemysocks?');
crypted = Buffer.concat([crypted, cipher.final()]);

第3步:解密&失败

var decipher = crypto.createDecipheriv('aes-256-cbc', key, 'dogsarefun'.toString('binary'));

var decrypted = decipher.update(crypted);
decrypted = Buffer.concat([decrypted, decipher.final()]);
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
    at Error (native)
    at Decipher.Cipher.final (crypto.js:150:26)
    at repl:1:48
    at REPLServer.defaultEval (repl.js:272:27)
    at bound (domain.js:280:14)
    at REPLServer.runBound [as eval] (domain.js:293:12)
    at REPLServer.<anonymous> (repl.js:441:10)
    at emitOne (events.js:101:20)
    at REPLServer.emit (events.js:188:7)
    at REPLServer.Interface._onLine (readline.js:219:10)

我做错了什么?这似乎是对的,但是错了。

2 个答案:

答案 0 :(得分:5)

您需要为CBC模式提供IV,它需要是块大小(AES为16字节)。 &#39; dogsarefun&#39;只有10个字节,所以剩余的字节是未指定的,可能(可能是)垃圾。

由于PKCS填充是默认设置并且使用了CBC模式,因此错误的IV将导致解密时填充错误,可能是错误:例程:EVP_DecryptFinal_ex:bad decrypt

P.S。当心:这是猫所用的互联网。

答案 1 :(得分:0)

您需要使用createDecipheriv函数进行解密,并且您的IV必须为16个字符。

示例:

var crypto = require('crypto');
var buffer = require('buffer');

var key = crypto.pbkdf2Sync('prancypoodle', 'sherylcrowe', 10000, 32, 'sha512');

// Initialization vector must be 16 characters.
var cipher = crypto.createCipheriv('aes-256-cbc', key,
  new Buffer('1234567812345678', 'binary'));

var crypted = cipher.update('wherearemysocks?');
console.log('Encrypted: %s', crypted);
crypted = Buffer.concat([crypted, cipher.final()]);
// Again, IV must be 16 characters.
var decipher = crypto.createDecipheriv('aes-256-cbc', key,
  new Buffer('1234567812345678', 'binary'));

var decrypted = decipher.update(crypted);
console.log('Decrypted: %s', decrypted);

输出:

Encrypted: #�j���(����
Decrypted: wherearemysocks?