Skip to content
Advertisement

Translate encryption in python to node

Trying to implement these 2 functions from Python to Nodejs:

JavaScript

This decrypt works (when I encrypt in Python, I manage to decrypt in node), but the opposite way fails. Any idea what is missing in the nodejs encrypt function?

JavaScript

Advertisement

Answer

If the following points are taken into account, the encryption and decryption of both codes run in all possible combinations on my machine.

  • The Node-code must be changed in 2 places so that encryption and decryption are consistent: In the return-statement of the encrypt-method, '00'+encodedKey must be replaced by ''+encodedKey, otherwise the key for the decryption is one byte too long. In the return-statement of the decrypt-method, Buffer.from(base64Data) must be replaced by Buffer.from(base64Data, 'base64'), since the ciphertext is Base64-encoded.

  • The ciphertext in Python (returned by encrypt, passed to decrypt) is a byte-array. The ciphertext in Node (returned from encrypt, passed to decrypt) is a Base64-encoded string. Therefore a conversion is necessary here, e.g. in the Python-code.

  • Node returns the key as a hex-string with lowercase letters, Python needs uppercase letters. Therefore, an appropriate conversion is necessary here, e.g. in tbe Python-code.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement