base64加密解密

发布时间 2023-04-27 10:31:56作者: 要跑啊
// base64加密解密 不支持中文哦,会有问题
var Base64 = {
    //加密
    encode : function(str) {
        return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
            function toSolidBytes(match, p1) {
                return String.fromCharCode('0x' + p1);
            }));
    },
    //解密
    decode : function(str) {
        // Going backwards: from bytestream, to percent-encoding, to original string.
        var res;
        var a, b
        //  atob(str)在ie 浏览器中会抛出异常
        try { a = atob(str)
        } catch (e) { a = '';}
       
        b = a.split('')
        res = b.filter(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        })
//处理 百分号%
        return decodeURIComponent(res.join('').replace(/%/g, '%25'));
    }
}