Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when trying to encode/decode String to Base64

Tags:

java

base64

I need to do Base64 encoding from byte array to stirng as opposed to another byte array. But when I decode it back I get exception. Here is the code

I'm trying to encode a byte array into a string using Base64 encoding. When I encode, it seems to work, but when I decode it throws an exception. What am I doing wrong?

import org.springframework.security.crypto.codec.Base64;

byte[] bytes = new byte[]{1,2,3,4,5,6,7,8,9};
String stringToStore = Base64.encode(bytes).toString();
byte[] restoredBytes = Base64.decode(stringToStore.getBytes());

Here is the exception I'm getting:

org.springframework.security.crypto.codec.InvalidBase64CharacterException: Bad Base64 input character decimal 91 in array position 0
at org.springframework.security.crypto.codec.Base64.decode(Base64.java:625)
at org.springframework.security.crypto.codec.Base64.decode(Base64.java:246)
like image 345
user1651914 Avatar asked Sep 06 '12 12:09

user1651914


People also ask

What is the problem that Base64 encoding method design to solve?

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remains intact without modification during transport.

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.

What is Base64 error?

This error happens when the string that you are trying to transform contains a character not recognized by the basic Base 64 Alphabet (in this case it was an underscore character). Below you can see which characters are accepted. ietf.org - RFC 4648.

Is there a limit to Base64 encoding?

The BASE64ENCODE function returns the Base64 encoded version of the binary values of a character string. The schema is SYSTOOLS. A character expression to be encoded. The maximum length in 2732 characters.


1 Answers

Could you try...

byte[] bytes = new byte[]{1,2,3,4,5,6,7,8,9}; 
String stringToStore = new String(Base64.encode(bytes));
byte[] restoredBytes = Base64.decode(stringToStore.getBytes()); 
like image 62
nullpotent Avatar answered Sep 18 '22 15:09

nullpotent