Asper Header  1.0.14
The header injector extension
Loading...
Searching...
No Matches
enigma.ts
Go to the documentation of this file.
1
13import { BaseCipher } from "../base/baseCipher";
14
22export class EnigmaCipher extends BaseCipher {
26 readonly CipherName = "Enigma";
27
32 rotors: string[];
33
38 reflector: string;
39
44 positions: number[];
45
54 rotors: string[] = [
55 "EKMFLGDQVZNTOWYHXUSPAIBRCJ",
56 "AJDKSIRUXBLHWTMCQGZNPYFVOE",
57 "BDFHJLCPRTXVZNYEIWGAKMUSQO"
58 ],
59 reflector: string = "YRUHQSLDPXNGOKMIEBFZCWVJAT"
60 ) {
61 super();
62 this.rotors = rotors;
63 this.reflector = reflector;
64 this.positions = Array(rotors.length).fill(0);
65 }
66
73 private step(): void {
74 this.positions[0] = this.mod(this.positions[0] + 1, 26);
75
76 for (let i = 0; i < this.positions.length - 1; i++) {
77 if (this.positions[i] === 0) {
78 this.positions[i + 1] = this.mod(this.positions[i + 1] + 1, 26);
79 }
80 }
81 }
82
91 encode(plainText: string = ""): string {
92 let output = "";
93
94 for (const ch of plainText.toUpperCase()) {
95 if (!/[A-Z]/.test(ch)) {
96 output += ch;
97 continue;
98 }
99
100 this.step();
101
102 // Initial index in alphabet
103 let idx = EnigmaCipher.ALPHABET.indexOf(ch);
104
105 // Forward through rotors
106 for (let r = 0; r < this.rotors.length; r++) {
107 const rotor = this.rotors[r];
108 const shifted = this.mod(idx + this.positions[r], 26);
109 const mappedChar = rotor[shifted];
110 idx = this.mod(EnigmaCipher.ALPHABET.indexOf(mappedChar) - this.positions[r], 26);
111 }
112
113 // Reflector
114 idx = EnigmaCipher.ALPHABET.indexOf(this.reflector[idx]);
115
116 // Back through rotors (reverse)
117 for (let r = this.rotors.length - 1; r >= 0; r--) {
118 const rotor = this.rotors[r];
119 const shifted = this.mod(idx + this.positions[r], 26);
120 const pos = rotor.indexOf(EnigmaCipher.ALPHABET[shifted]);
121 idx = this.mod(pos - this.positions[r], 26);
122 }
123
124 output += EnigmaCipher.ALPHABET[idx];
125 }
126
127 return output;
128 }
129
138 decode(cipherText: string = ""): string {
139 // Enigma is symmetrical
140 return this.encode(cipherText);
141 }
142}
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
Simplified implementation of the Enigma machine polyalphabetic cipher.
Definition enigma.ts:22
constructor(rotors:string[]=["EKMFLGDQVZNTOWYHXUSPAIBRCJ", "AJDKSIRUXBLHWTMCQGZNPYFVOE", "BDFHJLCPRTXVZNYEIWGAKMUSQO"], reflector:string="YRUHQSLDPXNGOKMIEBFZCWVJAT")
Constructor for Enigma cipher.
Definition enigma.ts:53
readonly CipherName
Identifier name for this cipher.
Definition enigma.ts:26
export const Record< string,(...args:any[])=> string