Asper Header  1.0.14
The header injector extension
Loading...
Searching...
No Matches
affine.ts
Go to the documentation of this file.
1
13import { BaseCipher } from "../base/baseCipher";
14
22export class AffineCipher extends BaseCipher {
26 private readonly a: number;
27
31 private readonly b: number;
32
36 readonly CipherName = "Affine";
37
46 constructor(a: number = 5, b: number = 8) {
47 super();
48 this.a = a;
49 this.b = b;
50 if (this.gcd(this.a, 26) !== 1) {
51 throw new Error("a must be coprime with 26");
52 }
53 }
54
62 private gcd(a: number, b: number): number {
63 return b === 0 ? a : this.gcd(b, a % b);
64 }
65
73 encode(plainText: string = ""): string {
74 return plainText
75 .toUpperCase()
76 .split("")
77 .map(ch => {
78 const i = BaseCipher.ALPHABET.indexOf(ch);
79 if (i === -1) {
80 return ch;
81 }// preserve non-letters
82 return BaseCipher.ALPHABET[this.mod(this.a * i + this.b, 26)];
83 })
84 .join("");
85 }
86
95 decode(cipherText: string = ""): string {
96 const invA = this.modInverse(this.a, 26);
97 return cipherText
98 .toUpperCase()
99 .split("")
100 .map(ch => {
101 const i = BaseCipher.ALPHABET.indexOf(ch);
102 if (i === -1) {
103 return ch;
104 }
105 return BaseCipher.ALPHABET[this.mod(invA * (i - this.b), 26)];
106 })
107 .join("");
108 }
109}
Implementation of the Affine substitution cipher.
Definition affine.ts:22
constructor(a:number=5, b:number=8)
Constructor for Affine cipher.
Definition affine.ts:46
readonly CipherName
Identifier name for this cipher.
Definition affine.ts:36
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
export const Record< string,(...args:any[])=> string