Base64 Java encode and decode a string

Sameera Kumarasingha picture Sameera Kumarasingha · Nov 2, 2013 · Viewed 627.6k times · Source

I want to encode a string into base64 and transfer it through a socket and decode it back.

But after decoding it gives different answer.

Following is my code and result is "77+9x6s="

import javax.xml.bind.DatatypeConverter;

    public class f{

       public static void main(String a[]){

          String str = new String(DatatypeConverter.parseBase64Binary("user:123"));
          String res = DatatypeConverter.printBase64Binary(str.getBytes());
          System.out.println(res);
       }
    }

Any idea about how to implement this?

Answer

Dark Knight picture Dark Knight · Nov 2, 2013

You can use following approach:

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

// Encode data on your side using BASE64
byte[] bytesEncoded = Base64.encodeBase64(str.getBytes());
System.out.println("encoded value is " + new String(bytesEncoded));

// Decode data on other side, by processing encoded data
byte[] valueDecoded = Base64.decodeBase64(bytesEncoded);
System.out.println("Decoded value is " + new String(valueDecoded));

Hope this answers your doubt.