Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Something like Tryparse from Convert.FromBase64String

Tags:

.net

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);
like image 539
Sarawut Positwinyu Avatar asked Oct 07 '11 11:10

Sarawut Positwinyu


People also ask

What is base64url?

base64url.com Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding. Each base64 digit represents exactly 6 bits of data.

How do you convert a string to Base64?

To convert a string into a Base64 character the following steps should be followed: Get the ASCII value of each character in the string. Compute the 8-bit binary equivalent of the ASCII values. Convert the 8-bit characters chunk into chunks of 6 bits by re-grouping the digits.

What are valid Base64 characters?

Base64 only contains A–Z , a–z , 0–9 , + , / and = . So the list of characters not to be used is: all possible characters minus the ones mentioned above. For special purposes .


3 Answers

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.

like image 99
Hans Passant Avatar answered Oct 20 '22 21:10

Hans Passant


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);
}
like image 22
LukeH Avatar answered Oct 20 '22 22:10

LukeH


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

see https://docs.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

like image 30
AndyD Avatar answered Oct 20 '22 21:10

AndyD