Last active
January 15, 2021 11:38
-
-
Save zetxx/022ca644bed54938767ea7de553a6ca9 to your computer and use it in GitHub Desktop.
This file contains 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
const key = (k, strLen) => Array | |
.from({ | |
length: Math.ceil(strLen / k.length) | |
}) | |
.fill(k) | |
.join('') | |
.split('') | |
.map((v) => v.charCodeAt(0)); | |
const xorStr = (s, {key: {ascii: asciiKey}}) => { | |
const str = s.split(''); | |
const k = key(asciiKey, str.length); | |
const x = str.map( | |
(v, idx) => [ | |
'0', | |
(v.charCodeAt(0) ^ k[idx]) | |
.toString('16') | |
] | |
.join('') | |
.slice(-2) | |
); | |
return x.join(''); | |
}; | |
const unXorStr = (s, {key: {ascii: asciiKey}}) => { | |
const str = s | |
.split('') | |
.reduce((a, c, idx) => { | |
if (idx % 2 === 0) { | |
return a.concat(c); | |
} else { | |
return a | |
.slice(0, -1) | |
.concat( | |
parseInt(a.slice(-1).concat(c).join(''), 16) | |
) | |
} | |
}, []); | |
const k = key(asciiKey, str.length); | |
return str | |
.map((v, idx) => String.fromCharCode(v ^ k[idx])) | |
.join(''); | |
}; | |
const kk = 'abcd' | |
const s = 'The quick brown fox'; | |
console.log({kk, s}); | |
const a = xorStr( | |
s, | |
{key: {ascii: kk}} | |
); | |
console.log(a); | |
const b = unXorStr(a, {key: {ascii: kk}}); | |
console.log(b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment