尝试从Python到Nodejs实现这两个功能:
def encrypt(base64_data):
key = os.urandom(32)
encoded_key = base64.b16encode(key)
iv = ""
iv_vector = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in iv_vector:
iv += chr(i)
ctr = Counter.new(128, initial_value=long(iv.encode("hex"), 16))
cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
encrypted = cipher.encrypt(base64_data)
return encrypted, encoded_key
def decrypt(encrypted_data, orig_key):
key = base64.b16decode(orig_key)
iv = ""
iv_vector = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
for i in iv_vector:
iv += chr(i)
ctr = Counter.new(128, initial_value=long(iv.encode("hex"), 16))
cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
decrypted = cipher.decrypt(encrypted_data)
return decrypted
此解密有效(当我在Python中加密时,我设法在node中解密),但相反的方法失败了。 知道nodejs加密函数中缺少什么吗?
// Not working
export const encrypt = (base64Data: string): {encryptedData: string, decryptionKey: string} => {
const key = randomBytes(32);
const encodedKey = key.toString('hex');
var iv = Buffer.from('00000000000000000000000000000000', 'hex');
var encipher = createCipheriv('aes-256-ctr', key, iv);
const x = Buffer.concat([
encipher.update(base64Data),
encipher.final()
]);
return {encryptedData: x.toString('base64'), decryptionKey: encodedKey};
}
// This works
export const decrypt = (base64Data: string, encodedKey: string) => {
const key = Buffer.from( encodedKey, 'hex')
var iv = Buffer.from('00000000000000000000000000000000', 'hex');
var decipher = createDecipheriv('aes-256-ctr', key, iv);
return Buffer.concat([
decipher.update(Buffer.from(base64Data)),
decipher.final()
]);
}
答案 0 :(得分:1)
如果考虑以下几点,则这两种代码的加密和解密将在我的计算机上以所有可能的组合运行。
必须在2个地方更改节点代码,以便加密和解密保持一致:在return
方法的encrypt
声明中,'00'+encodedKey
必须为用''+encodedKey
替换,否则解密密钥太长一个字节。在return
方法的decrypt
语句中,Buffer.from(base64Data)
必须用Buffer.from(base64Data, 'base64')
替换,因为密文是Base64编码的。
Python中的密文(由encrypt
返回,传递给decrypt
)是一个字节数组。 Node中的密文(从encrypt
返回,传递给decrypt
)是Base64编码的字符串。因此,此处需要进行转换,例如在Python代码中。
Node以带有小写字母的十六进制字符串形式返回键,Python需要大写字母。因此,此处需要适当的转换,例如在Python代码中。