Example analysis of JavaScript implementation of encode64 encryption algorithm
- 2020-05-30 19:21:17
- OfStack
The example of this article describes the encode64 encryption algorithm implemented by JavaScript. Share with you for your reference. The details are as follows:
This JavaScript code can implement the encode64 encryption algorithm, the speed is quite good.
//encode64 codec
(function() {
var codeChar = "PaAwO65goUf7IK2vi9-xq8cFTEXLCDY1Hd3tV0ryzjbpN_BlnSs4mGRkQWMZJeuh";
window.encode64 = function(str) {
var s = "";
var a = strToBytes(str);
// Gets the byte array of a string , The array length is the string length 2 times .
var res = a.length % 3;
//3 bytes 1 Group processing , Remaining special treatment
var i = 2, v;
for (; i < a.length; i += 3) {
// every 3 Bytes in 4 Character representation ,
// The equivalent of 3 A character ( Is, in fact, 6 bytes ) with 8 Character encoding ( For the actual 16 bytes )
// It looks like the capacity has expanded a lot , But with compression enabled , These cancel out again
v = a[i - 2] + (a[i - 1] << 8) + (a[i] << 16);
s += codeChar.charAt(v & 0x3f);
s += codeChar.charAt((v >> 6) & 0x3f);
s += codeChar.charAt((v >> 12) & 0x3f);
s += codeChar.charAt((v >> 18));
}
if (res == 1) {// The word "savings" 1 When a , fill 2 A character , 64*64>256
v = a[i - 2];
s += codeChar.charAt(v & 0x3f);
s += codeChar.charAt((v >> 6) & 0x3f);
} else if (res == 2) {
// The word "savings" 2 When a , fill 3 bytes , 64*64*64>256*256, So it works
v = a[i - 2] + (a[i - 1] << 8);
s += codeChar.charAt(v & 0x3f);
s += codeChar.charAt((v >> 6) & 0x3f);
s += codeChar.charAt((v >> 12) & 0x3f);
}
return s;
};
window.decode64 = function(codeStr) {
var dic = [];
for (var i = 0; i < codeChar.length; i++) {
dic[codeChar.charAt(i)] = i;
}
var code = [];
var res = codeStr.length % 4;
var i = 3, v;
for (; i < codeStr.length; i += 4) {
v = dic[codeStr.charAt(i - 3)];
v += dic[codeStr.charAt(i - 2)] << 6;
v += dic[codeStr.charAt(i - 1)] << 12;
v += dic[codeStr.charAt(i)] << 18;
code.push(v & 0xff, (v >> 8) & 0xff, (v >> 16) & 0xff);
}
if (res == 2) {
// The correct number of bytes must be redundant 2 or 3, There is no 1 In the case , If there is a , Give up .
v = dic[codeStr.charAt(i - 3)];
v += dic[codeStr.charAt(i - 2)] << 6;
code.push(v & 0xff);
} else if (res == 3) {
v = dic[codeStr.charAt(i - 3)];
v += dic[codeStr.charAt(i - 2)] << 6;
v += dic[codeStr.charAt(i - 1)] << 12;
code.push(v & 0xff, (v >> 8) & 0xff);
}
return strFromBytes(code);
};
})();
I hope this article has been helpful to your javascript programming.