验证字符串为Proper Base64String并转换为byte []

时间:2016-08-08 10:42:45

标签: c# asp.net .net asp.net-mvc asp.net-mvc-4

我想验证输入字符串是否有效Base64。如果它有效则转换为byte []。

我尝试了以下解决方案

  1. RegEx
  2. MemoryStream
  3. Convert.FromBase64String
  4. 例如,我想验证"932rnqia38y2"是否是有效的Base64字符串,然后将其转换为byte[]。这个字符串不是有效的Base64,但我总是在我的代码中变为真或有效。

    如果您有任何解决方案,请告诉我。

    代码

    //Regex _rx = new Regex(@"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=|[A-Za-z0-9+/][AQgw]==)?$", RegexOptions.Compiled);
    
    Regex _rx = new Regex(@"^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$", RegexOptions.Compiled);
    if (image == null) return null;
    
    if ((image.Length % 4 == 0) && _rx.IsMatch(image))
    {
        try
        {
            //MemoryStream stream = new MemoryStream(Convert.FromBase64String(image));
            return Convert.FromBase64String(image);
        }
        catch (FormatException)
        {
            return null;
        }
    }
    

1 个答案:

答案 0 :(得分:2)

只需创建一些帮助器,它将在输入字符串上捕获FormatException:

    public static bool TryGetFromBase64String(string input, out byte[] output)
    {
        output = null;
        try
        {
            output = Convert.FromBase64String(input);
            return true;
        }
        catch (FormatException)
        {
            return false;
        }
    }