-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautokey.js
59 lines (55 loc) · 1.32 KB
/
autokey.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
function Autokey (key, alphabet) {
this.key = []
for (var i = 0, ii = key.length; i < ii; ++i) {
this.key[i] = key[i].charCodeAt(0)
}
this.betaalph = []
for (i = 0, ii = alphabet.length; i < ii; ++i) {
this.betaalph[alphabet[i]] = i
}
this.alphabet = alphabet
this.keylen = key.length
this.alphalen = alphabet.length
}
Autokey.prototype.encode = function (raw) {
var res = ''
var cc = this.keylen
var last = []
var k
for (var i = 0, ii = raw.length; i < ii; ++i) {
if (this.betaalph[raw[i]] === undefined) {
res += raw[i]
} else {
if (cc-- > 0) {
k = this.key[cc]
} else {
k = this.betaalph[last.shift()]
}
var c = this.alphabet[(this.betaalph[raw[i]] + k) % this.alphalen]
res += c
last.push(c)
}
}
return res
}
Autokey.prototype.decode = function (raw) {
var res = ''
var cc = this.keylen
var last = []
var k
for (var i = 0, ii = raw.length; i < ii; ++i) {
if (this.betaalph[raw[i]] === undefined) {
res += raw[i]
} else {
if (cc-- > 0) {
k = this.key[cc] % this.alphalen
} else {
k = this.betaalph[last.shift()]
}
res += this.alphabet[(this.betaalph[raw[i]] - k + this.alphalen) % this.alphalen]
last.push(raw[i])
}
}
return res
}
module.exports = Autokey