Android中DatatypeConverter的替代方法 [英] Alternatives for DatatypeConverter in Android
本文介绍了Android中DatatypeConverter的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试在Android中实现算法AES 128,但无法正常工作,问题是 import javax.xml.bind.DatatypeConverter;
I trying implement algorithm AES 128 in Android but it doesn't work, the problem is 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;
}
我看到其他人答案,但我无法实现解决方案。
I see others answers, but I can't implement a solution.
推荐答案
解决方案
我使用
compile 'commons-codec:commons-codec:1.3'
,而我在Android上使用android.util.Base64
and I use android.util.Base64 for 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的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文