187

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?

Alex Kulinkovich
  • 4,408
  • 15
  • 46
  • 50
Sameera Kumarasingha
  • 2,908
  • 3
  • 25
  • 41
  • 2
    see http://stackoverflow.com/questions/13109588/base64-encoding-in-java – Frederic Close Nov 02 '13 at 16:06
  • 5
    `DataTypeConverter` works just fine, the original poster has just mixed the order. It should look like this: `String str = DatatypeConverter.printBase64Binary("user:123".getBytes());` `String res = new String(DatatypeConverter.parseBase64Binary(str));` – mrts Sep 12 '16 at 14:42
  • 1
    parseBase64Binary() is used for decoding and printBase64Binary() is used for encoding. – sagar vyas Feb 18 '21 at 06:33

6 Answers6

272

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.

leaqui
  • 533
  • 6
  • 22
Dark Knight
  • 8,218
  • 4
  • 39
  • 58
160

Java 8 now supports BASE64 Encoding and Decoding. You can use the following classes: java.util.Base64, java.util.Base64.Encoder and java.util.Base64.Decoder.

Example usage:

// encode with padding
String encoded = Base64.getEncoder().encodeToString(someByteArray);

// encode without padding
String encoded = Base64.getEncoder().withoutPadding().encodeToString(someByteArray);

// decode a String
byte [] barr = Base64.getDecoder().decode(encoded); 
dschulz
  • 4,666
  • 1
  • 31
  • 31
Lakshma Gopidi
  • 1,601
  • 1
  • 10
  • 2
  • 28
    When to use with padding vs without padding?? – IgorGanapolsky Feb 11 '16 at 17:00
  • 5
    Take care when switching from apache to java 8: org.apache.commons.codec.binary.Base64.decodeBase64 also accepts mime encoded input, but java.util.Base64.getDecoder not. If you also want to decode mime encoded you need to use java.util.Base64.getMimeDecoder. – wdk Dec 12 '16 at 12:08
  • 2
    @IgorGanapolsky here is the anwer to what is padding? https://stackoverflow.com/questions/4080988/why-does-base64-encoding-require-padding-if-the-input-length-is-not-divisible-by It has to do with filling the String with 0 bytes if its odd – Khan Oct 01 '18 at 20:54
60

The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries

Java 11 and up

import java.util.Base64;

public class Base64Encoding {

    public static void main(String[] args) {
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        String str = "77+9x6s=";

        // encode data using BASE64
        String encoded = enc.encodeToString(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data
        String decoded = new String(dec.decode(encoded));
        System.out.println("decoded value is \t" + decoded);
        System.out.println("original value is \t" + str);
    }
}

Java 6 - 10

import java.io.UnsupportedEncodingException;    
import javax.xml.bind.DatatypeConverter;

public class EncodeString64 {
    public static void main(String[] args) throws UnsupportedEncodingException {

        String str = "77+9x6s=";
        // encode data using BASE64
        String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data 
        String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
        System.out.println("decoded value is \t" + decoded);

        System.out.println("original value is \t" + str);
    }
}

The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.

nocdib
  • 3
  • 1
nocdib
  • 1,286
  • 10
  • 7
28

For Spring Users , Spring Security has a Base64 class in the org.springframework.security.crypto.codec package that can also be used for encoding and decoding of Base64. Ex.

 public static String base64Encode(String token) {
    byte[] encodedBytes = Base64.encode(token.getBytes());
    return new String(encodedBytes, Charset.forName("UTF-8"));
}


public static String base64Decode(String token) {
    byte[] decodedBytes = Base64.decode(token.getBytes());
    return new String(decodedBytes, Charset.forName("UTF-8"));
}
iamiddy
  • 3,015
  • 3
  • 30
  • 33
  • For those of you who are looking this now 'org.springframework.security.crypto.codec.Base64' is deprecated – Samakaab Dec 16 '21 at 17:55
23

The following is a good solution -

import android.util.Base64;

String converted = Base64.encodeToString(toConvert.toString().getBytes(), Base64.DEFAULT);

String stringFromBase = new String(Base64.decode(converted, Base64.DEFAULT));

That's it. A single line encoding and decoding.

Gandalf the White
  • 2,415
  • 2
  • 18
  • 39
Yehonatan
  • 3,168
  • 7
  • 31
  • 39
8
import javax.xml.bind.DatatypeConverter;

public class f{

   public static void main(String a[]){

      String str = new String(DatatypeConverter.printBase64Binary(new String("user:123").getBytes()));
      String res = DatatypeConverter.parseBase64Binary(str);
      System.out.println(res);
   }
}
Tahong Shen
  • 101
  • 1
  • 4