Android的aes cbc模式加密解密例子
时间: 2023-06-12 17:06:44 浏览: 149
一个aes加密解密的简单例子
下面是一个Android中使用AES CBC模式加密解密的示例代码:
加密:
```java
public static String encrypt(String key, String iv, String data) throws Exception {
byte[] keyBytes = key.getBytes("UTF-8");
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
return Base64.encodeToString(encrypted, Base64.DEFAULT);
}
```
解密:
```java
public static String decrypt(String key, String iv, String encryptedData) throws Exception {
byte[] keyBytes = key.getBytes("UTF-8");
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decrypted = cipher.doFinal(Base64.decode(encryptedData, Base64.DEFAULT));
return new String(decrypted);
}
```
其中,key为密钥,iv为初始化向量,data为待加密的数据。加密后返回Base64编码的字符串。解密时需要传入相同的key和iv,以及加密后的Base64编码字符串。注意,加密和解密时使用的加密算法和填充方式必须相同。
阅读全文