-
Notifications
You must be signed in to change notification settings - Fork 5
/
AesUtils.java
executable file
·112 lines (100 loc) · 2.85 KB
/
AesUtils.java
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
public class AesUtils
{
private static final Logger LOGGER = LoggerFactory.getLogger(AesUtils.class);
private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
private static KeyGenerator keyGen;
private static Cipher cipher;
static
{
init();
}
private static void init()
{
try
{
keyGen = KeyGenerator.getInstance("AES");
}
catch (NoSuchAlgorithmException e)
{
LOGGER.error("[AesUtils] init KeyGen error" ,e);
}
keyGen.init(128);
try
{
cipher = Cipher.getInstance(ALGORITHM);
}
catch (Exception e)
{
LOGGER.error("[AesUtils] init cihper error" ,e);
}
}
/**
* 功能描述:加密并BASE64编码<p>
*
*/
public static String encryptBase64(String content, String keyString)
{
String encryptText = null;
Key key = new SecretKeySpec(keyString.getBytes(), "AES");
try
{
cipher.init(Cipher.ENCRYPT_MODE, key);
}
catch (InvalidKeyException e)
{
LOGGER.error("[AesUtils] invalid key " + keyString, e);
}
try
{
byte[] encryptBytes = cipher.doFinal(content.getBytes());
encryptText = new String(Base64.encodeBase64(encryptBytes));
}
catch (Exception e)
{
LOGGER.error("[AesUtils] encrypt error ", e);
}
return encryptText;
}
/**
* 功能描述:从BASE64字符串解密<p>
*/
public static String decryptBase64(String content, String keyString)
{
String decryptText = null;
Key key = new SecretKeySpec(keyString.getBytes(), "AES");
try
{
cipher.init(Cipher.DECRYPT_MODE, key);
}
catch (InvalidKeyException e)
{
LOGGER.error("[AesUtils]invalid key" + keyString ,e);
}
try
{
byte[] encryptBytes = Base64.decodeBase64(content.getBytes());
byte[] decryptBytes = cipher.doFinal(encryptBytes);
decryptText = new String(decryptBytes);
}
catch (IllegalBlockSizeException e)
{
LOGGER.error("[AesUtils]invalid key" + keyString ,e);
}
catch (BadPaddingException e)
{
LOGGER.error("[AesUtils]invalid key" + keyString ,e);
}
return decryptText;
}
}