【问题标题】:Simple way to encode a string with a password in Nodejs?在 Nodejs 中使用密码对字符串进行编码的简单方法?
【发布时间】:2019-07-22 14:05:53
【问题描述】:

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

【问题讨论】:

  • 众多用于散列密码的 npm 包。除此之外,SO 不是免费的代码转换服务
  • 我会将加密操作留给图书馆。另请记住,在浏览器中加密并不安全。您可以使用内置节点crypto 或该帖子的答案(fernet)中谈到的加密实现
  • 查看加密和 aes 或一些基于盐的算法。
  • 我需要创建完全相同的哈希,由这个 pyton 代码创建。此哈希已在系统中使用。

标签: javascript node.js encode


【解决方案1】:

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

 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'));

【讨论】:

    猜你喜欢
    • 2011-01-30
    • 2019-06-02
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多