java Android 中 DatatypeConverter 的替代方案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34342136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alternatives for DatatypeConverter in Android
提问by David Hackro
I trying implement algorithm AES 128 in Android but it doesn't work, the problem is import javax.xml.bind.DatatypeConverter;
我尝试在 Android 中实现算法 AES 128 但它不起作用,问题是 import javax.xml.bind.DatatypeConverter;
DatatypeConverter.parseHexBinary(key)
and
DatatypeConverter.printBase64Binary(finalData)
DatatypeConverter.parseHexBinary(key)
和
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.
我看到其他人的答案,但我无法实施解决方案。
回答by David Hackro
Solution
解决方案
I solved my problem using
我解决了我的问题
compile 'commons-codec:commons-codec:1.3'
and I use android.util.Base64 for Android
我使用 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());