How to generate encoded base 64 string from string ?

When we work with REST API’s we have to deal with different authentications. One of the popular authentiation is from the given token string we need to generate the encoded base 64 string and need to pass as the additional authentication headers.

Using Apache Commons (import org.apache.commons.codec.binary.Base64;)

String to Encoded Base 64 – Sample Code:

public static void main(String[] args) {
        String auth = "ngdeveloper-token-string";
        byte[] encodedAuth =
                Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
        String encodedAuthString = new String(encodedAuth);
        System.out.println(encodedAuthString);
    }

Using Java Inbuilt Base 64

String to Encoded Base 64 – Sample Code:

public static void main(String[] args) {
        String auth = "ngdeveloper-token-string";
        String encodedAuth =
				Base64.getEncoder().encodeToString(auth.getBytes());
        System.out.println(encodedAuth);
    }

Output:

you will get encoded base 64 string something like,

bmdkZXZlbG9wZXItdG9rZW4tc3RyaW5n

Util.codes is the No.1 utility code snippet provder website. Login, Search, Execute & That’s it

6 comments

Leave a Reply