我想解码Base64编码的字符串,然后将它存储在我的数据库中。如果输入不是Base64编码的,我需要抛出一个错误。
我如何检查一个字符串是否被Base64编码?
我想解码Base64编码的字符串,然后将它存储在我的数据库中。如果输入不是Base64编码的,我需要抛出一个错误。
我如何检查一个字符串是否被Base64编码?
当前回答
你可以:
检查长度是否为4个字符的倍数 检查每个字符都在A-Z, A-Z, 0-9, +, /集合中,除了末尾的填充为0,1或2 '='字符
如果你期望它是base64,那么你可以使用平台上可用的任何库来尝试将它解码为字节数组,如果它不是有效的base64则抛出异常。当然,这取决于你的平台。
其他回答
如果你正在使用Java,你实际上可以使用common -codec库
import org.apache.commons.codec.binary.Base64;
String stringToBeChecked = "...";
boolean isBase64 = Base64.isArrayByteBase64(stringToBeChecked.getBytes());
[更新1]弃用通知 而不是使用
Base64.isBase64(价值);
/**
* Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
* method treats whitespace as valid.
*
* @param arrayOctet
* byte array to test
* @return {@code true} if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
* {@code false}, otherwise
* @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0.
*/
@Deprecated
public static boolean isArrayByteBase64(final byte[] arrayOctet) {
return isBase64(arrayOctet);
}
尝试使用前面提到的正则表达式:
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");
}
Base64有许多变体,所以考虑只确定您的字符串是否类似于您期望处理的变体。因此,您可能需要根据索引和填充字符(即+,/,=)调整下面的正则表达式。
class String
def resembles_base64?
self.length % 4 == 0 && self =~ /^[A-Za-z0-9+\/=]+\Z/
end
end
用法:
raise 'the string does not resemble Base64' unless my_string.resembles_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。
对于Flutter,我测试了上面的几个注释,并将其转换为dart函数,如下所示
static bool isBase64(dynamic value) {
if (value.runtimeType == String){
final RegExp rx = RegExp(r'^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$',
multiLine: true,
unicode: true,
);
final bool isBase64Valid = rx.hasMatch(value);
if (isBase64Valid == true) {return true;}
else {return false;}
}
else {return false;}
}