-
-
Notifications
You must be signed in to change notification settings - Fork 241
/
CaesarCipher.js
199 lines (180 loc) · 5.32 KB
/
CaesarCipher.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
import Encoder from '../Encoder'
import MathUtil from '../MathUtil'
const meta = {
name: 'caesar-cipher',
title: 'Caesar cipher',
category: 'Ciphers',
type: 'encoder'
}
const defaultAlphabet = 'abcdefghijklmnopqrstuvwxyz'
const defaultShift = 7
/**
* Encoder brick for Caesar Cipher encoding and decoding
*/
export default class CaesarCipherEncoder extends Encoder {
/**
* Returns brick meta.
* @return {object}
*/
static getMeta () {
return meta
}
/**
* Constructor
*/
constructor () {
super()
this.addSettings([
{
name: 'shift',
type: 'number',
label: 'Shift',
priority: 10,
value: defaultShift,
integer: true,
useBigInt: true,
describeValue: this.describeShiftValue.bind(this),
randomizeValue: this.randomizeShiftValue.bind(this)
},
{
name: 'alphabet',
type: 'text',
value: defaultAlphabet,
uniqueChars: true,
minLength: 2,
caseSensitivity: false,
randomizable: false
},
{
name: 'caseStrategy',
type: 'enum',
value: 'maintain',
elements: ['maintain', 'ignore', 'strict'],
labels: ['Maintain case', 'Ignore case', 'Strict (A ≠ a)'],
width: 6,
randomizable: false
},
{
name: 'includeForeignChars',
type: 'boolean',
label: 'Foreign Chars',
width: 6,
value: true,
trueLabel: 'Include',
falseLabel: 'Ignore',
randomizable: false
}
])
}
/**
* Performs encode or decode on given content.
* @param {Chain} content
* @param {boolean} isEncode True for encoding, false for decoding
* @return {number[]|string|Uint8Array|Chain} Resulting content
*/
performTranslate (content, isEncode) {
const { shift, caseStrategy, includeForeignChars } =
this.getSettingValues()
// Prepare alphabet(s) depending on chosen case strategy
let alphabet = this.getSettingValue('alphabet')
let uppercaseAlphabet
if (caseStrategy !== 'strict') {
alphabet = alphabet.toLowerCase()
uppercaseAlphabet = alphabet.toUpperCase()
}
const m = alphabet.getLength()
const n = content.getLength()
const result = new Array(n)
let codePoint, x, y, uppercase
let j = 0
// Go through each character in content
for (let i = 0; i < n; i++) {
codePoint = content.getCodePointAt(i)
// Match alphabet character
x = alphabet.indexOfCodePoint(codePoint)
uppercase = false
// Match uppercase alphabet character (depending on case strategy)
if (x === -1 && caseStrategy !== 'strict') {
x = uppercaseAlphabet.indexOfCodePoint(codePoint)
uppercase = true
}
if (x === -1) {
// Character is not in the alphabet
if (includeForeignChars) {
result[j++] = codePoint
}
} else {
// Shift character
if (typeof shift !== 'bigint') {
y = MathUtil.mod(x + shift * (isEncode ? 1 : -1), m)
} else {
y = Number(MathUtil.mod(
BigInt(x) + shift * BigInt(isEncode ? 1 : -1),
BigInt(m)
))
}
// Translate index to character following the case strategy
if (caseStrategy === 'maintain' && uppercase) {
result[j++] = uppercaseAlphabet.getCodePointAt(y)
} else {
result[j++] = alphabet.getCodePointAt(y)
}
}
}
return result.slice(0, j)
}
/**
* 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 'caseStrategy':
// Apply case sensitivity on the alphabet setting
this.getSetting('alphabet').setCaseSensitivity(value === 'strict')
break
case 'alphabet':
// The shift value description depends on the alphabet and thus needs
// to be updated when the alphabet changes
this.getSetting('shift').setNeedsValueDescriptionUpdate()
break
}
}
/**
* Generates a random shift setting value.
* @param {Random} random Random instance
* @param {Field} setting Shift setting
* @return {string} Randomized plugboard setting value
*/
randomizeShiftValue (random, setting) {
const alphabetSetting = this.getSetting('alphabet')
if (alphabetSetting.isValid()) {
return random.nextInteger(1, alphabetSetting.getValue().getLength() - 1)
}
return null
}
/**
* Function describing the given shift value in a human-readable way.
* @param {number} value Field value
* @param {Field} setting Sender
* @return {?string} Shift label
*/
describeShiftValue (value, setting) {
// The shift value description depends on the alphabet setting
if (!this.getSetting('alphabet').isValid()) {
return null
}
// Shift the first character of the alphabet to describe the translation
const { alphabet, shift } = this.getSettingValues()
const plain = alphabet.getCharAt(0)
const index = MathUtil.mod(
shift,
typeof shift !== 'bigint'
? alphabet.getLength()
: BigInt(alphabet.getLength())
)
const encoded = alphabet.getCharAt(index)
return `${plain}→${encoded}`
}
}