Alex Rivera | Logout

Error when trying to encode/decode String to Base64

Asked 2012-09-06T12:51:59.077
16

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)
Edit
Report

2 Answers

3
String stringToStore = Base64.encode(bytes).toString();

That's not turning the bytes to a string. It's Java's string representation of the object (for example, "[B@9a4d5c6"). You need to do what iccthedral suggest and provide the bytes to a String class.

answered 2012-09-06T12:59:17.687
0

I tried Base64 from apache codec , and the result is fine.

    import org.apache.commons.codec.binary.Base64;
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    Base64 base64 = new Base64();
    byte[] stringToStore = base64.encode(bytes);
    System.out.print(Arrays.toString(stringToStore));//[65, 81, 73, 68, 66, 65, 85, 71, 66, 119, 103, 74]
    byte[] restoredBytes = base64.decode(stringToStore);
    System.out.print(Arrays.toString(restoredBytes));//[1, 2, 3, 4, 5, 6, 7, 8, 9]
answered 2012-09-06T13:14:50.883

Your Answer