Encryption with NodeJS doesn’t match encryption using Python (cryptography.fernet)

  cryptography, encryption, fernet, node.js, python

Cryptography noob here. I’m trying to write a script in NodeJS that encrypts a string and produces output that matches the output of my Python script that uses the cryptography.fernet library. My overall goal is to use the original key to encrypt messages in Node that will later be decrypted using Python.

Sample of my Python code:

from cryptography.fernet import Fernet

key = Fernet.generate_key() # For example: 6saGtiTFEXej729GUWSeAyQdIpRFdGhfY2XFUDpvsu8=
f = Fernet(key)
message = 'Hello World'
encoded = message.encode()
encrypted = f.encrypt(encoded)

Which produces the output: gAAAAABhJs_E-dDVp_UrLK6PWLpukDAM0OT5M6bfcqvVoCvg7r63NSi4OWOamLpABuYQG-5wsts_9h7cLbCsWmctArXcGqelXz_BXl_o2C7KM9o7_eq7VTc=

My Node script uses the built-in Crypto module and must also use the same 32-byte key that is being used in my Python program. I know that fernet uses is AES-128-CBC as its algorithm, so that’s what I’m using for my Node script.

My NodeJS code:

const crypto = require("crypto");

const key = '6saGtiTFEXej729GUWSeAyQdIpRFdGhfY2XFUDpvsu8=';
const algorithm = 'aes-128-cbc';
const message = 'Hello World';
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, key, iv);
const encrypted = cipher.update(message, 'utf8', 'hex') + cipher.final('hex');

Which is giving me: Error: Invalid key length

My first problem is that I’m unsure how to convert the key so that it’s the proper length. I also know from looking at fernet’s source code that the key is split into two parts: the first 16 bytes are the signing_key and the last 16 bytes are the encryption_key – I haven’t found much information on whether/how I need to deal with those two pieces of the original key in my Node implementation.

Since I’m new to this I’m a little confused on how to accomplish what I’m after. Any tips or advice is very much appreciated.

Source: Python Questions