Android java AES加密解密 完整代码
时间: 2023-10-25 19:26:42 浏览: 126
当然可以!以下是一个示例的完整代码,用于在Android中使用Java实现AES加密和解密:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
public class AESUtil {
private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final String CHARSET = "UTF-8";
private static byte[] encrypt(byte[] key, byte[] initVector, byte[] value) {
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher.doFinal(value);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static byte[] decrypt(byte[] key, byte[] initVector, byte[] encrypted) {
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(initVector);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
return cipher.doFinal(encrypted);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String encrypt(String key, String initVector, String value) {
try {
byte[] encrypted = encrypt(key.getBytes(CHARSET), initVector.getBytes(CHARSET), value.getBytes(CHARSET));
return Base64.encodeToString(encrypted, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String key, String initVector, String encrypted) {
try {
byte[] decoded = Base64.decode(encrypted, Base64.DEFAULT);
byte[] decrypted = decrypt(key.getBytes(CHARSET), initVector.getBytes(CHARSET), decoded);
return new String(decrypted, CHARSET);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
```
使用示例:
```java
String key = "0123456789abcdef"; // 16字节的密钥
String initVector = "ABCDEF0123456789"; // 16字节的初始向量
String originalText = "Hello, AES!";
String encryptedText = AESUtil.encrypt(key, initVector, originalText);
String decryptedText = AESUtil.decrypt(key, initVector, encryptedText);
System.out.println("Original Text: " + originalText);
System.out.println("Encrypted Text: " + encryptedText);
System.out.println("Decrypted Text: " + decryptedText);
```
请注意,这只是一个简单的示例代码,并不涵盖所有的错误处理和最佳实践。在实际使用中,请根据需要进行适当的异常处理和安全性考虑。
阅读全文