0

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.

1
  • Take a look at crypto-js Commented Apr 5, 2020 at 9:06

1 Answer 1

2

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'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.