简体   繁体   English

解码 Node.js 中的字符串,该字符串在 Python 中编码

[英]Decode a string in Node.js which was encoded in Python

I have a requirement where I am encoding a string in Python using a secret key.我有一个要求,我使用密钥对 Python 中的字符串进行编码。 Then I need to decode it in Node.js.然后我需要在 Node.js 中对其进行解码。 I am new to Node.js, so not sure how to do that.我是 Node.js 的新手,所以不知道该怎么做。

Here's Python side:这是Python侧:

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.在我的 Node.js 脚本中,我可以访问编码字符串和密钥。 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.请注意,我同时拥有 Python 和 Node.js 脚本,因此如果需要,我可以更改 python 脚本以使用不同的编码机制。

Running your Python code, I've got:运行您的 Python 代码,我得到:

KRUcAAZDNhsbAwo=

To decode this in JavaScript, without 3rd party libraries:要在 JavaScript 中对此进行解码,无需第三方库:

// 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM