Home » Android » Hexadecimal string to Base64 string in Java for android-Exceptionshub

Hexadecimal string to Base64 string in Java for android-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am struggling to convert a hex string to base64 string in java. I have already tried this answer but Hex.decodeHex is showing errors.

    byte[] decodedHex;
    byte[] encodedHexB64;

    try {
      decodedHex = Hex.decodeHex("1234567890123458");
      encodedHexB64 = Base64.encodeBase64(decodedHex);
      System.out.println("FINAL ENCODED STRING -> "+encodedHexB64.toString());
     .
     ..}

Throws below error

E/AndroidRuntime: FATAL EXCEPTION: main

java.lang.NoSuchMethodError: No static method decodeHex(Ljava/lang/String;)[B in class Lorg/apache/commons/codec/binary/Hex; or its super classes (declaration of 'org.apache.commons.codec.binary.Hex' appears in /system/framework/org.apache.http.legacy.boot.jar)

I also tried to convert it to byte array and then convert to base64 string but that is also not working for me.

byte[] decodedHex;
byte[] encodedHexB64;
try {
  decodedHex = hexStringToByteArray(finalString); // finalString = 1234567890123458
  encodedHexB64 = Base64.encodeBase64(decodedHex);
  System.out.println("FINAL ENCODED STRING -> "+encodedHexB64.toString()); 
  .
  ..}

  // Desired output = EjRWeJASNFg= 
  // But actual output is FINAL ENCODED STRING -> [[email protected]

checking the same input here gives the desired output

I have also tried to use Rhino to use javascript environment to get this value from javascript functions but that is also not working for me. There must be some way in java to get this. your help would be appreciated.

How to&Answers: