检查字符串是普通字符串还是 Base64 字符串问题



以下方法,我正在使用来验证 Base64

Public Function ValidateBase64String(ByVal sString As String) As Boolean     
If (sString.Length <> 4) Then
Dim b As Byte() = Convert.FromBase64String(sString)
Return True
Else
Return False
End If
End Function

我将"johnjohn"作为字符串传递给该方法,并返回以下字符串是 base64 字符串。它不返回 false 而不是返回 true 的原因是什么?

以下方法几乎每次都有效

Console.WriteLine(ValidateBase64String("johnjohn"))-> it will always returns false
Public Function ValidateBase64String(ByVal value As string) As Boolean
Try
If value.Length <> 4 AndAlso (Base64Decode(value) IsNot Nothing AndAlso System.Text.RegularExpressions.Regex.IsMatch(Base64Decode(value), "^[a-zA-Z0-9+/]*={0,3}$")) Then
Return True
End If
Catch ex As Exception            
End Try
Return False
End Function
Public Function Base64Decode(ByVal base64EncodedData As String) As String
Try
Dim base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData)
Return System.Text.Encoding.UTF8.GetString(base64EncodedBytes)
Catch ex As Exception            
End Try
Return Nothing
End Function

最新更新