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

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


咨詢
建站咨詢
