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

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


当前回答

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个字符的倍数 检查每个字符都在A-Z, A-Z, 0-9, +, /集合中,除了末尾的填充为0,1或2 '='字符

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

从Java 8开始,您可以简单地使用Java .util。Base64尝试解码字符串:

String someString = "...";
Base64.Decoder decoder = Base64.getDecoder();

try {
    decoder.decode(someString);
} catch(IllegalArgumentException iae) {
    // That string wasn't valid.
}
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');
}

如果解码时我们得到一个包含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