在 Nodejs 中使用密码对字符串进行编码的简单方法?

Simple way to encode a string with a password in Nodejs?

我正在寻找下面提到的 NodeJS 编码实现 (javascript)。

import base64

def encode(key, string):
    encoded_chars = []
    for i in xrange(len(string)):
        key_c = key[i % len(key)]
        encoded_c = chr(ord(string[i]) + ord(key_c) % 256)
        encoded_chars.append(encoded_c)
    encoded_string = "".join(encoded_chars)
    return base64.urlsafe_b64encode(encoded_string)

我从 Simple way to encode a string according to a password?

那里得到了这个

这里是解决方案,使用秘密字符串进行编码和解码。

 const encode = (secret, plaintext) => {
  const enc = [];
  for (let i = 0; i < plaintext.length; i += 1) {
    const keyC = secret[i % secret.length];
    const encC = `${String.fromCharCode((plaintext[i].charCodeAt(0) + keyC.charCodeAt(0)) % 256)}`;
    enc.push(encC);
  }
  const str = enc.join('');
  return Buffer.from(str, 'binary').toString('base64');
};


const decode = (secret, ciphertext) => {
  const dec = [];
  const enc = Buffer.from(ciphertext, 'base64').toString('binary');
  for (let i = 0; i < enc.length; i += 1) {
    const keyC = secret[i % secret.length];
    const decC = `${String.fromCharCode((256 + enc[i].charCodeAt(0) - keyC.charCodeAt(0)) % 256)}`;
    dec.push(decC);
  }
  return dec.join('');
};



  console.log('result encode:', encode('abcd56&r#iu)=', '122411353520'));
  console.log('result decode:', decode('abcd56&r#iu)=', 'kpSVmGZnWadWnqdZ'));