-
-
Notifications
You must be signed in to change notification settings - Fork 241
/
ADFGXCipher.js
271 lines (239 loc) · 7.64 KB
/
ADFGXCipher.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import ArrayUtil from '../ArrayUtil'
import Chain from '../Chain'
import Encoder from '../Encoder'
import PolybiusSquareEncoder from './PolybiusSquare'
const meta = {
name: 'adfgx-cipher',
title: 'ADFGX cipher',
category: 'Polybius square ciphers',
type: 'encoder'
}
/**
* Default variant name.
* @type {string}
*/
const defaultVariantName = 'adfgx'
/**
* Array of ADFGVX variants.
* @type {object[]}
*/
const variants = [
{
name: 'adfgx',
label: 'ADFGX',
squarePositions: 'adfgx',
// Reversed base alphabet without the letter J
alphabet: 'zyxwvutsrqponmlkihgfedcba'
},
{
name: 'adfgvx',
label: 'ADFGVX',
squarePositions: 'adfgvx',
// Reverse base alphabet including the letter J and numbers 0-9
alphabet: '9876543210zyxwvutsrqponmlkjihgfedcba'
}
]
/**
* Alphabet (without the letter J)
* @type {string}
*/
const alphabet = 'abcdefghiklmnopqrstuvwxyz'
/**
* Encoder brick for ADFGVX cipher encryption and decryption
*/
export default class ADFGVXCipherEncoder extends Encoder {
/**
* Returns brick meta.
* @return {object}
*/
static getMeta () {
return meta
}
/**
* Constructor
*/
constructor () {
super()
this.addSettings([
{
name: 'variant',
type: 'enum',
value: defaultVariantName,
elements: variants.map(variant => variant.name),
labels: variants.map(variant => variant.label),
randomizable: false
},
{
name: 'alphabet',
type: 'text',
value: alphabet,
uniqueChars: true,
blacklistChars: ' ',
minLength: 0,
maxLength: 25,
caseSensitivity: false
},
{
name: 'key',
type: 'text',
value: 'cargo',
minLength: 2,
maxLength: 24,
caseSensitivity: false
}
])
// Create internal Polybius square encoder instance
const variant = this.constructor.getVariant(defaultVariantName)
this._polybiusSquare = new PolybiusSquareEncoder()
this._polybiusSquare.setSettingValues({
alphabet: alphabet,
rows: variant.squarePositions,
columns: variant.squarePositions,
separator: '',
caseSensitivity: false,
includeForeignChars: false
})
}
/**
* Performs encode on given content.
* @protected
* @param {Chain} content
* @return {number[]|string|Uint8Array|Chain} Encoded content
*/
async performEncode (content) {
// Prepare content
let contentString = content.getString()
const variantName = this.getSettingValue('variant')
if (variantName === 'adfgx') {
// As I and J shares the same alphabet position, replace all J chars
contentString = contentString.replace(/j/gi, 'i')
}
// Derive column map from key
const key = this.getSettingValue('key')
const keyLength = key.getLength()
const columnMap = this.mapElementsToSortedPosition(key.getChars())
// Encode content to coordinates using Polybius square
const polybius = await this._polybiusSquare.encode(contentString)
const polybiusLength = polybius.getLength()
// Encode Polybius square coordinates using substitution and transposition
const result = new Array(polybiusLength + keyLength)
let i, column, row, index
let j = 0
for (i = 0; i < keyLength; i++) {
// Derive column from key
column = columnMap[i]
// Go through each column row
for (row = 0; row * keyLength + column < polybiusLength; row++) {
// Translate 2D column and row coordintes to 1D index
index = row * keyLength + column
result[j++] = polybius.getCodePointAt(index)
}
}
// Group result in pairs of 5 characters each, separated by a space
return ArrayUtil.joinSlices(ArrayUtil.chunk(result.slice(0, j), 5), [32])
}
/**
* Performs decode on given content.
* @protected
* @param {Chain} content
* @return {number[]|string|Uint8Array|Chain} Decoded content
*/
performDecode (content) {
const variantName = this.getSettingValue('variant')
const variant = this.constructor.getVariant(variantName)
const squarePositions = Chain.wrap(variant.squarePositions).getCodePoints()
// Prepare content by removing non-position characters
const codePoints = content.getCodePoints()
.filter(codePoint => squarePositions.indexOf(codePoint) !== -1)
const length = codePoints.length
// Derive column map from key
const key = this.getSettingValue('key')
const keyLength = key.getLength()
const columnMap = this.mapElementsToSortedPosition(key.getChars())
// Calculate the number of columns available in the last row as the
// plaintext content may not have filled up the entire grid
let lastRowColumns = (length % keyLength) || keyLength
let rows = Math.ceil(length / keyLength)
// Decode code points to Polybius square coordinates
const polybius = new Array(length)
let index = 0
let i, column, row, columnRows
// Go through columns
for (i = 0; i < keyLength; i++) {
column = columnMap[i]
// The last row of this column may be empty
columnRows = column >= lastRowColumns ? rows - 1 : rows
// Transpose each column character
for (row = 0; row < columnRows; row++) {
polybius[row * keyLength + column] = codePoints[index++]
}
}
// Decode coordinates using Polybius square
return this._polybiusSquare.decode(polybius)
}
/**
* Maps the given elements to their corresponding positions in a sorted array.
* @protected
* @param {array} elements Array of elements
* @return {array} Array with the corresponding position for each element
*/
mapElementsToSortedPosition (elements) {
const length = elements.length
const map = new Array(length)
let from = elements.slice()
let to = elements.slice().sort()
let index
for (let k = 0; k < length; k++) {
index = from.indexOf(to[k])
map[k] = index
// Flag the element as claimed, with that duplicate elements are mapped to
// different sorted positions
delete from[index]
}
return map
}
/**
* Triggered when a setting field has changed.
* @param {Field} setting Sender setting field
* @param {mixed} value New field value
*/
settingValueDidChange (setting, value) {
switch (setting.getName()) {
case 'variant': {
// Configure the Polybius square according to the given variant
const variant = this.constructor.getVariant(value)
this._polybiusSquare.setSettingValues({
rows: variant.squarePositions,
columns: variant.squarePositions
})
// Update alphabet, if setting is valid
const alphabetSetting = this.getSetting('alphabet')
if (alphabetSetting.isValid()) {
this._polybiusSquare.setSettingValue('alphabet',
alphabetSetting.getValue().extend(variant.alphabet))
}
// Configure variant constraints
this.getSetting('alphabet').setMaxLength(variant.alphabet.length)
this.getSetting('key').setMaxLength(variant.alphabet.length - 1)
break
}
case 'alphabet': {
// Derive Polybius square mixed alphabet from the alphabet setting
const variant = this.constructor.getVariant(
this.getSettingValue('variant'))
this._polybiusSquare.setSettingValue('alphabet',
value.extend(variant.alphabet))
break
}
}
}
/**
* Returns a variant for the given name.
* @protected
* @param {string} name Variant name
* @return {object|null} Variant object or null, if unknown
*/
static getVariant (name) {
return variants.find(variant => variant.name === name) || null
}
}