Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives for DatatypeConverter in Android

Tags:

java

android

aes

I trying implement algorithm AES 128 in Android but it doesn't work, the problem is import javax.xml.bind.DatatypeConverter;

DatatypeConverter.parseHexBinary(key) and DatatypeConverter.printBase64Binary(finalData)

Does an alternative exist?

My method:

private static final String ALGORIT = "AES";

public static String encryptHackro(String plaintext, String key)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, IOException, DecoderException {


    byte[] raw = DatatypeConverter.parseHexBinary(key);

    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance(ALGORITMO);
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

    byte[] cipherText = cipher.doFinal(plaintext.getBytes(""));
    byte[] iv = cipher.getIV();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    outputStream.write(iv);
    outputStream.write(cipherText);

    byte[] finalData = outputStream.toByteArray();

    String encodedFinalData = DatatypeConverter.printBase64Binary(finalData);

    return encodedFinalData;

}

I see others answers, but I can't implement a solution.

like image 239
David Hackro Avatar asked Dec 17 '15 18:12

David Hackro


2 Answers

In case you are looking to use DatatypeConverter like me in android please add this to build.gradle file:

implementation 'javax.xml.bind:jaxb-api:2.3.1'

This will add DatatypeConverter.

like image 149
Vasudevan V Avatar answered Nov 09 '22 02:11

Vasudevan V


Solution

I solved my problem using

compile 'commons-codec:commons-codec:1.3'

and I use android.util.Base64 for Android

incompatible / replacement

DatatypeConverter.parseHexBinary 
org.apache.commons.codec.binary.Hex.decodeHex(key.toCharArray());




DatatypeConverter.printBase64Binary(finalData);
android.util.Base64.encodeToString(finalData, 16) 



DatatypeConverter.parseBase64Binary(encodedInitialData);
org.apache.commons.codec.binary.Hex.decodeHex(key.toCharArray());
like image 15
David Hackro Avatar answered Nov 09 '22 04:11

David Hackro