MCPcopy Create free account
hub / github.com/cryptii/cryptii / performEncode

Method performEncode

src/Encoder/TrifidCipher.js:59–118  ·  view source on GitHub ↗

* Performs encode on given content. * @protected * @param {Chain} content * @return {number[]|string|Uint8Array|Chain} Encoded content

(content)

Source from the content-addressed store, hash-verified

57 * @return {number[]|string|Uint8Array|Chain} Encoded content
58 */
59 async performEncode (content) {
60 const { key, groupSize } = this.getSettingValues()
61
62 // Derive mixed-alphabet from key
63 const alphabet = Chain.wrap(key).extend(baseAlphabet).getCodePoints()
64
65 // Map Unicode code points to their respective alphabet positions
66 const positions =
67 content.toLowerCase().getCodePoints()
68 .map(codePoint => alphabet.indexOf(codePoint))
69 .filter(codePoint => codePoint !== -1)
70
71 // Delastelle says: 'We start by writing vertically under each letter, the
72 // numerical trigram that corresponds to it in the enciphering alphabet'
73 // a i d e t o i l e c
74 // 1 1 1 1 2 3 1 1 1 2
75 // 3 2 3 1 1 1 2 1 1 2
76 // 1 1 3 2 2 1 1 3 2 1
77
78 // Thus working with a one-dimensional array to represent the above table
79 // we enumerate coordinates like this:
80 // a i d e t o i l e c
81 // 01 02 03 04 05 21 22 23 24 25
82 // 06 07 08 09 10 26 27 28 29 30
83 // 11 12 13 14 15 31 32 33 34 35
84 // 16 17 18 19 20 36 37 38 39 40
85 const length = positions.length
86 const table = new Array(length * 3)
87 let i, j, coordinates, group, index, size
88
89 for (i = 0; i < length; i++) {
90 // Gather group number, character index inside group and group size, which
91 // may be shorter for the last group
92 group = Math.floor(i / groupSize)
93 index = i - group * groupSize
94 size = Math.min(groupSize, length - group * groupSize)
95
96 // Position group coordinates vertically inside the one-dimensional table
97 coordinates = this.cartesianCoordinatesFromIndex(positions[i])
98 for (j = 0; j < 3; j++) {
99 table[index + group * groupSize * 3 + size * j] = coordinates[j]
100 }
101 }
102
103 // Following Delastelle: 'Proceeding horizontally as if the numbers were
104 // written on a single line, we take groups of three numbers, look them up
105 // in the deciphering alphabet'
106 // Having built a one-dimensional array, we read 3-element cartesian
107 // coordinates successively, translate them to one-dimensional indexes and
108 // map each of them to the corresponding alphabet character
109 const result = new Array(length)
110
111 for (i = 0; i < length; i++) {
112 coordinates = table.slice(i * 3, (i + 1) * 3)
113 index = this.indexFromCartesianCoordinates(coordinates)
114 result[i] = alphabet[index]
115 }
116

Callers

nothing calls this directly

Calls 8

getSettingValuesMethod · 0.80
getCodePointsMethod · 0.80
extendMethod · 0.80
wrapMethod · 0.80
toLowerCaseMethod · 0.80
indexOfMethod · 0.80

Tested by

no test coverage detected