我想将以下 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