· 7 years ago · Aug 28, 2018, 06:22 AM
1public class AESUtil
2{
3 private static final Logger LOGGER = LoggerFactory.getLogger(AESUtil.class);
4
5 /**å°†äºŒè¿›åˆ¶è½¬æ¢æˆ16进制
6 * @param buf
7 * @return
8 */
9 public static String parseByte2HexStr(byte buf[]) {
10 StringBuffer sb = new StringBuffer();
11 for (int i = 0; i < buf.length; i++) {
12 String hex = Integer.toHexString(buf[i] & 0xFF);
13 if (hex.length() == 1) {
14 hex = '0' + hex;
15 }
16 sb.append(hex.toUpperCase());
17 }
18 return sb.toString();
19 }
20
21 public static SecretKeySpec getKey(String myKey){
22
23
24 MessageDigest sha = null;
25 try {
26 byte[] key = myKey.getBytes("UTF-8");
27 sha = MessageDigest.getInstance("SHA-1");
28 key = sha.digest(key);
29 String s = parseByte2HexStr(key);
30 String substring = s.substring(0, 16);
31 String s1 = substring.toLowerCase();
32 SecretKeySpec secretKey = new SecretKeySpec(s1.getBytes(),"AES");
33 return secretKey;
34
35 } catch (NoSuchAlgorithmException e) {
36 LOGGER.error(e.getMessage(),e);
37 } catch (UnsupportedEncodingException e) {
38 LOGGER.error(e.getMessage(),e);
39 }
40 return null;
41 }
42
43 /**
44 * åŠ å¯†
45 * @param strToEncrypt
46 * @return
47 */
48 public static String encrypt(String strToEncrypt,String password)
49 {
50 try
51 {
52 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
53
54 cipher.init(Cipher.ENCRYPT_MODE, getKey(password));
55
56
57 return Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
58
59 }
60 catch (Exception e)
61 {
62
63 LOGGER.error(e.getMessage(),e);
64 }
65 return null;
66 }
67
68 /**
69 * 解密
70 * @param strToDecrypt
71 * @return
72 */
73 public static String decrypt(String strToDecrypt,String password)
74 {
75 try
76 {
77 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
78
79 cipher.init(Cipher.DECRYPT_MODE,getKey(password));
80 return new String(cipher.doFinal(Base64.decodeBase64(strToDecrypt)));
81
82 }
83 catch (Exception e)
84 {
85
86 LOGGER.error(e.getMessage(),e);
87 }
88 return null;
89 }
90}