Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
titaniumnetwork-dev
GitHub Repository: titaniumnetwork-dev/Ludicrous
Path: blob/main/corrosion/lib/codec.js
1223 views
1
// -------------------------------------------------------------
2
// WARNING: this file is used by both the client and the server.
3
// Do not use any browser or node-specific API!
4
// -------------------------------------------------------------
5
exports.xor = {
6
encode(str){
7
if (!str) return str;
8
return encodeURIComponent(str.toString().split('').map((char, ind) => ind % 2 ? String.fromCharCode(char.charCodeAt() ^ 2) : char).join(''));
9
},
10
decode(str){
11
if (!str) return str;
12
return decodeURIComponent(str).split('').map((char, ind) => ind % 2 ? String.fromCharCode(char.charCodeAt() ^ 2) : char).join('');
13
},
14
};
15
exports.plain = {
16
encode(str) {
17
if (!str) return str;
18
return encodeURIComponent(str);
19
},
20
decode(str) {
21
if (!str) return str;
22
return decodeURIComponent(str);
23
},
24
};
25
exports.base64 = {
26
encode(str){
27
if (!str) return str;
28
str = str.toString();
29
const b64chs = Array.from('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=');
30
let u32;
31
let c0;
32
let c1;
33
let c2;
34
let asc = '';
35
let pad = str.length % 3;
36
37
for (let i = 0; i < str.length;) {
38
if((c0 = str.charCodeAt(i++)) > 255 || (c1 = str.charCodeAt(i++)) > 255 || (c2 = str.charCodeAt(i++)) > 255)throw new TypeError('invalid character found');
39
u32 = (c0 << 16) | (c1 << 8) | c2;
40
asc += b64chs[u32 >> 18 & 63]
41
+ b64chs[u32 >> 12 & 63]
42
+ b64chs[u32 >> 6 & 63]
43
+ b64chs[u32 & 63];
44
}
45
46
return encodeURIComponent(pad ? asc.slice(0, pad - 3) + '==='.substr(pad) : asc);
47
},
48
decode(str){
49
if (!str) return str;
50
str = decodeURIComponent(str.toString());
51
const b64tab = {"0":52,"1":53,"2":54,"3":55,"4":56,"5":57,"6":58,"7":59,"8":60,"9":61,"A":0,"B":1,"C":2,"D":3,"E":4,"F":5,"G":6,"H":7,"I":8,"J":9,"K":10,"L":11,"M":12,"N":13,"O":14,"P":15,"Q":16,"R":17,"S":18,"T":19,"U":20,"V":21,"W":22,"X":23,"Y":24,"Z":25,"a":26,"b":27,"c":28,"d":29,"e":30,"f":31,"g":32,"h":33,"i":34,"j":35,"k":36,"l":37,"m":38,"n":39,"o":40,"p":41,"q":42,"r":43,"s":44,"t":45,"u":46,"v":47,"w":48,"x":49,"y":50,"z":51,"+":62,"/":63,"=":64};
52
str = str.replace(/\s+/g, '');
53
str += '=='.slice(2 - (str.length & 3));
54
let u24;
55
let bin = '';
56
let r1;
57
let r2;
58
59
for (let i = 0; i < str.length;) {
60
u24 = b64tab[str.charAt(i++)] << 18
61
| b64tab[str.charAt(i++)] << 12
62
| (r1 = b64tab[str.charAt(i++)]) << 6
63
| (r2 = b64tab[str.charAt(i++)]);
64
bin += r1 === 64 ? String.fromCharCode(u24 >> 16 & 255)
65
: r2 === 64 ? String.fromCharCode(u24 >> 16 & 255, u24 >> 8 & 255)
66
: String.fromCharCode(u24 >> 16 & 255, u24 >> 8 & 255, u24 & 255);
67
};
68
return bin;
69
},
70
};
71
72