Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode Base64 with Jackson (or Spring)

This is the first time that I try to handle binary data so I'm quite new to this. I'm writing a REST service for uploading stuff, and I'm going to receive a Base64 encoded String.

I've found this (standard Java), and I've also found an internal Spring class (bad idea).

Is there a Jackson annotation to automatically decode a property from Base64? Should I use String or byte[] in my Object?

I'm also using Spring MVC 3, so it will be ok to have a class from the Spring framework to do this.

[please, no Apache Commons. I would like to find a solution without adding more stuff]

like image 604
Enrichman Avatar asked Nov 16 '12 10:11

Enrichman


People also ask

How do I decrypt Base64?

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.

Can we decrypt Base64?

Base64 is an encoding, the strings you've posted are encoded. You can DECODE the base64 values into bytes (so just a sequence of bits). And from there, you need to know what these bytes represent and what original encoding they were represented in, if you wish to convert them again to a legible format.

Does Base64 end in ==?

The equals sign "=" represents a padding, usually seen at the end of a Base64 encoded sequence. The size in bytes is divisible by three (bits divisible by 24): All bits are encoded normally.

Is Base64 decoder thread safe?

Instances of Base64. Decoder class are safe for use by multiple concurrent threads. Unless otherwise noted, passing a null argument to a method of this class will cause a NullPointerException to be thrown.


1 Answers

Use byte[] for property, and Base64 encoding/decoding "just works". Nothing additional to do.

Additionally, Jackson can do explicit conversion by something like:

ObjectMapper mapper = new ObjectMapper();
byte[] encoded = mapper.convertValue("Some text", byte[].class);
String decoded = mapper.convertValue(encoded, String.class);

if you want to use Jackson for stand-alone Base64 encoding/decoding.

like image 191
StaxMan Avatar answered Sep 21 '22 20:09

StaxMan