在Android中替代DatatypeConverter的选择

11

我试图在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;

}

我看了别人的答案,但我无法实现一个解决方案。


为什么你不能使用给定的替代方案?你遇到了什么问题? - Artjom B.
加密结果不同。 - David Hackro
1
那么你做错了什么。你应该展示一下你尝试了什么。 - Artjom B.
是的,我使用 'byte[] raw = Base64.decodeBase64(key)'。 - David Hackro
2个回答

15

解决方法

我使用以下方式解决了我的问题:

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

我在 Android 中使用 android.util.Base64。

不兼容 / 替换

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

1
Commons-codec 1.3不是Android API的一部分。如果Google在未来版本的Android中更改了commons-codec的版本,会发生什么?这只是巧合,因为版本1.3恰好与Android的根类加载器中的版本匹配。我试图解决的情况是当base64解码用于纯Java子项目并包含到Android应用程序中时。这真的很让人恼火,谷歌这样做。 - Tim P
2
这不是一个可靠的解决方案。 - Ege Kuzubasioglu
我使用实现组解决了这个问题:'javax.xml.bind',名称:'jaxb-api',版本:'2.1'。 - Amol Dadas
为什么不使用 org.apache.commons.codec.binary.Base64 - Simon Forsberg

6

如果你像我一样想在Android中使用DatatypeConverter,请将以下内容添加到build.gradle文件中:

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

这将添加DatatypeConverter。


3
请注意,您必须提供自己的实现(例如 Xerces);Android 没有默认实现。要在 Android 项目中添加 'xerces',请使用以下依赖项:implementation("xerces:xercesImpl:2.8.0")。来源:mvnrepository.com/artifact/xerces/xercesImpl/2.8.0 - Piyush Kumar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接