-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodhex.js
executable file
·69 lines (53 loc) · 1.71 KB
/
modhex.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
// modhex mapping base; c.....v => 0x0 ... 0xF
const modhexBase = 'cbdefghijklnrtuv'.split('');
// Convert the Yubico MODHEX encoded Strings to hex
function decode(input, encoding='hex'){
// strip whitespaces and string cleanup - all non matching characters are 0x00 (c in modhex)
const modhex = input.replace(/\s*/g, '').replace(/[^cbdefghijklnrtuv]/g, 'c');
// even length ?
if (modhex.length%2 !== 0){
throw new Error('modhex string has no even length (' + modhex.length + ')');
}
// tmp
let hexOutput = '';
// convert each character
for (let i=0;i<modhex.length;i++){
// convert index to hex
hexOutput += modhexBase.indexOf(modhex.charAt(i)).toString(16);
}
// output as buffer ?
if (encoding === 'buffer'){
return Buffer.from(hexOutput, 'hex');
}else{
return hexOutput;
}
}
// Convert hex Strings to the Yubico MODHEX
function encode(input){
// hex encoded input string
let hexInput = '';
// hex or buffer input ?
if (typeof input === 'string'){
// strip whitespaces and string cleanup
hexInput = input.replace(/\s*/g, '').replace(/[^a-f0-9]/gi, '');
// even length ?
if (hexInput.length%2 !== 0){
throw new Error('hex input string has no even length (' + hexInput.length + ')');
}
}else{
// buffer to hex
hexInput = input.toString('hex');
}
// tmp
let modhexOutput = '';
// convert
for (let i=0;i<hexInput.length;i++){
// convert index to hex
modhexOutput += modhexBase[(parseInt(hexInput.charAt(i), 16))];
}
return modhexOutput;
}
module.exports = {
encode: encode,
decode: decode
};