-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBasic32.ts
87 lines (67 loc) · 2 KB
/
Basic32.ts
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
const SIMILAR_CHAR = {
O: '0',
I: '1',
L: '1',
B: '8',
};
const CASTABLE_CHAR = {
O: 'W',
I: 'X',
L: 'Y',
B: 'Z',
};
class Base32OTP {
readonly digits: number;
readonly outputDigits: number;
constructor(digits = 6) {
this.digits = digits;
this.outputDigits = Number(Math.pow(10, digits) - 1).toString(32).length;
}
encode(rawCode: number | string) {
if (
typeof rawCode === 'string' &&
(!/^\d+$/.test(rawCode) || rawCode.length > this.digits)
)
throw new Error('Invalid code passed');
let code = Number(rawCode).toString(32).toUpperCase();
Object.keys(CASTABLE_CHAR).forEach(function (badLetter) {
code = code.replace(
new RegExp(badLetter, 'g'),
CASTABLE_CHAR[<keyof typeof CASTABLE_CHAR>badLetter],
);
});
const template = Array.from({length: this.outputDigits}, function () {
return '0';
});
return Object.assign(template, code.split('').reverse()).reverse().join('');
}
decode(rawCode: string) {
if (
/^\d+$/.test(rawCode) &&
rawCode.length === this.digits &&
rawCode.length !== this.outputDigits
)
return rawCode;
if (!/^[\dA-Za-z]+$/.test(rawCode) || rawCode.length !== this.outputDigits)
throw new Error(
'Code should be ' + this.outputDigits + ' alphanumeric characters',
);
let code = rawCode.toUpperCase();
Object.keys(SIMILAR_CHAR).forEach(function (badLetter) {
code = code.replace(
new RegExp(badLetter, 'g'),
SIMILAR_CHAR[<keyof typeof SIMILAR_CHAR>badLetter],
);
});
Object.keys(CASTABLE_CHAR).forEach(function (badLetter) {
code = code.replace(
new RegExp(CASTABLE_CHAR[<keyof typeof CASTABLE_CHAR>badLetter], 'g'),
badLetter,
);
});
const template = Array.from({length: this.digits}, () => '0');
code = parseInt(code, 32).toString(10);
return Object.assign(template, code.split('').reverse()).reverse().join('');
}
}
export default Base32OTP;