Search code examples
javascriptpythonnode.jsencryptioncryptojs

Python bytestring => Javascript?


I'm attempting to port some Python code to Javascript. Here is the Python code:

# Python 
import codecs
from Crypto.Cipher import AES
key = b"\xc3\x99\xff\xff\xc3\x99\xff\xff\xc3\x99\xff\xff\xc3\x99\xff\xff"
...
aes = AES.new(key, AES.MODE_ECB)
token = aes.encrypt("HELLO\x00\x00".encode("utf-8"))
token_hex = codecs.encode(token, "hex").decode("utf-8")

I'm not exactly sure how to port my Python key variable. Should it be UInt16Array...or a string?

This is my Javascript so far:

// Javascript
const crypto = require('crypto');
const key = '???' // <-- This is one place I am stuck. String? Byte array?
....
const cipher = crypto.createCipher('aes-128-ecb', key);
let tokenHex = cipher.update('HELLO\x00\x00', 'utf8', 'hex');
tokenHex = tokenHex.toString('utf8')

I appreciate any insight you can provide as to how I can get a matching tokenHex in Javascript.

Thank you!


Solution

  • What you are after is Buffer, which represents a collection of bytes.

    You probably want to instantiate the key variable similar to this:

    let key = Buffer.from("c399ff...", "hex");