Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JSON to Base64 string in Java?

Tags:

java

json

android

I have a JsonObject (Gson) I want to encrypt this json with Aes256 before I send it to the server, so I have to convert it to Base64 first

JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("command", "abc");


String body = Base64.encodeToString(jsonObject.toString().getBytes("UTF-8"), Base64.NO_WRAP);

String finalBody = aesKeyIv.encrypt(body);

However it sends malformed json because it cannot convert properly.

EDIT: This is for Android

My encrypt method:

 public String encrypt(String value) throws Exception {
        byte[] encrypted = cipherEnc.doFinal(value.getBytes());
        return Base64.encodeToString(encrypted, Base64.NO_WRAP);
    }

1 Answers

You can import the library:

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

Then you can use following code for encoding into Base64:

public byte[] encodeBase64(String encodeMe){
byte[] encodedBytes = Base64.encodeBase64(encodeMe.getBytes());
return encodedBytes ;
} 

and for decoding you can use

public String decodeBase64(byte[] encodedBytes){
byte[] decodedBytes = Base64.decodeBase64(encodedBytes);
return new String(decodedBytes)
}

And if you are using Java 8 then you have Base64 class directly available into package:

import java.util.Base64; 

And your code for encoding into Base64 will change to :

public String encodeBase64(byte [] encodeMe){
    byte[] encodedBytes = Base64.getEncoder().encode(encodeMe);
    return new String(encodedBytes) ;
    } 

and similarly your new decoding will change as

public byte[]decodeBase64(String encodedData){
    byte[] decodedBytes = Base64.getDecoder().decode(encodedData.getBytes());
    return decodedBytes ;
    }
like image 170
Rohan Kadu Avatar answered May 31 '26 07:05

Rohan Kadu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!