我尝试在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; }
我看到其他人的答案,但我无法实施解决方案.
解
我解决了我的问题
compile 'commons-codec:commons-codec:1.3'
我使用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());