js-base64-extend
Version:
基于base64上扩展,增加设置key,支持node和浏览器端
58 lines (48 loc) • 1.6 kB
JavaScript
// https://www.npmjs.com/package/js-base64
import base64 from 'js-base64';
var __key = '69/2+34=85710',
__key2 = 'qwertySDXCVBNuiopajFGHJKLZklzxcvbnmQWERTYsdfghUIOPAM',
__key3 = __key + __key2,
randomText = function (min, max) {
var str = '',
arr = __key2['split'](''),
pos;
min = Math.round(Math.random() * (max - min)) + min;
for (let i = 0; i < min; i++) {
pos = Math.round(Math.random() * (arr.length - 1));
str += arr[pos];
}
return str;
};
export default {
setCharsKey(k) {
__key3 = k + __key3;
},
encode: function (string) {
string = base64.Base64.encode(string).split('');
var newBase64 = [];
string.forEach(function (item) {
var index = __key3.indexOf(item);
if (index > -1) {
newBase64.push(index);
} else {
newBase64.push(item);
}
});
return randomText(1, 10) + newBase64.join('_').replace(/_/g, function () {
return randomText(1, 5);
}) + randomText(1, 10);
},
decode: function (string) {
string = string.replace(/[A-z]+/g, '_')['split']('_');
var newString = [];
string.forEach(function (item) {
if (typeof parseInt(item) === 'number' && !isNaN(parseInt(item))) {
newString.push(__key3[parseInt(item)]);
} else {
newString.push(item);
}
});
return base64.Base64.decode(newString.join(''));
}
};