TypeScript编码解码Base64
1 const Base64 = { 2 _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=', 3 _utf8_encode: function(string:string) { 4 string = string.replace(/\r\n/g, '\n') 5 let utftext = '' 6 for (let n = 0; n < string.length; n++) { 7 const c = string.charCodeAt(n) 8 if (c < 128) { 9 utftext += String.fromCharCode(c) 10 } else if ((c > 127) && (c < 2048)) { 11 utftext += String.fromCharCode((c >> 6) | 192) 12 utftext += String.fromCharCode((c & 63) | 128) 13 } else { 14 utftext += String.fromCharCode((c >> 12) | 224) 15 utftext += String.fromCharCode(((c >> 6) & 63) | 128) 16 utftext += String.fromCharCode((c & 63) | 128) 17 } 18 } 19 return utftext 20 }, 21 _utf8_decode: function(utftext:string) { 22 let string = '' 23 let i = 0 24 let c = 0 25 let c1 = 0 26 let c2 = 0 27 while (i < utftext.length) { 28 c = utftext.charCodeAt(i) 29 if (c < 128) { 30 string += String.fromCharCode(c) 31 i++ 32 } else if ((c > 191) && (c < 224)) { 33 c1 = utftext.charCodeAt(i + 1) 34 string += String.fromCharCode(((c & 31) << 6) | (c1 & 63)) 35 i += 2 36 } else { 37 c1 = utftext.charCodeAt(i + 1) 38 c2 = utftext.charCodeAt(i + 2) 39 string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63)) 40 i += 3 41 } 42 } 43 return string 44 }, 45 encode: function(input:string) { 46 let output = '' 47 let chr1, chr2, chr3, enc1, enc2, enc3, enc4 48 let i = 0 49 input = this._utf8_encode(input) 50 while (i < input.length) { 51 chr1 = input.charCodeAt(i++) 52 chr2 = input.charCodeAt(i++) 53 chr3 = input.charCodeAt(i++) 54 enc1 = chr1 >> 2 55 enc2 = ((chr1 & 3) << 4) | (chr2 >> 4) 56 enc3 = ((chr2 & 15) << 2) | (chr3 >> 6) 57 enc4 = chr3 & 63 58 if (isNaN(chr2)) { 59 enc3 = enc4 = 64 60 } else if (isNaN(chr3)) { 61 enc4 = 64 62 } 63 output = output + 64 this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + 65 this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4) 66 } 67 return output 68 }, 69 decode: function(input:string) { 70 let output = '' 71 let chr1, chr2, chr3 72 let enc1, enc2, enc3, enc4 73 let i = 0 74 // eslint-disable-next-line no-useless-escape 75 input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '') 76 while (i < input.length) { 77 enc1 = this._keyStr.indexOf(input.charAt(i++)) 78 enc2 = this._keyStr.indexOf(input.charAt(i++)) 79 enc3 = this._keyStr.indexOf(input.charAt(i++)) 80 enc4 = this._keyStr.indexOf(input.charAt(i++)) 81 chr1 = (enc1 << 2) | (enc2 >> 4) 82 chr2 = ((enc2 & 15) << 4) | (enc3 >> 2) 83 chr3 = ((enc3 & 3) << 6) | enc4 84 output = output + String.fromCharCode(chr1) 85 if (enc3 !== 64) { 86 output = output + String.fromCharCode(chr2) 87 } 88 if (enc4 !== 64) { 89 output = output + String.fromCharCode(chr3) 90 } 91 } 92 output = this._utf8_decode(output) 93 return output 94 } 95 } 96 97 const base64 = { 98 encode: Base64.encode.bind(Base64), 99 decode: Base64.decode.bind(Base64) 100 } 101 102 export default base64