Android中AES加密和解密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
 /**
* deEncryption method.
*
* @param data
* @param key
* @param iv
* @return
* @throws Exception
*/
public static String desEncrypt(String data, String key, String iv) throws Exception {
byte[] encrypted = new BASE64Decoder().decodeBuffer(data);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);

byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);

return originalString;
}

/**
* encryption method.
* @param key 随机生成的aesKey加密因子
* @param initVector
* @param value the data to be encrypted.
* @return
*/
public static String encrypt(String key, String initVector, String value) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: "
+ new BASE64Encoder().encode(encrypted));

return new BASE64Encoder().encode(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}

return null;

}
}