关于base64编码的问题
1. 使用 Buffer对象
Buffer.from(JSON.stringify(jwtHeader)).toString('base64')
2. 使用base64js.js
(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.base64js = 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, !0)
}
if (f) {
return f(i, !0)
}
var d = new Error("Cannot find module '" + i + "'");
throw d.code = "MODULE_NOT_FOUND", d
}
var c = t[i] = {
exports: {}
};
e[i][0].call(c.exports, function (r) {
var t = e[i][1][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 = 0; 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 Uint8Array !== "undefined" ? Uint8Array : Array;
var i = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
for (var a = 0, u = i.length; a < u; ++a) {
n[a] = i[a];
o[i.charCodeAt(a)] = a
}
o["-".charCodeAt(0)] = 62;
o["_".charCodeAt(0)] = 63;
function d(r) {
var e = r.length;
if (e % 4 > 0) {
throw new Error("Invalid string. Length must be a multiple of 4")
}
return r[e - 2] === "=" ? 2 : r[e - 1] === "=" ? 1 : 0
}
function c(r) {
return r.length * 3 / 4 - d(r)
}
function v(r) {
var e, t, n, i, a;
var u = r.length;
i = d(r);
a = new f(u * 3 / 4 - i);
t = i > 0 ? u - 4 : u;
var c = 0;
for (e = 0; e < t; e += 4) {
n = o[r.charCodeAt(e)] << 18 | o[r.charCodeAt(e + 1)] << 12 | o[r.charCodeAt(e + 2)] << 6 | o[r.charCodeAt(e + 3)];
a[c++] = n >> 16 & 255;
a[c++] = n >> 8 & 255;
a[c++] = n & 255
}
if (i === 2) {
n = o[r.charCodeAt(e)] << 2 | o[r.charCodeAt(e + 1)] >> 4;
a[c++] = n & 255
} else {
if (i === 1) {
n = o[r.charCodeAt(e)] << 10 | o[r.charCodeAt(e + 1)] << 4 | o[r.charCodeAt(e + 2)] >> 2;
a[c++] = n >> 8 & 255;
a[c++] = n & 255
}
}
return a
}
function l(r) {
return n[r >> 18 & 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 += 3) {
n = (r[f] << 16) + (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 % 3;
var f = "";
var i = [];
var a = 16383;
for (var u = 0, d = t - o; u < d; u += a) {
i.push(h(r, u, u + a > d ? d : u + a))
}
if (o === 1) {
e = r[t - 1];
f += n[e >> 2];
f += n[e << 4 & 63];
f += "=="
} else {
if (o === 2) {
e = (r[t - 2] << 8) + r[t - 1];
f += n[e >> 10];
f += n[e >> 4 & 63];
f += n[e << 2 & 63];
f += "="
}
}
i.push(f);
return i.join("")
}
}, {}]
}, {}, [])("/")
});
字符串编码
var utf8StrToBytes = function (utf8Str) {
var ens = encodeURIComponent(utf8Str);
var es = unescape(ens);
var esLen = es.length;
// Convert
var words = [];
for (var i = 0; i < esLen; i++) {
words[i] = es.charCodeAt(i);
}
return words;
}
var bytesToUtf8Str = function (bytesArray) {
var utf8Byte = bytesArray;
var latin1Chars = [];
for (var i = 0; i < utf8Byte.length; i++) {
latin1Chars.push(String.fromCharCode(utf8Byte[i]));
}
return decodeURIComponent(escape(latin1Chars.join('')));
}
测试
base64.fromByteArray(utf8StrToBytes('打快点快点')) // 5omT5b+r54K55b+r54K5
//同Java中 org.apache.commons.codec
Base64.encodeBase64String("打快点快点".getBytes()) // 5omT5b+r54K55b+r54K5
3. js中类似java中byte强转int类型
var intToByte = function(i) {
var b = i & 0xFF;
var c = 0;
if (b >= 128) {
c = b % 128;
c = -1 * (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实现代码如下:
//2.加密、解密算法封装:
function Base64() {
// private property
_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// public method for encoding
this.encode = function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
// &3表示只要chr1的后两位
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
return output;
}
// public method for decoding
this.decode = function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = _utf8_decode(output);
return output;
}
// private method for UTF-8 encoding
_utf8_encode = function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
// private method for UTF-8 decoding
_utf8_decode = function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
} else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
const base64 = new Base64()
console.log(base64.encode('1ab'));
console.log(base64.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)构成。
解码的操作跟这个刚好相反,大家可以试试。
1ab
110001 1100001 1100010 49 97 98
00110001 01100001 01100010(补成8位,划分成6位,高位补2个0)
001100 010110 000101 100010 (开始划分成4个,不够补0)
12 22 5 34
MWFi
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。