新聞中心
在Spring Boot中實現(xiàn)接口數(shù)據(jù)的加密和解密,可以使用對稱加密算法,例如AES算法,將請求參數(shù)和響應結果進行加密和解密。以下是一種示例實現(xiàn)方案:

創(chuàng)新互聯(lián)建站堅持“要么做到,要么別承諾”的工作理念,服務領域包括:成都網站制作、成都網站建設、外貿營銷網站建設、企業(yè)官網、英文網站、手機端網站、網站推廣等服務,滿足客戶于互聯(lián)網時代的上猶網站設計、移動媒體設計的需求,幫助企業(yè)找到有效的互聯(lián)網解決方案。努力成為您成熟可靠的網絡建設合作伙伴!
添加依賴
在pom.xml文件中添加以下依賴:
javax.crypto
jce
1.0.2
org.bouncycastle
bcprov-jdk15on
1.68
實現(xiàn)加密和解密工具類
創(chuàng)建AesUtil工具類,實現(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";
// 密鑰長度為16個字節(jié),即128位
private static final String AES_KEY = "1234567812345678";
// 初始化向量長度也為16個字節(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);
}
}
}實現(xiàn)請求參數(shù)和響應結果加密解密攔截器
創(chuàng)建AesEncryptInterceptor攔截器,用于對請求參數(shù)進行加密和對響應結果進行解密:
public class AesEncryptInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 對請求參數(shù)進行加密
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 {
// 對響應結果進行解密
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ù)的加密和解密功能就已經實現(xiàn)了。以下是示例代碼:
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/hello")
public String hello(@RequestParam("content") String content) {
return "Hello, " + content;
}
}
當發(fā)送請求時,請求參數(shù)content會被攔截器加密,請求被處理后返回的結果也會被攔截器解密,從而保證接口數(shù)據(jù)的安全性。
如果請求參數(shù)在body中,則需要在攔截器中讀取請求體并進行加密,同時在控制器方法中也需要讀取加密后的請求體并進行解密。
以下是修改后的代碼示例:
定義AesEncryptInterceptor攔截器
public class AesEncryptInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 對請求體進行加密
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 {
// 對響應結果進行解密
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();
}
}
}在控制器中解密請求體
@RestController
@RequestMapping("/api")
public class ApiController {
@PostMapping("/hello")
public String hello(@RequestBody String requestBody) {
// 解密請求體
String decryptedRequestBody = AesUtil.decrypt(requestBody);
// 處理請求
// ...
// 返回響應結果
String responseBody = "Hello, " + decryptedRequestBody;
// 加密響應結果
return AesUtil.encrypt(responseBody);
}
}
配置攔截器
在WebMvcConfigurer配置類中添加AesEncryptInterceptor攔截器:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AesEncryptInterceptor());
}
}
完成以上步驟后,接口數(shù)據(jù)的加密和解密功能。
網站題目:SpringBoot:接口加密解密設計
文章源于:http://www.dlmjj.cn/article/djeddhi.html


咨詢
建站咨詢
