简体   繁体   中英

Validate string as Proper Base64String and Convert to byte[]

I want to validate if an input string is valid Base64 or not. If it's valid then convert into byte[].

I tried the following solutions

  1. RegEx
  2. MemoryStream
  3. Convert.FromBase64String

For example I want to validate if "932rnqia38y2" is a valid Base64 string or not and then convert it to byte[] . This string is not valid Base64 but I'm always getting true or valid in my code.

please let me know if you have any solutions.

Code

//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;
    }
}

Just create some helper, which will catch FormatException on input string:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM