Created
December 21, 2021 22:31
-
-
Save danoseun/48d745a284cf1b123d37276312ba5eb4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//encrypt | |
const encrypt = (salt, text) => { | |
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 | |
.split("") | |
.map(textToChars) | |
.map(applySaltToChar) | |
.map(byteHex) | |
.join(""); | |
}; | |
//decrypt | |
const decrypt = (salt, encoded) => { | |
const textToChars = (text) => text.split("").map((c) => c.charCodeAt(0)); | |
const applySaltToChar = (code) => textToChars(salt).reduce((a, b) => a ^ b, code); | |
return encoded | |
.match(/.{1,2}/g) | |
.map((hex) => parseInt(hex, 16)) | |
.map(applySaltToChar) | |
.map((charCode) => String.fromCharCode(charCode)) | |
.join(""); | |
}; | |
// encrypting | |
console.log(encrypt('salt', 'quick brown fox')); // -> 7b7f6369612a6878657d642a6c6572 | |
// decrypting | |
console.log(decrypt('salt', '7b7f6369612a6878657d642a6c6572')); // -> quick brown fox |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment