如何通过AES自定义注解的方式实现用户信息加密
时间: 2024-11-16 16:27:18 浏览: 13
要通过AES自定义注解的方式在Spring Boot中实现用户信息加密,你可以按照以下步骤操作:
1. **编写自定义注解**[^1]:
创建一个名为`@Encrypt`的自定义注解,定义必要的属性,如密钥(key)、加密算法等。示例代码可能如下:
```java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Encrypt {
String key() default "your_secret_key";
// 其他加密参数可选...
}
```
2. **AES加密工具类**:
设计一个工具类,比如`EncryptionUtil.java`,用于封装AES加密和解密的方法。这里可以使用Java Cryptography Extension (JCE)库来实现AES加密/解密。例如:
```java
import javax.crypto.Cipher;
import java.security.Key;
...
public class EncryptionUtil {
private static final String ALGORITHM = "AES";
// 加密方法
public static String encrypt(String data, String key) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, generateKey(key));
return Base64.getEncoder().encodeToString(cipher.doFinal(data.getBytes()));
}
// 解密方法
public static String decrypt(String encryptedData, String key) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, generateKey(key));
byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
return new String(cipher.doFinal(decodedBytes), StandardCharsets.UTF_8);
}
// 生成AES Key
private static Key generateKey(String keyStr) throws Exception {
byte[] keyBytes = keyStr.getBytes(StandardCharsets.UTF_8);
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, ALGORITHM);
return secretKeySpec;
}
}
```
3. **实现ResponseBodyAdvice接口**:
创建一个实现了`ResponseBodyAdvice`接口的类,该类会在HTTP响应发送之前对结果进行处理。在这里,检测是否有`@Encrypt`注解并调用`EncryptionUtil`进行加密。示例代码:
```java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestControllerAdvice;
...
@RestControllerAdvice
public class ResponseBodyEncryptingAdvice implements ResponseBodyAdvice<String> {
@Override
public boolean supports(Class<? extends ResponseEntity<?>> responseEntityClass,
Method method, Object handler, HttpHeaders headers) {
return Encrypt.class.isAnnotationPresent(method.getDeclaringClass());
}
@Override
public String beforeBodyWrite(String body, MediaType mediaType,
Class<? extends ResponseEntity<?>> responseEntityClass,
Method method, Object handler, HttpHeaders headers, HttpStatus status)
throws IOException {
if (body != null && method.isAnnotationPresent(Encrypt.class)) {
String key = ((Encrypt) method.getAnnotation(Encrypt)).key();
try {
return EncryptionUtil.encrypt(body, key);
} catch (Exception e) {
throw new RuntimeException("Error while encrypting", e);
}
}
return body;
}
}
```
4. **测试**:
在控制器方法上应用`@Encrypt`注解,然后使用测试工具(如Postman)发送请求到该接口,验证返回的响应体是否已加密。
阅读全文