Base64URL decoding via JavaScript?

自作多情 提交于 2019-12-05 01:29:52

use this befor decoding :

decode = function(input) {
        // Replace non-url compatible chars with base64 standard chars
        input = input
            .replace(/-/g, '+')
            .replace(/_/g, '/');

        // Pad out with standard base64 required padding characters
        var pad = input.length % 4;
        if(pad) {
          if(pad === 1) {
            throw new Error('InvalidLengthError: Input base64url string is the wrong length to determine padding');
          }
          input += new Array(5-pad).join('=');
        }

        return input;
    }

after use this function you can use any base64 decoder

Solution:

var b64str = base64.encode('foo bar');

// fix padding according to the new format
b64str = b64str.padRight(b64str.length + (4 - b64str.length % 4) % 4, '=');

Using this great base64 encode/decode: http://code.google.com/p/stringencoders/source/browse/trunk/javascript/base64.js

Also depends on the padRight method:

String.prototype.padRight = function(n, pad){
    t = this;
    if(n > this.length)
        for(i = 0; i < n-this.length; i++)
            t += pad;
    return t;
}
The Mask
var str = "string";
var encoded = btoa(str); // encode a string (base64)
var decoded = atob(encoded); //decode the string 
alert( ["string base64 encoded:",encoded,"\r\n", "string base64 decoded:",decoded].join('') );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!