通过 JavaScript 进行 Base64URL 解码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5234581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:17:07  来源:igfitidea点击:

Base64URL decoding via JavaScript?

javascripturlbase64decoding

提问by chrisfullman

So I'm stumped. I know there's lots of Base64 encoders/decoders for JS, but not for the modified (and Facebook-favored) Base64URL variation. So far searching across stackoverflow has come up dry.

所以我很难过。我知道有很多用于 JS 的 Base64 编码器/解码器,但不适用于修改后的(和 Facebook 支持的)Base64URL 变体。到目前为止,在 stackoverflow 上搜索已经枯竭。

Yes, I could use PHP or another server-side library to decode this, but I'm trying to keep this universal regardless of what platform I'm using... for example, if I were to host a HTML-only Facebook app on Amazon S3/CloudFront and only use their JS SDK and jQuery to take care of processing forms and getting data.

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

That said, does anyone know of any Base64URL-specific decoders for JavaScript?

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

Thanks in advance!

提前致谢!

回答by mohamad

Use this before decoding :

在解码之前使用它:

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;
    }

After using this function you can use any base64 decoder

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

回答by Simeon

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

使用这个很棒的 base64 编码/解码:http: //code.google.com/p/stringencoders/source/browse/trunk/javascript/base64.js

Also depends on the padRight method:

还取决于 padRight 方法:

String.prototype.padRight = function(n, pad){
    t = this;
    if(n > this.length)
        for(i = 0; i < n-this.length; i++)
            t += pad;
    return t;
}

回答by 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('') );