类似于Convert.FromBase64String的Tryparse

Sar*_*nyu 11 .net

是否有任何tryparse Convert.FromBase64String 或我们只计算字符是否等于64个字符.

我复制加密和解密类,但以下行有错误.我想检查是否cipherText可以无错误地转换

byte[] bytes = Convert.FromBase64String(cipherText);
Run Code Online (Sandbox Code Playgroud)

Han*_*ant 14

好吧,你可以先检查字符串.它必须具有正确的字符数,用(str.Length*6)%8 == 0验证.并且你可以检查每个字符,它必须在集合AZ,az,0-9,+,/和= .=字符只能出现在最后.

这是昂贵的,实际上捕获异常实际上更便宜..NET没有TryXxx()版本的原因.

  • 某些版本的base64是否有虚假的尾随`=`?捕捉异常的另一个原因. (2认同)

Luk*_*keH 6

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);
}
Run Code Online (Sandbox Code Playgroud)