Asper Header  1.0.14
The header injector extension
Loading...
Searching...
No Matches
vigenere.ts
Go to the documentation of this file.
1
13import { BaseCipher } from "../base/baseCipher";
14
22export class VigenereCipher extends BaseCipher {
26 readonly CipherName = "Vigenere";
27
37 encode(plaintext: string, key: string): string {
38 const sanitizedKey = this.sanitize(key);
39 if (!sanitizedKey) {
40 throw new Error("Key required");
41 }
42
43 let keyIndex = 0;
44
45 return plaintext
46 .split("")
47 .map((char) => {
48 const plainIndex = VigenereCipher.ALPHABET.indexOf(char.toUpperCase());
49 if (plainIndex === -1) {
50 return char; // Non-alphabetic character
51 }
52
53 const shift = VigenereCipher.ALPHABET.indexOf(
54 sanitizedKey[keyIndex % sanitizedKey.length]
55 );
56
57 keyIndex++;
59 this.mod(plainIndex + shift, 26)
60 ];
61 })
62 .join("");
63 }
64
74 decode(ciphertext: string, key: string): string {
75 const sanitizedKey = this.sanitize(key);
76 if (!sanitizedKey) {
77 throw new Error("Key required");
78 }
79
80 let keyIndex = 0;
81
82 return ciphertext
83 .split("")
84 .map((char) => {
85 const cipherIndex = VigenereCipher.ALPHABET.indexOf(char.toUpperCase());
86 if (cipherIndex === -1) {
87 return char;
88 }
89
90 const shift = VigenereCipher.ALPHABET.indexOf(
91 sanitizedKey[keyIndex % sanitizedKey.length]
92 );
93
94 keyIndex++;
96 this.mod(cipherIndex - shift, 26)
97 ];
98 })
99 .join("");
100 }
101}
Abstract base class providing common functionality for cipher implementations.
Definition baseCipher.ts:18
static readonly ALPHABET
Standard English alphabet for cipher operations.
Definition baseCipher.ts:44
Implementation of the Vigenère polyalphabetic substitution cipher.
Definition vigenere.ts:22
readonly CipherName
Identifier name for this cipher.
Definition vigenere.ts:26
export const Record< string,(...args:any[])=> string