我想解码Base64编码的字符串,然后将它存储在我的数据库中。如果输入不是Base64编码的,我需要抛出一个错误。

我如何检查一个字符串是否被Base64编码?


当前回答

如果解码时我们得到一个包含ASCII字符的字符串,则字符串为 不编码

(RoR) ruby解决方案:

def encoded?(str)
  Base64.decode64(str.downcase).scan(/[^[:ascii:]]/).count.zero?
end

def decoded?(str)
  Base64.decode64(str.downcase).scan(/[^[:ascii:]]/).count > 0
end

其他回答

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

试试这个:

public void checkForEncode(String string) {
    String pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
    Pattern r = Pattern.compile(pattern);
    Matcher m = r.matcher(string);
    if (m.find()) {
        System.out.println("true");
    } else {
        System.out.println("false");
    }
}

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?

你可以:

检查长度是否为4个字符的倍数 检查每个字符都在A-Z, A-Z, 0-9, +, /集合中,除了末尾的填充为0,1或2 '='字符

如果你期望它是base64,那么你可以使用平台上可用的任何库来尝试将它解码为字节数组,如果它不是有效的base64则抛出异常。当然,这取决于你的平台。