How to check for a valid Base64 encoded string

How to check for a valid Base64 encoded string

回答1

Use Convert.TryFromBase64String from C# 7.2

public static bool IsBase64String(string base64)
{
   Span<byte> buffer = new Span<byte>(new byte[base64.Length]);
   return Convert.TryFromBase64String(base64, buffer , out int bytesParsed);
}
 
Works only in .NET Core 2.1+ or .NET Standard 2.1+
– Cyrus
May 8 '19 at 9:21

回答2

Update: For newer versions of C#, there's a much better alternative, please refer to the answer by Tomas below.


It's pretty easy to recognize a Base64 string, as it will only be composed of characters 'A'..'Z', 'a'..'z', '0'..'9', '+', '/' and it is often padded at the end with up to three '=', to make the length a multiple of 4. But instead of comparing these, you'd be better off ignoring the exception, if it occurs.

回答3

I know you said you didn't want to catch an exception. But, because catching an exception is more reliable, I will go ahead and post this answer.

public static bool IsBase64(this string base64String) {
     // Credit: oybek https://stackoverflow.com/users/794764/oybek
     if (string.IsNullOrEmpty(base64String) || base64String.Length % 4 != 0
        || base64String.Contains(" ") || base64String.Contains("\t") || base64String.Contains("\r") || base64String.Contains("\n"))
        return false;

     try{
         Convert.FromBase64String(base64String);
         return true;
     }
     catch(Exception exception){
     // Handle the exception
     }
     return false;
}

Update: I've updated the condition thanks to oybek to further improve reliability.

回答4

I believe the regex should be:

    Regex.IsMatch(s, @"^[a-zA-Z0-9\+/]*={0,2}$")

Only matching one or two trailing '=' signs, not three.

s should be the string that will be checked. Regex is part of the System.Text.RegularExpressions namespace.

原文地址:https://www.cnblogs.com/chucklu/p/15573205.html