我正在使用window.atob('string')
函数将一个字符串从Base64解码为普通字符串。现在,我想知道是否有任何方法可以检查'string'是否为有效的Base64格式。如果该字符串不是Base64格式,我希望得到通知,以便我可以执行其他操作。
我正在使用window.atob('string')
函数将一个字符串从Base64解码为普通字符串。现在,我想知道是否有任何方法可以检查'string'是否为有效的Base64格式。如果该字符串不是Base64格式,我希望得到通知,以便我可以执行其他操作。
在@anders-marzi-tornblad的答案的基础上,使用正则表达式来进行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
window.btoa("\u009a)Ý\u0099ªl")
- Philzenatob
不是一个好的选项来测试一个字符串是否为 base64 编码,因为它太宽松了。它允许没有必需的 =
或 ==
填充的 base64 编码字符串。Base64 编码字符串应该具有 4 的倍数长度。 - Anders Marzi Tornbladfuel
是一个完全有效的编码后的base64字符串,解码为~ç¥
。我怀疑您正在寻找一种函数,用于判断您是否在查看编码或纯粹的负载...但这样一个(非基于人工智能且完全确定性的)函数不存在,尽管我很乐意被证明错误。不过,这超出了本主题的范围,因为楼主明确要求一种方法来判断字符串是否包含有效的base64,而根据RFC4648,fuel
就是有效的base64字符。 - Philzen如果你想检查它是否可以被解码,你可以尝试解码并查看是否失败:
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')
}
这应该可以解决问题。
function isBase64(str) {
if (str ==='' || str.trim() ===''){ return false; }
try {
return btoa(atob(str)) == str;
} catch (err) {
return false;
}
}
test
不是有效的Base64编码? - Anders Marzi Tornblad/[A-Za-z0-9+/=]/
。=
。=
填充并不总是存在。 - Charlie我会使用正则表达式来实现。尝试使用此表达式:
/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/
解释:
^ # 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
SomeStringObviouslyNotBase64Encoded
测试为假,尽管它是有效的base64编码: atob("SomeStringObviouslyNotBase64Encoded")
返回 JJÚâ¾*.²\¢ÐZ±î¸w(uç
。有可能改进这个正则表达式使其100%准确吗? - undefinedwindow.atob
可以接受不完全正确的字符串。你的例子恰好有35个字符,并且应该用一个等号进行填充。引用自维基百科的一句话:“当未编码输入长度不是三的倍数时,必须添加填充以使编码输出长度成为四的倍数。” - Anders Marzi Tornblad这种方法尝试解码再编码,并与原始内容进行比较。在可能抛出解析错误的环境中,也可以与其他答案相结合使用。但是,有时候一个字符串在正则表达式上看起来像是有效的base64格式,但实际上并不是。
if(btoa(atob(str))==str){
//...
}
str
不是有效的base64,atob(str)
将抛出未捕获的错误。使用try..catch语句似乎更好。 - undefined这里是示例代码:
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
=
。 - Lukas Liesis
const validateBase64 = function(encoded1) {
var decoded1 = Buffer.from(encoded1, 'base64').toString('utf8');
var encoded2 = Buffer.from(decoded1, 'binary').toString('base64');
return encoded1 == encoded2;
}
对我而言,如果一个字符串满足以下条件,则很可能是编码为base64:
A-Z
a-z
0-9
+/=
=
(0-2个字符)因此代码应该是:
function isBase64(str)
{
return str.length % 4 == 0 && /^[A-Za-z0-9+/]+[=]{0,2}$/.test(str);
}
atob
和btoa
以及推荐的Buffer.from("...", "base64")
据我所知不需要使用=
进行填充。我看到许多项目因为各种原因而删除了填充=
字符,但是这样的字符串仍然可以在JS中进行base64解码而不会抛出错误。您的答案针对问题的要点,我在此留下任何想要检查字符串是否可以解码而不是检查它是否与实际RFC定义匹配的用户。 - undefinedvar base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
base64regex.test(value)
function (value) {
var base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
if (base64regex.test(value) && isNaN(value) && !/^[a-zA-Z]+$/.test(value)) {
return decodeURIComponent(escape(window.atob(value)));
}