|
| 1 | +import { Cipher } from "../Cipher.js" |
| 2 | + |
| 3 | +export class Alphabet extends Cipher { |
| 4 | + private keyword: string |
| 5 | + private static alphabet = "abcdefghijklmnopqrstuvwxyz" |
| 6 | + |
| 7 | + constructor(keyword: string) { |
| 8 | + super() |
| 9 | + this.keyword = keyword.toLowerCase() |
| 10 | + } |
| 11 | + |
| 12 | + /** |
| 13 | + * Encrypts a message using the Alphabet Cipher. |
| 14 | + * @param message - The plaintext message to encrypt. |
| 15 | + * @returns The encrypted ciphertext. |
| 16 | + */ |
| 17 | + encrypt(message: string): string { |
| 18 | + message = message.toLowerCase() |
| 19 | + const table = Alphabet.getVigenereTable() |
| 20 | + let result = "" |
| 21 | + |
| 22 | + for (let i = 0; i < message.length; i++) { |
| 23 | + const msgChar = message[i] |
| 24 | + const keyChar = this.keyword[i % this.keyword.length] |
| 25 | + |
| 26 | + if (!Alphabet.alphabet.includes(msgChar)) { |
| 27 | + result += msgChar // Preserve non-alphabet characters |
| 28 | + continue |
| 29 | + } |
| 30 | + |
| 31 | + const row = Alphabet.alphabet.indexOf(keyChar) |
| 32 | + const col = Alphabet.alphabet.indexOf(msgChar) |
| 33 | + result += table[row][col] |
| 34 | + } |
| 35 | + |
| 36 | + return result |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * Decrypts a message using the Alphabet Cipher. |
| 41 | + * @param ciphertext - The encrypted message to decrypt. |
| 42 | + * @returns The original plaintext message. |
| 43 | + */ |
| 44 | + decrypt(ciphertext: string): string { |
| 45 | + ciphertext = ciphertext.toLowerCase() |
| 46 | + const table = Alphabet.getVigenereTable() |
| 47 | + let result = "" |
| 48 | + |
| 49 | + for (let i = 0; i < ciphertext.length; i++) { |
| 50 | + const cipherChar = ciphertext[i] |
| 51 | + const keyChar = this.keyword[i % this.keyword.length] |
| 52 | + |
| 53 | + if (!Alphabet.alphabet.includes(cipherChar)) { |
| 54 | + result += cipherChar // Preserve non-alphabet characters |
| 55 | + continue |
| 56 | + } |
| 57 | + |
| 58 | + const row = Alphabet.alphabet.indexOf(keyChar) |
| 59 | + const col = table[row].indexOf(cipherChar) |
| 60 | + result += Alphabet.alphabet[col] |
| 61 | + } |
| 62 | + |
| 63 | + return result |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * Generates the Vigenère table for encoding and decoding. |
| 68 | + */ |
| 69 | + private static getVigenereTable(): string[][] { |
| 70 | + const table: string[][] = [] |
| 71 | + for (let i = 0; i < 26; i++) { |
| 72 | + table[i] = Alphabet.alphabet |
| 73 | + .slice(i) |
| 74 | + .split("") |
| 75 | + .concat(Alphabet.alphabet.slice(0, i).split("")) |
| 76 | + } |
| 77 | + return table |
| 78 | + } |
| 79 | +} |
0 commit comments