如何将Python加密代码重写为Node.js?

-1 投票
1 回答
1148 浏览
提问于 2025-04-18 08:30

我想把下面的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"

Node.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

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');

撰写回答