使用 JavaScript 确定字符串是否在 base64 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7860392/
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
Determine if string is in base64 using JavaScript
提问by Jonatan
I'm using the window.atob('string')
function to decode a string from base64 to a string. Now I wonder, is there any way to check that 'string' is actually valid base64? I would like to be notified if the string is not base64 so I can perform a different action.
我正在使用该window.atob('string')
函数将字符串从 base64 解码为字符串。现在我想知道,有什么方法可以检查“字符串”实际上是有效的 base64 吗?如果字符串不是 base64,我想收到通知,以便我可以执行不同的操作。
采纳答案by Dave Newton
If "valid" means "only has base64 chars in it" then check against /[A-Za-z0-9+/=]/
.
如果“有效”意味着“其中只有 base64 字符”,则检查/[A-Za-z0-9+/=]/
.
If "valid" means a "legal" base64-encoded string then you should check for the =
at the end.
如果“有效”表示“合法”的 base64 编码字符串,那么您应该=
在末尾检查。
If "valid" means it's something reasonable after decoding then it requires domain knowledge.
如果“有效”意味着解码后它是合理的,那么它需要领域知识。
回答by pimvdb
If you want to check whether it can be decoded or not, you can simply try decoding it and see whether it failed:
如果你想检查它是否可以解码,你可以简单地尝试解码它,看看它是否失败:
try {
window.atob(str);
} catch(e) {
// something failed
// if you want to be specific and only catch the error which means
// the base 64 was invalid, then check for 'e.code === 5'.
// (because 'DOMException.INVALID_CHARACTER_ERR === 5')
}
回答by Dan Smith
This should do the trick.
这应该可以解决问题。
function isBase64(str) {
if (str ==='' || str.trim() ===''){ return false; }
try {
return btoa(atob(str)) == str;
} catch (err) {
return false;
}
}
回答by Philzen
Building on @atornblad's answer, using the regex to make a simple true/false test for base64 validity is as easy as follows:
基于@atornblad 的回答,使用正则表达式对 base64 有效性进行简单的真/假测试非常简单,如下所示:
var base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
base64regex.test("SomeStringObviouslyNotBase64Encoded..."); // FALSE
base64regex.test("U29tZVN0cmluZ09idmlvdXNseU5vdEJhc2U2NEVuY29kZWQ="); // TRUE
回答by Anders Tornblad
I would use a regular expression for that. Try this one:
我会为此使用正则表达式。试试这个:
/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/
Explanation:
解释:
^ # Start of input
([0-9a-zA-Z+/]{4})* # Groups of 4 valid characters decode
# to 24 bits of data for each group
( # Either ending with:
([0-9a-zA-Z+/]{2}==) # two valid characters followed by ==
| # , or
([0-9a-zA-Z+/]{3}=) # three valid characters followed by =
)? # , or nothing
$ # End of input
回答by purplelizard
This method attempts to decode then encode and compare to the original. Could also be combined with the other answers for environments that throw on parsing errors. Its also possible to have a string that looks like valid base64 from a regex point of view but is not actual base64.
此方法尝试解码然后编码并与原始文件进行比较。也可以与引发解析错误的环境的其他答案结合使用。从正则表达式的角度来看,它也可能有一个看起来像有效的 base64 但不是实际的 base64 的字符串。
if(btoa(atob(str))==str){
//...
}
回答by Lukas Liesis
This is how it's done in one of my favorite validation libs:
这是在我最喜欢的验证库之一中完成的方式:
const notBase64 = /[^A-Z0-9+\/=]/i;
export default function isBase64(str) {
assertString(str); // remove this line and make sure you pass in a string
const len = str.length;
if (!len || len % 4 !== 0 || notBase64.test(str)) {
return false;
}
const firstPaddingChar = str.indexOf('=');
return firstPaddingChar === -1 ||
firstPaddingChar === len - 1 ||
(firstPaddingChar === len - 2 && str[len - 1] === '=');
}
https://github.com/chriso/validator.js/blob/master/src/lib/isBase64.js
https://github.com/chriso/validator.js/blob/master/src/lib/isBase64.js
回答by Kai
As there are mostly two possibilities posted here (regex vs try catch) I did compare the performance of both: https://jsperf.com/base64-check/
由于这里发布的主要有两种可能性(regex vs try catch),我确实比较了两者的性能:https: //jsperf.com/base64-check/
Regex solution seems to be much faster and clear winner. Not sure if the regex catches all cases but for my tests it worked perfectly.
正则表达式解决方案似乎更快更明显。不确定正则表达式是否能捕获所有情况,但对于我的测试,它运行良好。
Thanks to @Philzen for the regex!
感谢@Philzen 的正则表达式!
p.s.
ps
In case someone is interested in finding the fastest way to safely decode a base64 string (that's how I came here): https://jsperf.com/base64-decoding-check
如果有人有兴趣找到安全解码 base64 字符串的最快方法(这就是我来到这里的方式):https: //jsperf.com/base64-decoding-check