【Java】AES加机解密工具类代码

 1 import java.security.NoSuchAlgorithmException;
 2 import java.security.SecureRandom;
 3 
 4 import javax.crypto.Cipher;
 5 import javax.crypto.KeyGenerator;
 6 import javax.crypto.SecretKey;
 7 import javax.crypto.spec.SecretKeySpec;
 8 
 9 public final class AES {
10    //加密
11     public static String encrypt(String content, String key) throws Exception {
12 
13         Cipher cipher = Cipher.getInstance("AES");
14         cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(generateKey(key).getEncoded(), "AES"));
15         byte[] b = cipher.doFinal(content.getBytes("UTF-8"));
16 
17         if (b == null || b.length == 0) {
18             return "";
19         }
20 
21         StringBuffer buf = new StringBuffer();
22         for (int i = 0; i < b.length; i++) {
23 
24             String hex = Integer.toHexString(b[i] & 0xFF);
25 
26             if (hex.length() == 1) {
27                 hex = '0' + hex;
28             }
29             buf.append(hex.toUpperCase());
30         }
31         return buf.toString();
32     }
33     //解密
34     public static String decrypt(String content, String key) throws Exception {
35 
36         if (content == null || content.length() == 0) {
37             return null;
38         }
39 
40         byte[] b = new byte[content.length() / 2];
41         for (int i = 0; i < content.length() / 2; i++) {
42             int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
43             int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
44             b[i] = (byte) (high * 16 + low);
45         }
46 
47         Cipher cipher = Cipher.getInstance("AES");
48         cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(generateKey(key).getEncoded(), "AES"));
49 
50         return new String(cipher.doFinal(b));
51     }
52 
53     private static SecretKey generateKey(String key) throws NoSuchAlgorithmException {
54 
55         SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
56         KeyGenerator kg = KeyGenerator.getInstance("AES");
57 
58         secureRandom.setSeed(key.getBytes());
59         kg.init(128, secureRandom);
60 
61         return kg.generateKey();
62     }
63    //测试
64     public static void main(String[] args) {
65 
66         try {
67             String str = "AES测试";
68             String secretKey = "秘钥";
69 
70             System.out.println("秘钥:" + secretKey);
71             System.out.println("明文:" + str);
72 
73             String str0 = encrypt(str, secretKey);
74             System.out.println("密文:" + str0);
75             System.out.println("解密:" + decrypt(str0, secretKey));
76 
77         } catch (Exception e) {
78             e.printStackTrace();
79         }
80     }
81 }

 

posted @ 2019-10-31 14:17  IT_小树  阅读(1105)  评论(0编辑  收藏  举报