base64.js
1.06 KB
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
'use strict';
var Enc = require('./bytes.js');
// To Base64
Enc.bufToBase64 = function(u8) {
var bin = '';
u8.forEach(function(i) {
bin += String.fromCharCode(i);
});
return btoa(bin);
};
Enc.strToBase64 = function(str) {
return btoa(Enc.strToBin(str));
};
// From Base64
function _base64ToBin(b64) {
return atob(Enc.urlBase64ToBase64(b64));
}
Enc._base64ToBin = _base64ToBin;
Enc.base64ToBuf = function(b64) {
return Enc.binToBuf(_base64ToBin(b64));
};
Enc.base64ToStr = function(b64) {
return Enc.binToStr(_base64ToBin(b64));
};
// URL Safe Base64
Enc.urlBase64ToBase64 = function(u64) {
var r = u64 % 4;
if (2 === r) {
u64 += '==';
} else if (3 === r) {
u64 += '=';
}
return u64.replace(/-/g, '+').replace(/_/g, '/');
};
Enc.base64ToUrlBase64 = function(b64) {
return b64
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '');
};
Enc.bufToUrlBase64 = function(buf) {
return Enc.base64ToUrlBase64(Enc.bufToBase64(buf));
};
Enc.strToUrlBase64 = function(str) {
return Enc.bufToUrlBase64(Enc.strToBuf(str));
};
module.exports = Enc;