我想解码Base64编码的字符串,然后将它存储在我的数据库中。如果输入不是Base64编码的,我需要抛出一个错误。
我如何检查一个字符串是否被Base64编码?
我想解码Base64编码的字符串,然后将它存储在我的数据库中。如果输入不是Base64编码的,我需要抛出一个错误。
我如何检查一个字符串是否被Base64编码?
当前回答
当你知道原始内容的长度(例如校验和)时,这个片段可能会很有用。它检查编码的表单是否具有正确的长度。
public static boolean isValidBase64( final int initialLength, final String string ) {
final int padding ;
final String regexEnd ;
switch( ( initialLength ) % 3 ) {
case 1 :
padding = 2 ;
regexEnd = "==" ;
break ;
case 2 :
padding = 1 ;
regexEnd = "=" ;
break ;
default :
padding = 0 ;
regexEnd = "" ;
}
final int encodedLength = ( ( ( initialLength / 3 ) + ( padding > 0 ? 1 : 0 ) ) * 4 ) ;
final String regex = "[a-zA-Z0-9/\\+]{" + ( encodedLength - padding ) + "}" + regexEnd ;
return Pattern.compile( regex ).matcher( string ).matches() ;
}
其他回答
我试着用这个,是的,这个有用
^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$
但我添加了一个条件,检查至少字符的结尾是=
string.lastIndexOf("=") >= 0
PHP5试试这样做
//where $json is some data that can be base64 encoded
$json=some_data;
//this will check whether data is base64 encoded or not
if (base64_decode($json, true) == true)
{
echo "base64 encoded";
}
else
{
echo "not base64 encoded";
}
在PHP7中使用这个
//$string parameter can be base64 encoded or not
function is_base64_encoded($string){
//this will check if $string is base64 encoded and return true, if it is.
if (base64_decode($string, true) !== false){
return true;
}else{
return false;
}
}
Function Check_If_Base64(ByVal msgFile As String) As Boolean
Dim I As Long
Dim Buffer As String
Dim Car As String
Check_If_Base64 = True
Buffer = Leggi_File(msgFile)
Buffer = Replace(Buffer, vbCrLf, "")
For I = 1 To Len(Buffer)
Car = Mid(Buffer, I, 1)
If (Car < "A" Or Car > "Z") _
And (Car < "a" Or Car > "z") _
And (Car < "0" Or Car > "9") _
And (Car <> "+" And Car <> "/" And Car <> "=") Then
Check_If_Base64 = False
Exit For
End If
Next I
End Function
Function Leggi_File(PathAndFileName As String) As String
Dim FF As Integer
FF = FreeFile()
Open PathAndFileName For Binary As #FF
Leggi_File = Input(LOF(FF), #FF)
Close #FF
End Function
检查字符串的长度是否为4的倍数。然后使用这个正则表达式来确保字符串中的所有字符都是base64字符。
\A[a-zA-Z\d\/+]+={,2}\z
如果您使用的库添加换行符作为遵守每行最多76个字符规则的一种方式,请将它们替换为空字符串。
如果RegEx不起作用,而您知道原始字符串的格式风格,则可以通过对该格式进行RegEx来反转逻辑。
例如,我使用base64编码的xml文件,只检查文件是否包含有效的xml标记。如果没有,我可以假设它是base64解码的。这不是很动态,但对于我的小应用程序来说很好。