Created
June 5, 2019 20:30
-
-
Save afranioce/051efe3520e4d6f92a9959d5b96fe7c2 to your computer and use it in GitHub Desktop.
A simple crypto to typescript
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
class Crypto { | |
constructor(private salt: string) { } | |
public encrypt(text: string) { | |
return this.textToChars(text) | |
.map(code => this.applySaltToChar(code)) | |
.map(char => this.byteHex(char)) | |
.join(''); | |
} | |
public decrypt(text: string) { | |
return text.match(/.{1,2}/g) | |
.map(hex => parseInt(hex, 16)) | |
.map(code => this.applySaltToChar(code)) | |
.map(charCode => String.fromCharCode(charCode)) | |
.join(''); | |
} | |
private textToChars(text: string): number[] { | |
return text.split('').map(c => c.charCodeAt(0)); | |
} | |
private byteHex(char: number): string { | |
return ("0" + char.toString(16)).substr(-2); | |
} | |
private applySaltToChar(code: number): number { | |
return this.textToChars(this.salt) | |
.reduce((a, b) => a ^ b, code); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment