Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Encrypt {
- alphabet: string;
- links: {};
- table: string[][];
- constructor(_alpthabet: string) {
- this.alphabet = _alpthabet,
- this.links = this.generateLinks(),
- this.table = this.generateTable();
- }
- generateLinks(): Object {
- let tempLinks: Object = {};
- for (let i = 0; i < this.alphabet.length; i++) {
- tempLinks[this.alphabet[i]] = i;
- }
- return tempLinks;
- }
- generateTable(): string[][] {
- let tempTable: string[][] = [];
- for (let i: number = 0; i < this.alphabet.length; i++) {
- tempTable[i] = [];
- for (let j: number = 0; j < this.alphabet.length; j++) {
- let shiftedPos: number = (j + i) % this.alphabet.length;
- tempTable[i][j] = this.alphabet.charAt(shiftedPos);
- }
- }
- return tempTable;
- }
- encrypt(_string: string, _key: string): string {
- if (_string.length != _key.length) return "Lenth not a same";
- let encryptedString: string = "";
- for (let i: number = 0; i < _string.length; i++) {
- let stringIndex: string = this.links[_string[i]];
- let keyIndex: string = this.links[_key[i]];
- encryptedString += this.table[keyIndex][stringIndex];
- }
- return encryptedString;
- }
- decrypt(_string: string, _key: string): string {
- let decryptedString: string = "";
- if (_string.length != _key.length) return "Lenth not a same";
- for (let i: number = 0; i < _string.length; i++) {
- let keyIndex: number = this.links[_key[i]];
- let secondIndex: number = this.table[keyIndex].findIndex(key => _string[i] === key); //indexOf(_string[i]);
- decryptedString += Object.keys(this.links).find(key => this.links[key] === secondIndex);
- }
- return decryptedString;
- }
- }
- const enAlphabet: string = "BCDEFGHIJKLMNOPQRSTUVWXYZA";
- console.log(enAlphabet.length);
- const en = new Encrypt(enAlphabet);
- const text: string = "HELLOWORLD";
- console.log(text.length);
- const key: string = "MAXSMOKEMA";
- console.log(key.length);
- const encString: string = en.encrypt(text, key);
- console.log(encString);
- const decryptedString: string = en.decrypt(encString, text);
- console.log(decryptedString);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement