Encryption and decryption in javascript

by Faisal Khan Janjua

HTML

<div id="result"></div>

CSS

span {
  color: red;
}

JavaScript

const cipher = salt => {
  const textToChars = text => text.split('').map(c => c.charCodeAt(0));
  const byteHex = n => ("0" + Number(n).toString(16)).substr(-2);
  const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);

  return text => text.split('')
    .map(textToChars)
    .map(applySaltToChar)
    .map(byteHex)
    .join('');
}

const decipher = salt => {
  const textToChars = text => text.split('').map(c => c.charCodeAt(0));
  const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);
  return encoded => encoded.match(/.{1,2}/g)
    .map(hex => parseInt(hex, 16))
    .map(applySaltToChar)
    .map(charCode => String.fromCharCode(charCode))
    .join('');
}

var bodyTxt = '';
var secretString = '786';

/* Now Call function like this:>>> */
var str = 'Faisal Khan Janjua';
bodyTxt += '<span>String to Encode: </span>'+str+'<br>';
console.log(str);

const myCipher = cipher(secretString);

//Then cipher any text:
var myStr = myCipher(str);
bodyTxt += '<span>Encoded String: </span>'+myStr+'<br>';
console.log(myStr);

//To decipher, you need to create a decipher and use it:
const myDecipher = decipher(secretString);
var oriStr = myDecipher(myStr);
bodyTxt += '<span>Orignal String: </span>'+oriStr+'<br>';
console.log(oriStr);

document.getElementById("result").innerHTML = bodyTxt;