Hi, I'm Akaash.

My apologies in advance.

Running a Python Script From Node.js

While working on something today, I needed to decrypt an RC4 encrypted string on Node. I was receiving the encrypted string from another server, so the encryption wasn’t really under my control. Given that there are a bunch of pre-written NPM modules out there that do RC4 encryption/decryption this wasn’t supposed to be a particularly difficult task. However, this seemingly trivial job turned out to be quite the timesuck.

None of the crypto modules I tried were able to correctly decrypt the encrypted string, which I’m guessing meant that the other server was probably doing something funny during the encryption process. The organisation whose server I was communicating with had provided a Python code snippet that had an implementation of the RC4 decryption algorithm, and this particular implementation was working for the encrypted strings being returned.

As a quick-fix, I decided to just call this Python script from my Node server, pass it the encrypted string and receive the decrypted string as output. To do this in Node, you need to spawn a child Python process.

1
2
3
4
5
6
7
8
9
10
11
12
13
var terminal = require('child_process').spawn('python', ['rc4.py', secretKey, encryptedString]);;

terminal.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
});

terminal.on('exit', function (code) {
    console.log('child process exited with code ' + code);
});

terminal.stderr.on('data', function (data) {
  console.log('stderr: ' + data);
});

The arguments to the spawn function are the child process command name (in this case ‘python’ since I was trying to run a python program), followed by the array of arguments needed by the child process (in this case the name of the Python script, the encryption key and the encrypted string, respectively).

This worked quite well, but seemed somewhat hack-y in nature. So I might have to revisit this later and see how to do it directly within the Node process itself.