我正在尝试在NodeJS中实现以下Python代码:
from Cryptodome.Cipher import AES
from functools import reduce
from Cryptodome.Hash import SHA256
from Cryptodome import Random
from binascii import b2a_hex
def encrypt(text, *params):
key = createKey(*params)
iv = Random.new().read(16)
to_encrypt = _pad(text.encode('utf-8'))
aes = AES.new(key, AES.MODE_CBC,iv)
result = aes.encrypt(to_encrypt)
padded = result + iv
hexed = b2a_hex(padded)
return hexed.decode('utf-8')
def decrypt(encrypted, *params):
try:
hex_data = bytes.fromhex(encrypted)
except Exception as e:
print('fromhex failed: {}'.format(e))
return encrypted
iv = hex_data[-16:]
to_decrypt = hex_data[:-16]
aes = AES.new(createKey(*params), AES.MODE_CBC, iv)
result = aes.decrypt(to_decrypt)
encrypt('Fname Snamne', '5b18f13dacef4a051745c895', '5b265df1acef4a4a1e9562fc', 'integrityCare')
return _unpad(result).decode('utf-8')
def _unpad(s):
return s[:-ord(s[len(s)-1:])]
def createKey(*params):
acc = reduce((lambda x, y: x + y), params)
return SHA256.new((acc).encode('utf-8')).digest()
def _pad(s):
pad = 16 - len(s) % 16
newlen = len(s) + pad
return s.ljust(newlen, bytes([pad]))
换句话说,我需要两个功能的NodeJS实现:encrypt
和decrypt
。
这里有两个测试来检查实现是否正确(Python代码通过了):
测试1:
decrypt('5b34bf12052364771da80b30bce3c986c610d26d3d9d1c8c41f755b45064fe48', '5b18f13dacef4a051745c895', '5b265df1acef4a4a1e9562fc', 'integrityCare')
Result: 'Fname Snamne'
测试2:
decrypt(encrypt('Fname Snamne', '5b18f13dacef4a051745c895', '5b265df1acef4a4a1e9562fc', 'integrityCare'), '5b18f13dacef4a051745c895', '5b265df1acef4a4a1e9562fc', 'integrityCare')
Result: 'Fname Snamne'
有一个非常流行的用于AES aes-js的NodeJS程序包,我只是无法在NodeJS上正确实现上述功能。