秘钥key的长度只能是16/24/32个字符。否则会报错:Key length not 128/192/256 bits.

pom.xml 引入

1
2
3
4
5
6
<!-- AES加密解密 PKCS7Padding-->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15</artifactId>
<version>1.44</version>
</dependency>

AES加密

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* AES加密
* AES/ECB/PKCS7Padding
*/
public static String encrypt(String input, String key) throws Exception {

SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey);
byte[] crypted = cipher.doFinal(input.getBytes());

return new String(Base64.encodeBase64(crypted));
}

AES解密

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* AES解密
* AES/ECB/PKCS7Padding
*/
public static String decrypt(String input, String key) throws Exception {

SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, skey);
byte[] output = cipher.doFinal(Base64.decodeBase64(input));

return new String(output);
}