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);
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.
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.
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 .
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.
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With