This repository has been archived by the owner on Aug 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base64url.nut
129 lines (103 loc) · 2.78 KB
/
base64url.nut
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// Base64 URL functions accessed via the table 'Base64URL'
// Licence: MIT
// Code version 1.0.0
// EXAMPLES
// server.log(Base64URL.encode("ladies and gentlemen we are floating in space"));
// server.log(Base64URL.fromBase64("qL8R4QIcQ/ZsRqOAbeRfcZhilN/MksRtDaErMA=="));
// server.log(Base64URL.toBase64("qL8R4QIcQ_ZsRqOAbeRfcZhilN_MksRtDaErMA"));
// server.log(Base64URL.decode("cmlkZTogZHJlYW1zIGJ1cm4gZG93bg"));
Base64URL <- {};
Base64URL.padString <- function (input) {
local strLen = input.len();
local diff = strLen % 4;
if (!diff) return input;
local pos = strLen;
local padLen = 4 - diff;
local buffer = blob(strLen + padLen);
buffer.writestring(input);
while (padLen--) {
buffer.writestring("=");
pos++;
}
return buffer.tostring();
}
Base64URL.fromBase64 <- function (base64string) {
local rs = "";
local i = 0;
local a = 0;
do {
if (a > base64string.len()) break;
i = base64string.find("=", a);
if (i != null) {
rs = rs + base64string.slice(a, i);
a = i + 1;
} else {
rs = rs + base64string.slice(a);
}
} while (i != null);
base64string = rs;
rs = "";
i = 0;
a = 0;
do {
if (a > base64string.len()) break;
i = base64string.find("+", a);
if (i != null) {
rs = rs + base64string.slice(a, i) + "-";
a = i + 1;
} else {
rs = rs + base64string.slice(a);
}
} while (i != null);
base64string = rs;
rs = "";
i = 0;
a = 0;
do {
if (a > base64string.len()) break;
i = base64string.find("/", a);
if (i != null) {
rs = rs + base64string.slice(a, i) + "_";
a = i + 1;
} else {
rs = rs + base64string.slice(a);
}
} while (i != null);
return rs;
}
Base64URL.toBase64 <- function (base64url) {
local rs = "";
local i = 0;
local a = 0;
do {
if (a > base64url.len()) break;
i = base64url.find("-", a);
if (i != null) {
rs = rs + base64url.slice(a, i) + "+";
a = i + 1;
} else {
rs = rs + base64url.slice(a);
}
} while (i != null);
base64url = rs;
rs = "";
i = 0;
a = 0;
do {
if (a > base64url.len()) break;
i = base64url.find("_", a);
if (i != null) {
rs = rs + base64url.slice(a, i) + "/";
a = i + 1;
} else {
rs = rs + base64url.slice(a);
}
} while (i != null);
return padString(rs);
}
Base64URL.encode <- function (input){
return fromBase64(http.base64encode(input));
}
Base64URL.decode <- function (base64url) {
return http.base64decode(toBase64(base64url));
}