-1

我想将以下 python 代码重写为 node.js。我要用 AES 算法重写小型加密/解密库。我想解密由 python 加密函数加密的值。

然后我在node.js中写了代码,但它仍然有问题.. :(

如果可能的话,请看看这个。谢谢你。

Python

import hashlib
imoprt base64
from Crypto.Cipher import AES
from Crypto import Random

# secret: the raw key used by the algorithm
# data: the data to encypt

m = hashlib.md5()
m.update(secret)
key = m.hexdigest()

iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_ECB, iv)
encrypted = base64.b64encode(iv + cipher.encrypt(pad((data))))

bdata = base64.b64decode(encrypted)
iv = bdata[0:AES.block_size]
edata = bdata[AES.block_size:]
cipher = AES.new(key, AES.MODE_ECB, iv)
decrypted = cipher.decrypt(edata).strip("\0")

# data == decrypted should be true

def pad(self, s):
  return s + (16 - len(s) % 16) * "\0"

节点.js

var crypto = require('crypto');

var AES_BLOCK_SIZE = 16;
var algorithm = 'aes-256-ecb';
var inputEncoding = 'utf8';
var outputEncoding = 'base64';

var m = crypto.createHash('md5');
m.update(secret);
var key = m.digest('hex');

var iv = crypto.randomBytes(AES_BLOCK_SIZE);
var cipher = crypto.createCipheriv(algorithm, key, iv);
var ciphered = cipher.update(data, inputEncoding, 'binary');
ciphered += cipher.final('binary');
var encrypted = Buffer.concat([iv, new Buffer(ciphered, 'binary')]);
encrypted = encrypted.toString(outputEncoding);

var buffer = new Buffer(encrypted, outputEncoding);
var iv = buffer.slice(0, AES_BLOCK_SIZE);
var edata = buffer.slice(AES_BLOCK_SIZE, buffer.length);

console.log(key.length); # 16
console.log(iv.length); # 16

var decipher = crypto.createDecipheriv(algorithm, key, iv);
decipher.setAutoPadding(false);
var deciphered = decipher.update(edata, 'binary', inputEncoding);

# it says "node-crypto : Invalid IV length"

我还尝试重写 node.js 的解密部分。仍然不起作用并出现错误...

var decipher = crypto.createDecipheriv(algorithm, key, iv);
var buffers = [];
buffers.push(decipher.update(edata));
buffers.push(decipher.final(inputEncoding));
var plaintext = Buffer.concat(buffers).toString(inputEncoding);

TypeError: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
4

1 回答 1

0

最后,我自己解决了这个问题.. :-p 所以基本上,不需要 ecb 模式 iv。然后我将空白文本放入 iv 参数中。

var m = crypto.createHash('md5');
m.update(secret);
var key = m.digest('hex');

var iv = crypto.randomBytes(AES_BLOCK_SIZE);
var cipher = crypto.createCipheriv(algorithm, keyBuf, '');
cipher.setAutoPadding(true);
var ciphered = cipher.update(expect, inputEncoding, 'binary');
ciphered += cipher.final('binary');
var encrypted = Buffer.concat([iv, new Buffer(ciphered, 'binary')]);
var edata = encrypted.toString(outputEncoding);

var decipher = crypto.createDecipheriv(algorithm, key, '');
decipher.setAutoPadding(false);
buffers.push(decipher.update(edata, 'binary'));
buffers.push(decipher.final('binary'));
var decrypted = buffers.join('');
var plaintext = decrypted.toString('utf8');
于 2014-06-05T17:26:50.407 回答