在Node.js中用密码编码字符串的简单方法?

时间:2019-07-22 14:05:53

标签: javascript node.js encode

我正在寻找下面提到的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?那里得到了

1 个答案:

答案 0 :(得分:0)

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

 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'));
相关问题