Reputation: 847
I have a requirement where I am encoding a string in Python using a secret key. Then I need to decode it in Node.js. I am new to Node.js, so not sure how to do that.
Here's Python side:
from Crypto.Cipher import XOR
def encrypt(key, plaintext):
cipher = XOR.new(key)
return base64.b64encode(cipher.encrypt(plaintext))
encoded = encrypt('application secret', 'Hello World')
In my Node.js script, I have access to the encoded string and secret key. And I need to retrieve the original string.
const decoded = someLibrary.someMethod('application secret', encoded)
// decoded = 'Hello World'
Note that I own both Python and Node.js script, so if needed, I can change the python script to use a different encoding mechanism.
Upvotes: 0
Views: 552
Reputation: 4783
Running your Python code, I've got:
KRUcAAZDNhsbAwo=
To decode this in JavaScript, without 3rd party libraries:
// The atob function (to decode base64) is not available in node,
// so we need this polyfill.
const atob = base64 => Buffer.from(base64, 'base64').toString();
const key = 'application secret';
const encoded = 'KRUcAAZDNhsbAwo=';
const decoded = atob(encoded)
.split('')
.map((char, index) =>
String.fromCharCode(char.charCodeAt(0) ^ key.charCodeAt(index % key.length))
)
.join('');
// decoded = 'Hello World'
Upvotes: 2