-
Notifications
You must be signed in to change notification settings - Fork 46
/
base32.js
103 lines (81 loc) · 2.13 KB
/
base32.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
// Module for encoding/decoding base32
var Base32 = (function () {
"use strict";
// Vars used
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
pad_lengths = [ 0, 1, 3, 4, 6 ],
pad_char = "=";
// Encode/decode functions
return {
/**
Encode a string into base32
@param str
The string to convert.
This string should be encoded in some way such that each character is in the range [0,255]
@return
A base32 encoded string
*/
encode: function (str) {
var len = str.length,
str_new = "",
i = 0,
c1, c2, c3, c4, c5;
// Null pad
while ((str.length % 5) !== 0) str += "\x00";
// String modify
while (i < len) {
c1 = str.charCodeAt(i++);
c2 = str.charCodeAt(i++);
c3 = str.charCodeAt(i++);
c4 = str.charCodeAt(i++);
c5 = str.charCodeAt(i++);
str_new += alphabet[(c1 >> 3)];
str_new += alphabet[((c1 & 0x07) << 2) | (c2 >> 6)];
str_new += alphabet[((c2 & 0x3F) >> 1)];
str_new += alphabet[((c2 & 0x01) << 4) | (c3 >> 4)];
str_new += alphabet[((c3 & 0x0F) << 1) | (c4 >> 7)];
str_new += alphabet[((c4 & 0x7F) >> 2)];
str_new += alphabet[((c4 & 0x03) << 3) | (c5 >> 5)];
str_new += alphabet[(c5 & 0x1F)];
}
// Padding
if (i > len) {
i = pad_lengths[i - len]; // (i - len) equals the number of times \x00 was padded
str_new = str_new.substr(0, str_new.length - i);
while ((str_new.length % 8) !== 0) str_new += pad_char;
}
// Done
return str_new;
},
/**
Decode a string from base32
@param str
A valid base32 string
@return
The original string
*/
decode: function (str) {
var len = str.length,
str_new = "",
bits = 0,
char_buffer = 0,
i;
// Cut off padding
while (len > 0 && str[len - 1] == "=") --len;
// Iterate
for (i = 0; i < len; ++i) {
// Update with the 32bit value
char_buffer = (char_buffer << 5) | alphabet.indexOf(str[i]);
// Update bitcount
bits += 5;
if (bits >= 8) {
// Update string
str_new += String.fromCharCode((char_buffer >> (bits - 8)) & 0xFF);
bits -= 8;
}
}
// Done
return str_new;
},
};
})();