Question

String encode = Base64.encodeBase64String("Hello".getBytes());
System.out.println(encode);
byte[] decode = Base64.decodeBase64(encode);
System.out.println(decode.toString());

I can't tell whats wrong here. I've tried every possible combination there is. Set the charset, toString, no toString. The encode works perfectly. I can throw that number into a web decoder and get the right value every time. Just can't get this to work.

Output:

 run:
SGVsbG8= (encode)

[B@1fb8ee3  (decode)

I can make it work if I use a for loop and manually add the characters to a string. But I thought toString did that for me?

Was it helpful?

Solution

The immediate problem is how you're converting the byte array to a string.

Try this instead:

System.out.println(new String(decode));

However, it's generally a bad idea to use the overloads of String.getBytes() or new String(byte[]) which don't specify a character encoding. They use the platform default encoding, which immediately means your code isn't portable - or at least, your data isn't. I suggest you use a common encoding such as UTF-8.

OTHER TIPS

toString() on an array doesn't do what you're expecting... it's just the default toString() implementation from Object, which returns a string based on the hashcode of the object. Try new String(decode).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top