Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve MIME type from Base64 encoded String

Tags:

java

mime

base64

Let' say a file (e.g. myfile.jpeg) encoded in Base64 String and given to me. There is no way I know what the file type was. I'd like to decode the string into a file (an image in this example). How do I know the type of the file (e.g jpeg)?

like image 617
codereviewanskquestions Avatar asked Feb 06 '15 00:02

codereviewanskquestions


People also ask

How do I identify a file type by base64 encoded strings?

If you have a base64 string you can detect file type by checking the first character of your base64 string: '/' means jpeg. 'i' means png. 'R' means gif.

How do I decrypt a base64 string?

To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.

What is content type for base64 encoded string?

Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. By consisting only of ASCII characters, base64 strings are generally url-safe, and that's why they can be used to encode data in Data URLs.

How do I find base64 encoding?

In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /] . If the rest length is less than 4, the string is padded with '=' characters. ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.


2 Answers

In general, a base 64-encoded string could contain absolutely any data, so there is no way to know its file type.

To determine if it is an instance of a JPEG image, you'd need to base64-decode it, and then do something like checking its magic number, which is useful in telling you what the file isn't. You'd still need to do more work to determine if it is a valid JPEG image.

like image 196
Andy Turner Avatar answered Oct 17 '22 18:10

Andy Turner


data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY/j//z8ABf4C/qc1gYQAAAAASUVORK5CYII=

Is a sample image. Just split it with the first slash and get array index 1. Supposing the image is coming from a trusted client.

like image 25
F.O.O Avatar answered Oct 17 '22 16:10

F.O.O