JS实现 PHP 函数 (base64加解密)

//base64加密

function base64_encode(e){

    var r=function(e){

        return encodeURIComponent(e).replace(/%([0-9A-F]{2})/g,function(e,r){return String.fromCharCode("0x"+r)})};

    if("undefined"==typeof window)return new Buffer(e).toString("base64");

    if(void 0!==window.btoa)return window.btoa(r(e));

    var n,t,o,i,a,c,d,f,h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u=0,w=0,A="",l=[];

    if(!e)return e;e=r(e);

    do{n=e.charCodeAt(u++),t=e.charCodeAt(u++),o=e.charCodeAt(u++),f=n<<16|t<<8|o,i=f>>18&63,a=f>>12&63,c=f>>6&63,d=63&f,l[w++]=h.charAt(i)+h.charAt(a)+h.charAt(c)+h.charAt(d)}

    while(u<e.length);A=l.join("");var C=e.length%3;return(C?A.slice(0,C-3):A)+"===".slice(C||3)

}

//base64解密

function base64_decode(n){

    var r=function(n){

        return decodeURIComponent(n.split("").map(function(n)

        {

            return"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)}).join(""))

    };

    if("undefined"==typeof window)return new Buffer(n,"base64").toString("utf-8");

    if(void 0!==window.atob)return r(window.atob(n));

    var e,t,o,i,d,f,a,c,u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",h=0,w=0,C="",g=[];

    if(!n)return n;n+="";

    do{

        i=u.indexOf(n.charAt(h++)),d=u.indexOf(n.charAt(h++)),f=u.indexOf(n.charAt(h++)),a=u.indexOf(n.charAt(h++)),c=i<<18|d<<12|f<<6|a,e=c>>16&255,t=c>>8&255,o=255&c,g[w++]=64===f?String.fromCharCode(e):64===a?String.fromCharCode(e,t):String.fromCharCode(e,t,o)

    }while(h<n.length);

    return C=g.join(""),r(C.replace(/\0+$/,""))

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值