Last active
January 17, 2017 01:39
-
-
Save korniychuk/bc3abfb51ccf4d619dae87f6c3f77596 to your computer and use it in GitHub Desktop.
Very simple encoder that supports UTF-16 characters
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
class Encoder { | |
public static encode(str: string, pass: string): string { | |
let res = ''; | |
let j = 0, jlen = pass.length; | |
str = pass + str; | |
for (let i = 0, ilen = str.length; i < ilen; i++) { | |
let charCode = str.charCodeAt(i), | |
passCode = pass.charCodeAt(j), | |
sumCode = charCode + passCode; | |
let code = sumCode > 0xffff ? sumCode - 0xffff : sumCode; | |
res += String.fromCharCode(code); | |
j = j + 1 >= jlen ? 0 : j + 1; | |
} | |
return res; | |
} | |
public static decode(str: string, pass: string): string|null { | |
let res = ''; | |
let j = 0, jlen = pass.length; | |
for (let i = 0, ilen = str.length; i < ilen; i++) { | |
let charCode = str.charCodeAt(i), | |
passCode = pass.charCodeAt(j), | |
diffCode = charCode - passCode; | |
let code = diffCode < 0 ? diffCode + 0xffff : diffCode; | |
res += String.fromCharCode(code); | |
j = j + 1 >= jlen ? 0 : j + 1; | |
} | |
return res.substr(0, jlen) === pass ? res.substr(jlen) : null; | |
} | |
} | |
let str = 'y%$E' + String.fromCodePoint(0x10000); | |
let pass = 'hello'; | |
let enc = Encoder.encode(str, pass); | |
let dec = Encoder.decode(enc, pass); | |
console.log(str, pass, enc, dec, str === dec); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment