通过JavaScript解码Base64URL?

chr*_*man 10 javascript url base64 decoding

所以我很难过.我知道有很多用于JS的Base64编码器/解码器,但不适用于修改过的(和Facebook赞成的)Base64URL变体.到目前为止,搜索stackoverflow已经变得干涸.

是的,我可以使用PHP或其他服务器端库对此进行解码,但我试图保持这种通用性,无论我使用什么平台...例如,如果我要托管一个仅限HTML的Facebook应用程序在Amazon S3/CloudFront上,只使用他们的JS SDK和jQuery来处理表单和获取数据.

也就是说,有没有人知道任何针对JavaScript的Base64URL特定解码器?

提前致谢!

moh*_*mad 17

在解码之前使用它:

var 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;
    }
Run Code Online (Sandbox Code Playgroud)

使用此功能后,您可以使用任何base64解码器


The*_*ask -9

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('') );
Run Code Online (Sandbox Code Playgroud)

  • 这使用普通的、非 url 安全的映射字符。请参阅 RFC 4648 §5 (https://en.wikipedia.org/wiki/Base64) (6认同)