Android 中 DatatypeConverter 的替代方案

Alternatives for DatatypeConverter in Android

我尝试在 Android 中实现算法 AES 128 但它不起作用,问题是 import javax.xml.bind.DatatypeConverter;

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

是否存在替代方案?

我的方法:

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;

}

我看到其他人answers,但我无法实施解决方案。

解决方案

我使用

解决了我的问题
compile 'commons-codec:commons-codec:1.3'

我使用 android.util.Base64 表示 Android

不兼容 / 替换

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

如果您希望在 android 中像我一样使用 DatatypeConverter,请将此添加到 build.gradle 文件:

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

这将添加 DatatypeConverter。