日日操夜夜添-日日操影院-日日草夜夜操-日日干干-精品一区二区三区波多野结衣-精品一区二区三区高清免费不卡

公告:魔扣目錄網(wǎng)為廣大站長(zhǎng)提供免費(fèi)收錄網(wǎng)站服務(wù),提交前請(qǐng)做好本站友鏈:【 網(wǎng)站目錄:http://www.ylptlb.cn 】, 免友鏈快審服務(wù)(50元/站),

點(diǎn)擊這里在線咨詢客服
新站提交
  • 網(wǎng)站:51998
  • 待審:31
  • 小程序:12
  • 文章:1030137
  • 會(huì)員:747

 

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

  1. 添加依賴

在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>
  1. 實(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);
        }
    }
}
  1. 實(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);
    }
}
  1. 配置攔截器

在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)行解密。

以下是修改后的代碼示例:

  1. 定義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);
    }
}
  1. 定義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();
        }
    }
}
  1. 在控制器中解密請(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);
    }
}
  1. 配置攔截器

在WebMvcConfigurer配置類中添加AesEncryptInterceptor攔截器:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AesEncryptInterceptor());
    }
}

完成以上步驟后,接口數(shù)據(jù)的加密和解密功能

分享到:
標(biāo)簽:SpringBoot
用戶無頭像

網(wǎng)友整理

注冊(cè)時(shí)間:

網(wǎng)站:5 個(gè)   小程序:0 個(gè)  文章:12 篇

  • 51998

    網(wǎng)站

  • 12

    小程序

  • 1030137

    文章

  • 747

    會(huì)員

趕快注冊(cè)賬號(hào),推廣您的網(wǎng)站吧!
最新入駐小程序

數(shù)獨(dú)大挑戰(zhàn)2018-06-03

數(shù)獨(dú)一種數(shù)學(xué)游戲,玩家需要根據(jù)9

答題星2018-06-03

您可以通過答題星輕松地創(chuàng)建試卷

全階人生考試2018-06-03

各種考試題,題庫(kù),初中,高中,大學(xué)四六

運(yùn)動(dòng)步數(shù)有氧達(dá)人2018-06-03

記錄運(yùn)動(dòng)步數(shù),積累氧氣值。還可偷

每日養(yǎng)生app2018-06-03

每日養(yǎng)生,天天健康

體育訓(xùn)練成績(jī)?cè)u(píng)定2018-06-03

通用課目體育訓(xùn)練成績(jī)?cè)u(píng)定