Base64编码和解码实现

时间:2023-03-09 05:46:54
Base64编码和解码实现
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 = ;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> ;
enc2 = ((chr1 & ) << ) | (chr2 >> );
enc3 = ((chr2 & ) << ) | (chr3 >> );
enc4 = chr3 & ;
if (isNaN(chr2)) {
enc3 = enc4 = ;
} else if (isNaN(chr3)) {
enc4 = ;
}
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 = ;
input = input.replace(/[^A-Za-z0-\+\/\=]/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 << ) | (enc2 >> );
chr2 = ((enc2 & ) << ) | (enc3 >> );
chr3 = ((enc3 & ) << ) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != ) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != ) {
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 = ; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < ) {
utftext += String.fromCharCode(c);
} else if ((c > ) && (c < )) {
utftext += String.fromCharCode((c >> ) | );
utftext += String.fromCharCode((c & ) | );
} else {
utftext += String.fromCharCode((c >> ) | );
utftext += String.fromCharCode(((c >> ) & ) | );
utftext += String.fromCharCode((c & ) | );
}
}
return utftext;
};
// private method for UTF-8 decoding
_utf8_decode = function (utftext) {
var string = "";
var i = ;
var c = c1 = c2 = ;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < ) {
string += String.fromCharCode(c);
i++;
} else if ((c > ) && (c < )) {
c2 = utftext.charCodeAt(i + );
string += String.fromCharCode(((c & ) << ) | (c2 & ));
i += ;
} else {
c2 = utftext.charCodeAt(i + );
c3 = utftext.charCodeAt(i + );
string += String.fromCharCode(((c & ) << ) | ((c2 & ) << ) | (c3 & ));
i += ;
}
}
return string;
}
} //调用和示例显示
var base = new Base64();
var str = document.getElementById("p1").innerHTML;
str = base.decode(str); //解码
document.getElementById("p1").innerHTML = str;