在Spring Boot中實(shí)現(xiàn)接口數(shù)據(jù)的加密和解密,可以使用對(duì)稱加密算法,例如AES算法,將請(qǐng)求參數(shù)和響應(yīng)結(jié)果進(jìn)行加密和解密。以下是一種示例實(shí)現(xiàn)方案:
- 添加依賴
在pom.xml文件中添加以下依賴:
<dependency>
<groupId>JAVAx.crypto</groupId>
<artifactId>jce</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.68</version>
</dependency>
- 實(shí)現(xiàn)加密和解密工具類
創(chuàng)建AesUtil工具類,實(shí)現(xiàn)AES加密和解密方法:
public class AesUtil {
// AES算法使用CBC模式和PKCS7Padding填充方式
private static final String AES_ALGORITHM = "AES/CBC/PKCS7Padding";
// AES算法的密鑰算法是AES
private static final String AES_KEY_ALGORITHM = "AES";
// 密鑰長(zhǎng)度為16個(gè)字節(jié),即128位
private static final String AES_KEY = "1234567812345678";
// 初始化向量長(zhǎng)度也為16個(gè)字節(jié),即128位
private static final String AES_IV = "1234567890123456";
// AES加密方法
public static String encrypt(String content) {
try {
byte[] keyBytes = AES_KEY.getBytes();
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, AES_KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM, "BC");
IvParameterSpec ivSpec = new IvParameterSpec(AES_IV.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = cipher.doFinal(content.getBytes("UTF-8"));
return Base64.getEncoder().encodeToString(encrypted);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// AES解密方法
public static String decrypt(String content) {
try {
byte[] keyBytes = AES_KEY.getBytes();
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, AES_KEY_ALGORITHM);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM, "BC");
IvParameterSpec ivSpec = new IvParameterSpec(AES_IV.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] encrypted = Base64.getDecoder().decode(content);
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
- 實(shí)現(xiàn)請(qǐng)求參數(shù)和響應(yīng)結(jié)果加密解密攔截器
創(chuàng)建AesEncryptInterceptor攔截器,用于對(duì)請(qǐng)求參數(shù)進(jìn)行加密和對(duì)響應(yīng)結(jié)果進(jìn)行解密:
public class AesEncryptInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 對(duì)請(qǐng)求參數(shù)進(jìn)行加密
String content = request.getParameter("content");
if (StringUtils.isNotBlank(content)) {
String encryptedContent =AesUtil.encrypt(content);
request.setAttribute("content", encryptedContent);
}
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 對(duì)響應(yīng)結(jié)果進(jìn)行解密
Object result = request.getAttribute("result");
if (result != null && result instanceof String) {
String decryptedResult = AesUtil.decrypt((String) result);
request.setAttribute("result", decryptedResult);
}
super.postHandle(request, response, handler, modelAndView);
}
}
- 配置攔截器
在WebMvcConfigurer配置類中添加AesEncryptInterceptor攔截器:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AesEncryptInterceptor());
}
}
完成以上步驟后,接口數(shù)據(jù)的加密和解密功能就已經(jīng)實(shí)現(xiàn)了。以下是示例代碼:
@RestController
@RequestMApping("/api")
public class ApiController {
@GetMapping("/hello")
public String hello(@RequestParam("content") String content) {
return "Hello, " + content;
}
}
當(dāng)發(fā)送請(qǐng)求時(shí),請(qǐng)求參數(shù)content會(huì)被攔截器加密,請(qǐng)求被處理后返回的結(jié)果也會(huì)被攔截器解密,從而保證接口數(shù)據(jù)的安全性。
如果請(qǐng)求參數(shù)在body中,則需要在攔截器中讀取請(qǐng)求體并進(jìn)行加密,同時(shí)在控制器方法中也需要讀取加密后的請(qǐng)求體并進(jìn)行解密。
以下是修改后的代碼示例:
- 定義AesEncryptInterceptor攔截器
public class AesEncryptInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 對(duì)請(qǐng)求體進(jìn)行加密
String requestBody = HttpHelper.getBodyString(request);
if (StringUtils.isNotBlank(requestBody)) {
String encryptedBody = AesUtil.encrypt(requestBody);
HttpHelper.setBodyString(request, encryptedBody);
}
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 對(duì)響應(yīng)結(jié)果進(jìn)行解密
Object result = request.getAttribute("result");
if (result != null && result instanceof String) {
String decryptedResult = AesUtil.decrypt((String) result);
request.setAttribute("result", decryptedResult);
}
super.postHandle(request, response, handler, modelAndView);
}
}
- 定義HttpHelper類
public class HttpHelper {
public static String getBodyString(final ServletRequest request) throws IOException {
InputStream inputStream = null;
StringBuilder sb = new StringBuilder();
try {
inputStream = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return sb.toString();
}
public static void setBodyString(final ServletRequest request, String body) {
try {
ServletInputStream inputStream = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String oldBody = sb.toString();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
Field field = inputStream.getClass().getDeclaredField("in");
field.setAccessible(true);
field.set(inputStream, byteArrayInputStream);
request.setAttribute("oldBody", oldBody);
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 在控制器中解密請(qǐng)求體
@RestController
@RequestMapping("/api")
public class ApiController {
@PostMapping("/hello")
public String hello(@RequestBody String requestBody) {
// 解密請(qǐng)求體
String decryptedRequestBody = AesUtil.decrypt(requestBody);
// 處理請(qǐng)求
// ...
// 返回響應(yīng)結(jié)果
String responseBody = "Hello, " + decryptedRequestBody;
// 加密響應(yīng)結(jié)果
return AesUtil.encrypt(responseBody);
}
}
- 配置攔截器
在WebMvcConfigurer配置類中添加AesEncryptInterceptor攔截器:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AesEncryptInterceptor());
}
}
完成以上步驟后,接口數(shù)據(jù)的加密和解密功能