目录
- 关于base64编码的问题
- 1. 使用 Buffer对象
- 2. 使用base64js.js
- 3. js中类似java中byte强转int类型
- 手把手教你js实现base64编码规则
- 总结
关于base64编码的问题
1. 使用 Buffer对象
Buffer.from(JSON.stringify(jwtHeader)).toString('base')
2. 使用base64js.js
/** | |
* basejs Uint8Array 8位无符号整数,长度1个字节, | |
* basejs.byteLength(base64Str) base64字符串转为字节数组的长度 | |
* basejs.toByteArray(base64Str) base64字符串转为字节数组 | |
* basejs.fromByteArray(bytes) 字节数组转为base64字符串 | |
*/ | |
(function (r) { | |
if (typeof exports === "object" && typeof module !== "undefined") { | |
module.exports = r() | |
} else { | |
if (typeof define === "function" && define.amd) { | |
define([], r) | |
} else { | |
var e; | |
if (typeof window !== "undefined") { | |
e = window | |
} else { | |
if (typeof global !== "undefined") { | |
e = global | |
} else { | |
if (typeof self !== "undefined") { | |
e = self | |
} else { | |
e = this | |
} | |
} | |
} | |
e.basejs = r() | |
} | |
} | |
})(function () { | |
var r, e, t; | |
return function r(e, t, n) { | |
function o(i, a) { | |
if (!t[i]) { | |
if (!e[i]) { | |
var u = typeof require == "function" && require; | |
if (!a && u) { | |
return u(i, !) | |
} | |
if (f) { | |
return f(i, !) | |
} | |
var d = new Error("Cannot find module '" + i + "'"); | |
throw d.code = "MODULE_NOT_FOUND", d | |
} | |
var c = t[i] = { | |
exports: {} | |
}; | |
e[i][].call(c.exports, function (r) { | |
var t = e[i][][r]; | |
return o(t ? t : r) | |
}, c, c.exports, r, e, t, n) | |
} | |
return t[i].exports | |
} | |
var f = typeof require == "function" && require; | |
for (var i =; i < n.length; i++) { | |
o(n[i]) | |
} | |
return o | |
}({ | |
"/": [function (r, e, t) { | |
t.byteLength = c; | |
t.toByteArray = v; | |
t.fromByteArray = s; | |
var n = []; | |
var o = []; | |
var f = typeof UintArray !== "undefined" ? Uint8Array : Array; | |
var i = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"; | |
for (var a =, u = i.length; a < u; ++a) { | |
n[a] = i[a]; | |
o[i.charCodeAt(a)] = a | |
} | |
o["-".charCodeAt()] = 62; | |
o["_".charCodeAt()] = 63; | |
function d(r) { | |
var e = r.length; | |
if (e % > 0) { | |
throw new Error("Invalid string. Length must be a multiple of") | |
} | |
return r[e -] === "=" ? 2 : r[e - 1] === "=" ? 1 : 0 | |
} | |
function c(r) { | |
return r.length * / 4 - d(r) | |
} | |
function v(r) { | |
var e, t, n, i, a; | |
var u = r.length; | |
i = d(r); | |
a = new f(u * / 4 - i); | |
t = i > ? u - 4 : u; | |
var c =; | |
for (e =; e < t; e += 4) { | |
n = o[r.charCodeAt(e)] << | o[r.charCodeAt(e + 1)] << 12 | o[r.charCodeAt(e + 2)] << 6 | o[r.charCodeAt(e + 3)]; | |
a[c++] = n >> & 255; | |
a[c++] = n >> & 255; | |
a[c++] = n & | |
} | |
if (i ===) { | |
n = o[r.charCodeAt(e)] << | o[r.charCodeAt(e + 1)] >> 4; | |
a[c++] = n & | |
} else { | |
if (i ===) { | |
n = o[r.charCodeAt(e)] << | o[r.charCodeAt(e + 1)] << 4 | o[r.charCodeAt(e + 2)] >> 2; | |
a[c++] = n >> & 255; | |
a[c++] = n & | |
} | |
} | |
return a | |
} | |
function l(r) { | |
return n[r >> & 63] + n[r >> 12 & 63] + n[r >> 6 & 63] + n[r & 63] | |
} | |
function h(r, e, t) { | |
var n; | |
var o = []; | |
for (var f = e; f < t; f +=) { | |
n = (r[f] <<) + (r[f + 1] << 8) + r[f + 2]; | |
o.push(l(n)) | |
} | |
return o.join("") | |
} | |
function s(r) { | |
var e; | |
var t = r.length; | |
var o = t %; | |
var f = ""; | |
var i = []; | |
var a =; | |
for (var u =, d = t - o; u < d; u += a) { | |
i.push(h(r, u, u + a > d ? d : u + a)) | |
} | |
if (o ===) { | |
e = r[t -]; | |
f += n[e >>]; | |
f += n[e << & 63]; | |
f += "==" | |
} else { | |
if (o ===) { | |
e = (r[t -] << 8) + r[t - 1]; | |
f += n[e >>]; | |
f += n[e >> & 63]; | |
f += n[e << & 63]; | |
f += "=" | |
} | |
} | |
i.push(f); | |
return i.join("") | |
} | |
}, {}] | |
}, {}, [])("/") | |
}); |
字符串编码
/** | |
* utf字符串转为字节数组 同java中 String.getBytes(utf8Str) | |
* @param utfStr | |
* @returns {[]} | |
*/ | |
var utfStrToBytes = function (utf8Str) { | |
var ens = encodeURIComponent(utfStr); | |
var es = unescape(ens); | |
var esLen = es.length; | |
// Convert | |
var words = []; | |
for (var i =; i < esLen; i++) { | |
words[i] = es.charCodeAt(i); | |
} | |
return words; | |
} | |
/** | |
* 字节数组转为utf字符串 同java中 new String(bytes) | |
* @param bytesArray | |
* @returns {string} | |
*/ | |
var bytesToUtfStr = function (bytesArray) { | |
var utfByte = bytesArray; | |
var latinChars = []; | |
for (var i =; i < utf8Byte.length; i++) { | |
latinChars.push(String.fromCharCode(utf8Byte[i])); | |
} | |
return decodeURIComponent(escape(latinChars.join(''))); | |
} |
测试
base.fromByteArray(utf8StrToBytes('打快点快点')) // 5omT5b+r54K55b+r54K5 | |
//同Java中 org.apache.commons.codec | |
Base.encodeBase64String("打快点快点".getBytes()) // 5omT5b+r54K55b+r54K5 |
3. js中类似java中byte强转int类型
/** | |
* int 转 byte, js中int转byte(-—127) | |
* @param i 整数 | |
*/ | |
var intToByte = function(i) { | |
var b = i &xFF; | |
var c =; | |
if (b >=) { | |
c = b %; | |
c = - * (128 - c); | |
} else { | |
c = b; | |
} | |
return c | |
} |
手把手教你js实现base64编码规则
base64编码是使用自己的编码规则重新编码ascii码,原理是将3*8个字节用4*6去代替,将8字节划分时会在前面添加2个0形成6位,最后不够4个字节全补0。
base64也是基于64个可打印的字符来表示二进制的数据的一种方法。
base64编码表如下图所示:
js实现代码如下:
//.加密、解密算法封装: | |
function Base() { | |
// private property | |
_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/="; | |
// public method for encoding | |
this.encode = function (input) { | |
var output = ""; | |
var chr, chr2, chr3, enc1, enc2, enc3, enc4; | |
var i =; | |
input = _utf_encode(input); | |
while (i < input.length) { | |
chr = input.charCodeAt(i++); | |
chr = input.charCodeAt(i++); | |
chr = input.charCodeAt(i++); | |
enc = chr1 >> 2; | |
// &表示只要chr1的后两位 | |
enc = ((chr1 & 3) << 4) | (chr2 >> 4); | |
enc = ((chr2 & 15) << 2) | (chr3 >> 6); | |
enc = chr3 & 63; | |
if (isNaN(chr)) { | |
enc = enc4 = 64; | |
} else if (isNaN(chr)) { | |
enc = 64; | |
} | |
output = output + | |
_keyStr.charAt(enc) + _keyStr.charAt(enc2) + | |
_keyStr.charAt(enc) + _keyStr.charAt(enc4); | |
} | |
return output; | |
} | |
// public method for decoding | |
this.decode = function (input) { | |
var output = ""; | |
var chr, chr2, chr3; | |
var enc, enc2, enc3, enc4; | |
var i =; | |
input = input.replace(/[^A-Za-z-9\+\/\=]/g, ""); | |
while (i < input.length) { | |
enc = _keyStr.indexOf(input.charAt(i++)); | |
enc = _keyStr.indexOf(input.charAt(i++)); | |
enc = _keyStr.indexOf(input.charAt(i++)); | |
enc = _keyStr.indexOf(input.charAt(i++)); | |
chr = (enc1 << 2) | (enc2 >> 4); | |
chr = ((enc2 & 15) << 4) | (enc3 >> 2); | |
chr = ((enc3 & 3) << 6) | enc4; | |
output = output + String.fromCharCode(chr); | |
if (enc != 64) { | |
output = output + String.fromCharCode(chr); | |
} | |
if (enc != 64) { | |
output = output + String.fromCharCode(chr); | |
} | |
} | |
output = _utf_decode(output); | |
return output; | |
} | |
// private method for UTF- encoding | |
_utf_encode = function (string) { | |
string = string.replace(/\r\n/g,"\n"); | |
var utftext = ""; | |
for (var n =; n < string.length; n++) { | |
var c = string.charCodeAt(n); | |
if (c <) { | |
utftext += String.fromCharCode(c); | |
} else if((c >) && (c < 2048)) { | |
utftext += String.fromCharCode((c >>) | 192); | |
utftext += String.fromCharCode((c &) | 128); | |
} else { | |
utftext += String.fromCharCode((c >>) | 224); | |
utftext += String.fromCharCode(((c >>) & 63) | 128); | |
utftext += String.fromCharCode((c &) | 128); | |
} | |
} | |
return utftext; | |
} | |
// private method for UTF- decoding | |
_utf_decode = function (utftext) { | |
var string = ""; | |
var i =; | |
var c = c = c2 = 0; | |
while ( i < utftext.length ) { | |
c = utftext.charCodeAt(i); | |
if (c <) { | |
string += String.fromCharCode(c); | |
i++; | |
} else if((c >) && (c < 224)) { | |
c = utftext.charCodeAt(i+1); | |
string += String.fromCharCode(((c &) << 6) | (c2 & 63)); | |
i +=; | |
} else { | |
c = utftext.charCodeAt(i+1); | |
c = utftext.charCodeAt(i+2); | |
string += String.fromCharCode(((c &) << 12) | ((c2 & 63) << 6) | (c3 & 63)); | |
i +=; | |
} | |
} | |
return string; | |
} | |
} | |
const base = new Base64() | |
console.log(base.encode('1ab')); | |
console.log(base.decode('MWE=')); |
二进制3*8位转4*6参考下图:
- 1.先来看看encode实现原理,首先是获取ascii码值,第一个字节001100是1在ascii码中是49,二进制是110001,此时在前面新增00得到00110001,第一个字节是110001右移两位得到001100。
- 2.我们看看第二个码010110,它是由第一个字节110001的后两位(&3)和第二个字节1100001的前四位(>>4)共同构成。
- 3.第三个码000101,它是由第二个字节1100001后四位(&15)和第三个字节的前两位(>>6)。
- 4.第四个码100010,它是由第三个字节1100010的后六位(&63)构成。
解码的操作跟这个刚好相反,大家可以试试。
ab | |
1100001 1100010 49 97 98 | |
01100001 01100010(补成8位,划分成6位,高位补2个0) | |
010110 000101 100010 (开始划分成4个,不够补0) | |
22 5 34 | |
MWFi |