15

Is there any tryparse for Convert.FromBase64String or we just count the character if it is equal 64 character or not.

I copy a encryption and decryption class, but there is an error on the following line. I want to check whether or not the cipherText can be converted without error

byte[] bytes = Convert.FromBase64String(cipherText);
AGB
  • 2,230
  • 1
  • 14
  • 21
Sarawut Positwinyu
  • 4,974
  • 15
  • 54
  • 80
  • 3
    Base64 doesn't mean 64 characters. It means that each character can represent a number between 0 and 63. e.g. Decimal is Base10 allows chars 0-9, Binary is Base2 (allows 0 or 1) and Hex is Base16 (allows 0-9 and A-F to represent values between 0 and 15) – Bob Vale Oct 07 '11 at 11:28
  • Can you explain further? There's To & FromBase64String and it simply converts the string to another string with a 64 base char set. It's not really a parse ... Do you just want a Try catch around it? – bryanmac Oct 07 '11 at 11:31
  • So what is i use to check if the input string is in a correct FromBase64String format and don't make error when i use Convert.FromBase64String – Sarawut Positwinyu Oct 07 '11 at 11:31
  • I have added more explanation and code. i might use try catch if there is no other way. – Sarawut Positwinyu Oct 07 '11 at 11:35

3 Answers3

21

Well, you could check the string first. It must have the right number of characters, verify with (str.Length * 6) % 8 == 0. And you can check every character, it must be in the set A-Z, a-z, 0-9, +, / and =. The = character can only appear at the end.

This is expensive, it is actually cheaper to just catch the exception. The reason .NET doesn't have a TryXxx() version.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
5
public static class Base64Helper
{
    public static byte[] TryParse(string s)
    {
        if (s == null) throw new ArgumentNullException("s");

        if ((s.Length % 4 == 0) && _rx.IsMatch(s))
        {
            try
            {
                return Convert.FromBase64String(s);
            }
            catch (FormatException)
            {
                // ignore
            }
        }
        return null;
    }

    private static readonly Regex _rx = new Regex(
        @"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=|[A-Za-z0-9+/][AQgw]==)?$",
        RegexOptions.Compiled);
}
LukeH
  • 263,068
  • 57
  • 365
  • 409
1

As part of the .NET standard 2.1 this now exists: Convert.TryFromBase64String

see https://learn.microsoft.com/en-us/dotnet/api/system.convert.tryfrombase64string?view=net-6.0

See this answer as well: How to check for a valid Base64 encoded string

AndyD
  • 5,252
  • 35
  • 32