2011-10-07 51 views
8

是否有任何tryparse为Convert.FromBase64String 或我们只是计数字符,如果它是等于64个字符或不。类似Tryparse从Convert.FromBase64String

我复制一个加密和解密类,但在下面的行上有一个错误。我要检查是否cipherText可以没有错误

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

Base64不代表64个字符。这意味着每个字符可以表示0到63之间的数字。十进制是Base10允许字符0-9,二进制是Base2(允许0或1),十六进制是Base16(允许0-9和A-F表示0到15之间的值) –

+0

你能进一步解释吗?有To&FromBase64String,它只是将字符串转换为另一个带有64个基本字符集的字符串。这不是一个真正的解析......你只是想尝试一下吗? – bryanmac

+0

那么我用什么来检查输入的字符串是否处于正确的FromBase64String格式,并且当我使用Convert.FromBase64String时不会出现错误 –

回答

13

很好地转换,你可以先检查字符串。它必须有正确数量的字符,用(str.Length * 6)%8 == 0进行验证。并且您可以检查每个字符,它必须位于AZ,az,0-9,+,/和= 。该字符只能出现在最后。

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

+2

不要某些版本的base64有伪造的尾部'='?理解这个例外的另一个原因。 –

3
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); 
}