Skip to content

Instantly share code, notes, and snippets.

@Vehmloewff
Last active December 19, 2020 16:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vehmloewff/a4be5e38c1ff0df62508627311a30110 to your computer and use it in GitHub Desktop.
Save Vehmloewff/a4be5e38c1ff0df62508627311a30110 to your computer and use it in GitHub Desktop.

Encryptor

Need to encrypt/decrypt something real quick? This is a simple, dependency-free way to get the job done.

const { encrypt, decrypt } = makeEncryptor('my-secret-key')

encrypt('hello, world!') // -> 1d1019191a5955021a07191154
decrypt('1d1019191a5955021a07191154') // -> hello, world!

Credits

The majority of the code was taken from this SO answer.

export function makeEncryptor(key: string) {
const textToChars = (text: string) => text.split('').map(c => c.charCodeAt(0))
const byteHex = (n: number) => ('0' + Number(n).toString(16)).substr(-2)
const applyKeyToChar = (code: number) => textToChars(key).reduce((a, b) => a ^ b, code)
function decrypt(encoded: string) {
return (encoded.match(/.{1,2}/g) || [])
.map(hex => parseInt(hex, 16))
.map(applyKeyToChar)
.map(charCode => String.fromCharCode(charCode))
.join('')
}
function encrypt(text: string) {
return textToChars(text).map(applyKeyToChar).map(byteHex).join('')
}
return { encrypt, decrypt }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment