开发者

Something like Tryparse from Convert.FromBase64String

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 cipherTex开发者_如何学Got can be converted without error

byte[] bytes = Convert.FromBase64String(cipherText);


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://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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜