AES 加密和解密工具类 AESUtil 记录
最编程
2024-05-05 09:04:03
...
1、首先引入需要的jar包,如下所示:
1 <dependency>
2 <groupId>commons-codec</groupId>
3 <artifactId>commons-codec</artifactId>
4 <version>1.10</version>
5 </dependency>
2、完整的加密,解密代码,如下所示:
1 package com.bie.utils;
2
3 import org.apache.commons.codec.binary.Base64;
4
5 import javax.crypto.Cipher;
6 import javax.crypto.KeyGenerator;
7 import javax.crypto.SecretKey;
8 import javax.crypto.spec.SecretKeySpec;
9 import java.security.NoSuchAlgorithmException;
10 import java.security.SecureRandom;
11 import java.util.UUID;
12 import java.util.logging.Level;
13 import java.util.logging.Logger;
14
15 /**
16 *
17 * @author biehl
18 *
19 */
20 public class AESUtil {
21
22 private static final String KEY_ALGORITHM = "AES";
23 private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
24
25 // appKey,每隔一段时间进行替换即可
26 // 可以设计成保存到数据库中或者那里,然后进行每隔一段时间进行替换,增加保密的安全性
27 private static final String appKey = "fa8f92af-fa83-443a-9626-e32b64481320";
28
29 /**
30 * AES 加密操作
31 *
32 * @param content
33 * 待加密内容
34 * @param appKey
35 * 加密appKey
36 * @return 返回Base64转码后的加密数据
37 */
38 public static String encrypt(String content, String appKey) {
39 try {
40 Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
41
42 byte[] byteContent = content.getBytes("utf-8");
43
44 cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(appKey));// 初始化为加密模式的密码器
45
46 byte[] result = cipher.doFinal(byteContent);// 加密
47
48 return Base64.encodeBase64String(result);// 通过Base64转码返回
49 } catch (Exception ex) {
50 ex.printStackTrace();
51 }
52 return null;
53 }
54
55 /**
56 * AES 解密操作
57 *
58 * @param content
59 * 待解密内容
60 * @param appKey
61 * 加密appKey
62 * @return
63 */
64 public static String decrypt(String content, String appKey) {
65
66 try {
67 // 实例化
68 Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
69
70 // 使用密钥初始化,设置为解密模式
71 cipher.init(Cipher.DECRYPT_MODE, getSecretKey(appKey));
72
73 // 执行操作
74 byte[] result = cipher.doFinal(Base64.decodeBase64(content));
75
76 return new String(result, "utf-8");
77 } catch (Exception ex) {
78 Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
79 }
80
81 return null;
82 }
83
84 /**
85 * 生成加密秘钥
86 *
87 * @return
88 */
89 private static SecretKeySpec getSecretKey(String appKey) {
90 // 返回生成指定算法密钥生成器的 KeyGenerator 对象
91 KeyGenerator kg = null;
92
93 try {
94 kg = KeyGenerator.getInstance(KEY_ALGORITHM);
95
96 // SecureRandom 实现随操作系统本身的內部状态,除非调用方在调用 getInstance 方法之后又调用了 setSeed 方法;该实现在
97 // windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。解决在linux操作系统中加密产生的字符串不一致问题。
98 SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
99
100 secureRandom.setSeed(appKey.getBytes());
101
102 // AES 要求密钥长度为 128
103 kg.init(128, secureRandom);
104
105 // 生成一个密钥
106 SecretKey secretKey = kg.generateKey();
107
108 return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
109 } catch (NoSuchAlgorithmException ex) {
110 ex.printStackTrace();
111 }
112
113 return null;
114 }
115
116 public static void main(String[] args) {
117 // for (int i = 0; i < 10; i++) {
118 // String userNo = "410725666659845865" + i;
119 // System.out.println("未加密的身份证号码userNo: " + userNo);
120 // String s1 = AESUtil.encrypt(userNo, AESUtil.appKey);
121 // System.out.println("加密的身份证号码userNo: " + s1);
122 // }
123
124 String userNo = "410725666659845865";
125 System.out.println("未加密的身份证号码userNo: " + userNo);
126 String encryptUserNo = AESUtil.encrypt(userNo, AESUtil.appKey);
127 System.out.println("加密的身份证号码userNo: " + encryptUserNo);
128 System.out.println("加密的身份证号码userNo: " + AESUtil.encrypt(userNo, AESUtil.appKey));
129
130 String decryptUserNo = AESUtil.decrypt(encryptUserNo, AESUtil.appKey);
131 System.out.println("解密的身份证号码userNo: " + decryptUserNo);
132
133 System.out.println(UUID.randomUUID().toString());
134
135 //
136 // // 直接使用AESUtil类调用静态方法decrypt,将加密的身份证号码、密钥appKey传进去即可。
137 // String decryptUserNo = AESUtil.decrypt(s1, appKey);
138 // System.out.println("解密的身份证号码userNo:" + decryptUserNo);
139 }
140
141 }
运行效果,如下所示:
1 未加密的身份证号码userNo: 410725666659845865
2 加密的身份证号码userNo: q6zDC7F3hBuFXNT3wTOWmeZuW66xVtbaI0sgqUcuedg=
3 加密的身份证号码userNo: q6zDC7F3hBuFXNT3wTOWmeZuW66xVtbaI0sgqUcuedg=
4 解密的身份证号码userNo: 410725666659845865
5 5c8935c2-76e7-4955-974e-bf6450342c23
6
7 Process finished with exit code 0
上一篇: Tomcat 生成会话阻塞的思考
下一篇: Qt 音视频开发 39-人脸识别在线版
推荐阅读
-
手写Spring-MVC之前后置处理器与异常处理、数据库框架-首先搭建前后置处理器的框架: 和是否处理JSON格式的数据类似,需要根据注解判断controller层中的方法是否需要对JSON格式的数据进行解密或者返回数据进行加密,因此要添加两个注解@BeforeAdviser和@AfterAdviser @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) public @interface BeforeAdviser { } @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AfterAdviser { } controller层的方法需要添加相应的注解标识 /** * 使用postman发送请求 * url:http://localhost:8080/user/test12.action * json:{"username":"zs","password":"123123"} * 传递JSON参数和返回JSON */ @RequestMapping("/test12.action") @ResponseBody @AfterAdviser public User test12(@RequestBody @BeforeAdviser User user){ System.out.println("user对象:"+ user); return user; 同时需要在参数描述类中和方法描述类中添加是否有相应注解的属性: /** * 参数描述类 */ @NoArgsConstructor @AllArgsConstructor @Data public class ParameterDefinition { private String name;//参数名 private Class<?> clazz;//参数类型 private int index;//参数下标 private Type actualTypeArguments;//参数泛型的数组 private boolean requestBodyHasOrNot;//参数上是否有@RequestBody注解 private boolean beforeAdviserHasOrNot;//参数上是否有@BeforeAdviser注解 } /** * 方法描述类 */ @NoArgsConstructor @AllArgsConstructor @Data public class MethodDefinition { private String requestMappingPath;//子级URi private String name;//方法名 private Method method;//方法对象 private Class<?> returnClazz;//返回值类型 private List<ParameterDefinition> parameterDefinitions;//参数描述类对象的集合 private boolean responseBodyHasOrNot;//方法上是否有@ResponseBody注解 private boolean afterAdviserHasOrNot;//方法上是否有@AfterAdviser注解 } 添加后监听器中封装部分也要进行相应修改: //获取参数上是否有@BeforeAdviser注解 boolean beforeAdviserHasOrNot = false; BeforeAdviser beforeAdviser = parameters[i].getAnnotation(BeforeAdviser.class); if(beforeAdviser!=null){ beforeAdviserHasOrNot = true; } ParameterDefinition parameterDefinition = new ParameterDefinition(parameterName, parameterType, index,actualTypeArguments,requestBodyHasOrNot,beforeAdviserHasOrNot);//封装参数描述类对象 parameterList.add(parameterDefinition); //获取方法上是否有@AfterAdviser注解 boolean afterAdviserHasOrNot = false; AfterAdviser afterAdviser = method.getAnnotation(AfterAdviser.class); if(afterAdviser!=null){ afterAdviserHasOrNot = true; } MethodDefinition methodDefinition = new MethodDefinition(sonUri, methodName, method, returnType, parameterList,responseBodyHasOrNot,afterAdviserHasOrNot);//封装方法描述类对象 至此,监听器就能把信息记录下来,调度的DispatcherServlet进行工作的时候就可以获取到相应的注解信息。 前置处理器的使用是在获取参数类型的时候会判断是否有@BeforeAdviser注解,如果有则代表需要进行解密操作: //解密 if(parameterDefinition.isBeforeAdviserHasOrNot){ //在这里进行具体的解密操作吗? } 在处理返回值的时候会判断方法是否有@AfterAdviser注解,如果有则代表需要进行加密操作: //加密 if(methodDefinition.isAfterAdviserHasOrNot){ //在这里进行加密操作吗? } 进行具体的解密和加密操作:
-
AES 加密和解密工具类 AESUtil 记录