xiaohan2012
xiaohan2012

Reputation: 10322

Java base64 encoding output from Apache Common the "wrong" result

I am trying to use the Base64 encoding functionality from Apache Common. But I seem to get the "wrong" result. The doc is here.

My code is like this:

import org.apache.commons.codec.binary.Base64;
String data = "hi,all,how can this happen?";

byte[] databytes = Base64.encodeBase64(data.getBytes());
data = databytes.toString();

System.out.println(data);
//the result is:
//[B@121cc40

However I encode the same string using Python, the code is:

import base64
print base64.b64encode("hi,all,how can this happen?")
#The result is aGksYWxsLGhvdyBjYW4gdGhpcyBoYXBwZW4/

How can there be such difference?

Upvotes: 1

Views: 4585

Answers (3)

Darshil Shah
Darshil Shah

Reputation: 495

You are printing the address. If you want to print the String data, you can use,

String password = new String(databytes);
System.out.println("Encoded String "+ password)

Upvotes: 1

Java
Java

Reputation: 2489

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

    public class Codec {
      public static void main(String[] args) {
        try {
          String data = "hi,all,how can this happen?";
          String encodedText;

          // Base64
          encodedText = new String(Base64.encodeBase64(data.getBytes()));
          System.out.println("Encoded: " + encodedText);
          System.out.println("Decoded:" 
              + new String(Base64.decodeBase64(encodedText.getBytes())));

        } 
        catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

Now it will encode your String data

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359776

That's not how you print a byte (or any other type of) array in Java, if you want to view its contents.
This is:

System.out.println(Arrays.toString(data));

Upvotes: 4

Related Questions