使用RegEx验证字符串是否为base64格式?

时间:2010-07-28 17:03:44

标签: c# regex validation

我一直在寻找如何验证base64字符串并遇到过这个问题。

 ^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$

我需要一些帮助才能允许“==”以及“=”。

由于

2 个答案:

答案 0 :(得分:21)

这应该表现得非常好。

private static readonly HashSet<char> _base64Characters = new HashSet<char>() { 
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 
    'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', 
    '='
};

public static bool IsBase64String(string value)
{
    if (string.IsNullOrEmpty(value))
    {
        return false;
    }
    else if (value.Any(c => !_base64Characters.Contains(c)))
    {
        return false;
    }

    try
    {
        Convert.FromBase64String(value);
        return true;
    }
    catch (FormatException)
    {
        return false;
    }
}

答案 1 :(得分:8)

我已经更新了上面的代码以满足更多要求:

  • 检查字符串大小是否正确(应为4的倍数)
  • 检查填充字符数(字符串末尾最多2个字符
  • 使其在.NET 2.0中运行(嗯,HashSet<T>应该实现或使用Dictionary<T, U>

代码是我的断言库的一部分,所以这就是为什么有两个检查方法和 param 参数......

    private const char Base64Padding = '=';

    private static readonly HashSet<char> Base64Characters = new HashSet<char>()
    { 
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 
        'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 
        'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
    };

    public static void CheckBase64String(string param, string paramName)
    {
        if (CheckBase64StringSafe(param) == false)
        {
            throw (new ArgumentException(String.Format("Parameter '{0}' is not a valid Base64 string.", paramName)));
        }
    }

    public static bool CheckBase64StringSafe(string param)
    {
        if (param == null)
        {
            // null string is not Base64 something
            return false;
        }

        // replace optional CR and LF characters
        param = param.Replace("\r", String.Empty).Replace("\n", String.Empty);

        if (param.Length == 0 ||
            (param.Length % 4) != 0)
        {
            // Base64 string should not be empty
            // Base64 string length should be multiple of 4
            return false;
        }

        // replace pad chacters
        int lengthNoPadding = param.Length;
        int lengthPadding;

        param = param.TrimEnd(Base64Padding);
        lengthPadding = param.Length;

        if ((lengthNoPadding - lengthPadding) > 2)
        {
            // there should be no more than 2 pad characters
            return false;
        }

        foreach (char c in param)
        {
            if (Base64Characters.Contains(c) == false)
            {
                // string contains non-Base64 character
                return false;
            }
        }

        // nothing invalid found
        return true;
    }

我没有广泛测试代码,因此根本没有功能保证!

相关问题