-3

I'm looking for mentioned below encoding implementation in 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)

I got this from Simple way to encode a string according to a password?

Sayse
  • 42,633
  • 14
  • 77
  • 146
Sanjeet kumar
  • 3,333
  • 3
  • 17
  • 26
  • Numerous npm packages around for hashing passwords. Beyond that, SO isn't a free code conversion service – charlietfl Jul 22 '19 at 14:14
  • I would leave crypto operations to a library. Also keep in mind encrypting in the browser is not considered safe. You can use the built-in Node `crypto` or an implementation of the encryption talked about in the answer to that post (fernet) – ktilcu Jul 22 '19 at 14:14
  • check out crypto and aes or some salt based algorithms. – Aritra Chakraborty Jul 22 '19 at 14:14
  • I need to create exact same hash, created by this pyton code. This hash already been using into the system. – Sanjeet kumar Jul 22 '19 at 14:18

1 Answers1

1

Here is the solution, encode and decode with secret string.

 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'));
Sanjeet kumar
  • 3,333
  • 3
  • 17
  • 26