Asper Header  1.0.14
The header injector extension
Loading...
Searching...
No Matches
columnar.ts
Go to the documentation of this file.
1
12import { BaseCipher } from "../base/baseCipher";
13
21export class ColumnarCipher extends BaseCipher {
25 readonly CipherName = "Columnar";
26
32 super();
33 }
34
42 private getOrder(key: string = ""): number[] {
43 const cleanKey = this.sanitize(key);
44 const indexedChars: { ch: string; i: number }[] = [];
45
46 for (let i = 0; i < cleanKey.length; i++) {
47 indexedChars.push({ ch: cleanKey[i], i });
48 }
49
50 indexedChars.sort((a, b) => a.ch.localeCompare(b.ch));
51
52 const order: number[] = [];
53 for (const item of indexedChars) {
54 order.push(item.i);
55 }
56
57 return order;
58 }
59
68 encode(plainText: string = "", key: string = ""): string {
69 const order = this.getOrder(key);
70 const cols = order.length;
71 const rows = Math.ceil(plainText.length / cols);
72 const grid: string[] = Array(cols).fill("");
73
74 for (let i = 0; i < plainText.length; i++) {
75 const colIndex = i % cols;
76 grid[colIndex] += plainText[i];
77 }
78
79 let output = "";
80 for (const colIndex of order) {
81 output += grid[colIndex];
82 }
83
84 return output;
85 }
86
95 decode(cipherText: string = "", key: string = ""): string {
96 const order = this.getOrder(key);
97 const cols = order.length;
98 const rows = Math.ceil(cipherText.length / cols);
99
100 // Calculate lengths of each column
101 const colLengths: number[] = Array(cols).fill(Math.floor(cipherText.length / cols));
102 let remainder = cipherText.length - colLengths.reduce((sum, len) => sum + len, 0);
103 for (let i = 0; i < remainder; i++) {
104 colLengths[i]++;
105 }
106
107 // Fill each column from cipherText
108 const columns: string[] = Array(cols).fill("");
109 let pos = 0;
110 for (let i = 0; i < cols; i++) {
111 const colIndex = order[i];
112 columns[colIndex] = cipherText.substr(pos, colLengths[i]);
113 pos += colLengths[i];
114 }
115
116 // Read row by row to reconstruct plaintext
117 let output = "";
118 for (let r = 0; r < rows; r++) {
119 for (let c = 0; c < cols; c++) {
120 output += columns[c][r] ?? "";
121 }
122 }
123
124 return output;
125 }
126}
Abstract base class providing common functionality for cipher implementations.
Definition baseCipher.ts:18
Implementation of the Columnar Transposition cipher.
Definition columnar.ts:21
constructor()
Constructor for Columnar Transposition cipher.
Definition columnar.ts:31
readonly CipherName
Identifier name for this cipher.
Definition columnar.ts:25
export const Record< string,(...args:any[])=> string