Skip to content

Instantly share code, notes, and snippets.

@afranioce
Created June 5, 2019 20:30
Show Gist options
  • Save afranioce/051efe3520e4d6f92a9959d5b96fe7c2 to your computer and use it in GitHub Desktop.
Save afranioce/051efe3520e4d6f92a9959d5b96fe7c2 to your computer and use it in GitHub Desktop.
A simple crypto to typescript
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