2

I have a task of base64 decoder. As you know base64 does not contain any inforamation about source file name, but first 5 symbols do contain information about file type. I already have a function that returns type from base64 string. Here it is.

    string GetFileTypeByBase64(string base64)
    {
        var data = base64.Substring(0, 5);
        switch (data.ToUpper())
        {
            case "IVBOR":
                return ".png";
            case "/9J/4":
                return ".jpg";
            case "AAAAI":
                return ".mp4";
            case "JVBER":
                return ".pdf";
            case "AAABA":
                return ".ico";
            case "UMFYI":
                return ".rar";
            case "E1XYD":
                return ".rtf";
            case "U1PKC":
                return ".txt";
            case "MQOWM":
            case "77U/M":
                return ".srt";
            default:
                return "." + data;
        }
    }

And here is my question : How do I know the file I have in base64 string is mp3 or wav? (Will also be grateful if you provide other file type sign)

  • 1
    *but first 5 symbols do contain information about file type* - that's only half true. In fact, base64 does only contains the encoded bytes of the original file and has no own header. Many file formats have a file header which often starts with a certain byte sequence and therefore the base64 encoded string also starts with a certain sequence. E.g. every base64 encoded png starts with 'iVBOR'. See also [my answer here](https://stackoverflow.com/questions/62329321/how-can-i-check-a-base64-string-is-a-filewhat-type-or-not/62330081#62330081). – jps Feb 18 '21 at 18:36
  • When you understand this, you can find it out easily for every filetype with a fixed header. Either look up the fileformat with a quick search on google or just encode a few files of the same type and see if the results always start with the same characters. – jps Feb 18 '21 at 18:39
  • Does this answer your question? [How can i check a base64 string is a file(what type?) or not?](https://stackoverflow.com/questions/62329321/how-can-i-check-a-base64-string-is-a-filewhat-type-or-not) – jps Feb 18 '21 at 18:55

1 Answers1

1

In relation to your switch statement, the string for a WAV file would be "UklGR" and the string for an MP3 file would be "SUQzB".

These strings are the bytes of the file itself and so this string is essentially the first part of the file header.

to6y
  • 96
  • 1
  • 9