[java] Base64 Java encode and decode a string

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?

This question is related to java base64 decode encode

The answer is


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);
   }
}

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"));
}

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); 

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.


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to base64

How to convert an Image to base64 string in java? How to convert file to base64 in JavaScript? How to convert Base64 String to javascript file object like as from file input form? How can I encode a string to Base64 in Swift? ReadFile in Base64 Nodejs Base64: java.lang.IllegalArgumentException: Illegal character Converting file into Base64String and back again Convert base64 string to image How to encode text to base64 in python Convert base64 string to ArrayBuffer

Examples related to decode

How to decode encrypted wordpress admin password? How to decode a QR-code image in (preferably pure) Python? Write Base64-encoded image to file Base64 Java encode and decode a string Android - How to decode and decompile any APK file? UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function PHP replacing special characters like à->a, è->e UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined> How do I decode a string with escaped unicode? UnicodeDecodeError, invalid continuation byte

Examples related to encode

Write Base64-encoded image to file Base64 Java encode and decode a string C# Base64 String to JPEG Image UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function PHP "pretty print" json_encode Convert int to ASCII and back in Python Python Unicode Encode Error How to convert a string or integer to binary in Ruby? AJAX POST and Plus Sign ( + ) -- How to Encode? How to HTML encode/escape a string? Is there a built-in?