1

Actually, I want to receive base64 in API but I want to allow base64 which contain only Audio following is the function by which I validate base64 but before Convert.FromBase64String(base64String); I want to validate that this base64 is audio.

public static int CheckAudio(string base64String)
        {

            if (string.IsNullOrEmpty(base64String) || base64String.Length % 4 != 0
               || base64String.Contains(" ") || base64String.Contains("\t") || base64String.Contains("\r") || base64String.Contains("\n"))
                return (int)ConfezzStatusCode.InValidParamter;

            try
            {
                 Convert.FromBase64String(base64String);
                    return (int)HttpStatusCode.OK;
            }
            catch
            {
                // Handle the exception
                return (int)ConfezzStatusCode.InValidParamter;
            }
        }

Note: I want to allow only Audio files.

Wajid khan
  • 657
  • 6
  • 18

1 Answers1

0

You can use file signatures to detect if it is a known audio format. Something like this:

// Decode the whole string to make sure it is a valid Base64
byte[] data = Convert.FromBase64String(base64String);

// Just for readability store it as HEX
// You might want to store only the file header (eg, 64 bytes)
string hex = BitConverter.ToString(data);

if (hex.StartsWith("49-44-33"))
{
  Console.WriteLine("mp3");
}
else if (hex.StartsWith("66-4C-61-43"))
{
  Console.WriteLine("flac");
}
else {
  Console.WriteLine("unknown:" + hex);
}

For more thoughts check:

Victor
  • 4,652
  • 1
  • 22
  • 27