Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding a Base64 string in Java

Tags:

java

base64

I'm trying to decode a simple Base64 string, but am unable to do so. I'm currently using the org.apache.commons.codec.binary.Base64 package.

The test string I'm using is: abcdefg, encoded using PHP YWJjZGVmZw==.

This is the code I'm currently using:

Base64 decoder = new Base64(); byte[] decodedBytes = decoder.decode("YWJjZGVmZw=="); System.out.println(new String(decodedBytes) + "\n") ;    

The above code does not throw an error, but instead doesn't output the decoded string as expected.

like image 683
TomasB Avatar asked Jul 18 '12 15:07

TomasB


People also ask

How do I decode 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.

How do you encode a decode string in Java Base64 encoding?

Encoder using getEncoder() and then get the encoded string by passing the byte value of actualString in encodeToString() method as parameter. byte[] actualByte= Base64. getDecoder(). decode(encodedString);

Do Base64 encoding Java?

Java 8 now has inbuilt encoder and decoder for Base64 encoding. In Java 8, we can use three types of Base64 encoding. Simple − Output is mapped to a set of characters lying in A-Za-z0-9+/. The encoder does not add any line feed in output, and the decoder rejects any character other than A-Za-z0-9+/.


1 Answers

Modify the package you're using:

import org.apache.commons.codec.binary.Base64; 

And then use it like this:

byte[] decoded = Base64.decodeBase64("YWJjZGVmZw=="); System.out.println(new String(decoded, "UTF-8") + "\n"); 
like image 87
RTB Avatar answered Sep 26 '22 15:09

RTB