Asper Header  1.0.14
The header injector extension
Loading...
Searching...
No Matches
railfence.ts
Go to the documentation of this file.
1
12import { BaseCipher } from "../base/baseCipher";
13
21export class RailFenceCipher extends BaseCipher {
25 readonly CipherName = "RailFence";
26
33 super();
34 }
35
44 encode(plainText: string, rails: number = 3): string {
45 if (rails <= 1) {
46 return plainText;
47 }
48
49 const rows: string[][] = Array.from({ length: rails }, () => []);
50 let currentRow = 0;
51 let direction = 1; // 1 = down, -1 = up
52
53 for (const character of plainText) {
54 rows[currentRow].push(character);
55
56 currentRow += direction;
57
58 // Change direction when hitting top or bottom rail
59 if (currentRow === rails - 1 || currentRow === 0) {
60 direction *= -1;
61 }
62 }
63
64 // Combine all rows into a single string
65 const cipherText = rows.map(row => row.join("")).join("");
66
67 return cipherText;
68 }
69
78 decode(cipherText: string, rails: number = 3): string {
79 if (rails <= 1) {
80 return cipherText;
81 }
82
83 const textLength = cipherText.length;
84 const railPattern: number[] = [];
85
86 let currentRow = 0;
87 let direction = 1;
88
89 // Determine the zigzag pattern used during encoding
90 for (let i = 0; i < textLength; i++) {
91 railPattern.push(currentRow);
92
93 currentRow += direction;
94
95 if (currentRow === rails - 1 || currentRow === 0) {
96 direction *= -1;
97 }
98 }
99
100 // Count how many characters belong to each rail
101 const railCharacterCounts = Array(rails).fill(0);
102 for (const rowIndex of railPattern) {
103 railCharacterCounts[rowIndex]++;
104 }
105
106 // Slice the ciphertext into its rails
107 const railsContent: string[][] = Array.from({ length: rails }, () => []);
108 let currentPosition = 0;
109
110 for (let rowIndex = 0; rowIndex < rails; rowIndex++) {
111 const rowLength = railCharacterCounts[rowIndex];
112 const rowCharacters = cipherText
113 .slice(currentPosition, currentPosition + rowLength)
114 .split("");
115
116 railsContent[rowIndex] = rowCharacters;
117 currentPosition += rowLength;
118 }
119
120 // Reconstruct plaintext by following the original pattern
121 const rowIndices = Array(rails).fill(0);
122 let plainText = "";
123
124 for (const rowIndex of railPattern) {
125 plainText += railsContent[rowIndex][rowIndices[rowIndex]];
126 rowIndices[rowIndex]++;
127 }
128
129 return plainText;
130 }
131}
Abstract base class providing common functionality for cipher implementations.
Definition baseCipher.ts:18
Implementation of the Rail Fence transposition cipher.
Definition railfence.ts:21
constructor()
Constructor for Rail Fence cipher.
Definition railfence.ts:32
readonly CipherName
Identifier name for this cipher.
Definition railfence.ts:25
export const Record< string,(...args:any[])=> string