我想解码Base64编码的字符串,然后将它存储在我的数据库中。如果输入不是Base64编码的,我需要抛出一个错误。
我如何检查一个字符串是否被Base64编码?
我想解码Base64编码的字符串,然后将它存储在我的数据库中。如果输入不是Base64编码的,我需要抛出一个错误。
我如何检查一个字符串是否被Base64编码?
当前回答
这在Python中是有效的:
import base64
def IsBase64(str):
try:
base64.b64decode(str)
return True
except Exception as e:
return False
if IsBase64("ABC"):
print("ABC is Base64-encoded and its result after decoding is: " + str(base64.b64decode("ABC")).replace("b'", "").replace("'", ""))
else:
print("ABC is NOT Base64-encoded.")
if IsBase64("QUJD"):
print("QUJD is Base64-encoded and its result after decoding is: " + str(base64.b64decode("QUJD")).replace("b'", "").replace("'", ""))
else:
print("QUJD is NOT Base64-encoded.")
IsBase64("string here")如果这里的字符串是base64编码的则返回true,如果这里的字符串不是base64编码的则返回false。
其他回答
尝试使用前面提到的正则表达式:
String regex = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
if("TXkgdGVzdCBzdHJpbmc/".matches(regex)){
System.out.println("it's a Base64");
}
...我们还可以做一个简单的验证,比如,如果它有空格,它就不能是Base64:
String myString = "Hello World";
if(myString.contains(" ")){
System.out.println("Not B64");
}else{
System.out.println("Could be B64 encoded, since it has no spaces");
}
这在Python中是有效的:
def is_base64(string):
if len(string) % 4 == 0 and re.test('^[A-Za-z0-9+\/=]+\Z', string):
return(True)
else:
return(False)
检查字符串的长度是否为4的倍数。然后使用这个正则表达式来确保字符串中的所有字符都是base64字符。
\A[a-zA-Z\d\/+]+={,2}\z
如果您使用的库添加换行符作为遵守每行最多76个字符规则的一种方式,请将它们替换为空字符串。
var base64Rejex = /^(?:[A-Z0-9+\/]{4})*(?:[A-Z0-9+\/]{2}==|[A-Z0-9+\/]{3}=|[A-Z0-9+\/]{4})$/i;
var isBase64Valid = base64Rejex.test(base64Data); // base64Data is the base64 string
if (isBase64Valid) {
// true if base64 formate
console.log('It is base64');
} else {
// false if not in base64 formate
console.log('it is not in base64');
}
您可以使用以下正则表达式来检查字符串是否构成有效的base64编码:
^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$
在base64编码中,字符集为[A-Z, A-Z, 0-9和+ /]。如果其余长度小于4,则字符串用'='字符填充。
^([A-Za-z0-9+/]{4})*表示字符串以0个或多个base64组开头。
([A-Za-z0-9 + /] {4} | [A-Za-z0-9 + /] {3} = | [A-Za-z0-9 + /]{2} = =)意味着美元的字符串以三种形式之一:A-Za-z0-9 + / {4}, {3} = [A-Za-z0-9 + /]或[A-Za-z0-9 + /]{2} = =。