最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot中request和response的加解密實(shí)現(xiàn)代碼

 更新時(shí)間:2022年06月08日 08:28:07   作者:ldcaws  
這篇文章主要介紹了springboot中request和response的加解密實(shí)現(xiàn),在springboot中提供了RequestBodyAdviceAdapter和ResponseBodyAdvice,利用這兩個(gè)工具可以非常方便的對(duì)請(qǐng)求和響應(yīng)進(jìn)行預(yù)處理,需要的朋友可以參考下

在系統(tǒng)開(kāi)發(fā)中,需要對(duì)請(qǐng)求和響應(yīng)分別攔截下來(lái)進(jìn)行解密和加密處理,在springboot中提供了RequestBodyAdviceAdapter和ResponseBodyAdvice,利用這兩個(gè)工具可以非常方便的對(duì)請(qǐng)求和響應(yīng)進(jìn)行預(yù)處理。

1、新建一個(gè)springboot工程,pom依賴如下

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

2、自定義加密、解密的注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Encrypt {
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.PARAMETER})
public @interface Decrypt {
}

其中加密注解放在方法上,解密注解可以放在方法上,也可以放在參數(shù)上。

3、加密算法

定義一個(gè)加密工具類(lèi),加密算法分為對(duì)稱加密和非對(duì)稱加密,本次使用java自帶的Ciphor來(lái)實(shí)現(xiàn)對(duì)稱加密,使用AES算法,如下

public class AESUtils {
    private static final String AES_ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final String key = "1234567890abcdef";
    /**
     * 獲取 cipher
     * @param key
     * @param model
     * @return
     * @throws Exception
     */
    private static Cipher getCipher(byte[] key, int model) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(model, secretKeySpec);
        return cipher;
    }
    /**
     * AES加密
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static String encrypt(byte[] data, byte[] key) throws Exception {
        Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE);
        return Base64.getEncoder().encodeToString(cipher.doFinal(data));
    }
    /**
     * AES解密
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
        return cipher.doFinal(Base64.getDecoder().decode(data));
    }
}

其中加密后的數(shù)據(jù)使用Base64算法進(jìn)行編碼,獲取可讀字符串;解密的輸入也是一個(gè)Base64編碼之后的字符串,先進(jìn)行解碼再進(jìn)行解密。

4、對(duì)請(qǐng)求數(shù)據(jù)進(jìn)行解密處理

@EnableConfigurationProperties(KeyProperties.class)
@ControllerAdvice
public class DecryptRequest extends RequestBodyAdviceAdapter {

    @Autowired
    private KeyProperties keyProperties;

    /**
     * 該方法用于判斷當(dāng)前請(qǐng)求,是否要執(zhí)行beforeBodyRead方法
     *
     * @param methodParameter handler方法的參數(shù)對(duì)象
     * @param targetType      handler方法的參數(shù)類(lèi)型
     * @param converterType   將會(huì)使用到的Http消息轉(zhuǎn)換器類(lèi)類(lèi)型
     * @return 返回true則會(huì)執(zhí)行beforeBodyRead
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasMethodAnnotation(Decrypt.class) || methodParameter.hasParameterAnnotation(Decrypt.class);
    }

    /**
     * 在Http消息轉(zhuǎn)換器執(zhí)轉(zhuǎn)換,之前執(zhí)行
     * @param inputMessage
     * @param parameter
     * @param targetType
     * @param converterType
     * @return 返回 一個(gè)自定義的HttpInputMessage
     * @throws IOException
     */
    @Override
    public HttpInputMessage beforeBodyRead(final HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException {
        byte[] body = new byte[inputMessage.getBody().available()];
        inputMessage.getBody().read(body);
        try {
            byte[] keyBytes = keyProperties.getKey().getBytes();
            byte[] decrypt = AESUtils.decrypt(body, keyBytes);
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decrypt);
            return new HttpInputMessage() {
                @Override
                public InputStream getBody() throws IOException {
                    return byteArrayInputStream;
                }

                @Override
                public HttpHeaders getHeaders() {
                    return inputMessage.getHeaders();
                }
            };
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
    }
}

5、對(duì)響應(yīng)數(shù)據(jù)進(jìn)行加密處理

@EnableConfigurationProperties(KeyProperties.class)
@ControllerAdvice
public class EncryptResponse implements ResponseBodyAdvice<RespBean> {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private KeyProperties keyProperties;

    /**
     * 該方法用于判斷當(dāng)前請(qǐng)求的返回值,是否要執(zhí)行beforeBodyWrite方法
     *
     * @param methodParameter handler方法的參數(shù)對(duì)象
     * @param converterType   將會(huì)使用到的Http消息轉(zhuǎn)換器類(lèi)類(lèi)型
     * @return 返回true則會(huì)執(zhí)行beforeBodyWrite
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        return methodParameter.hasMethodAnnotation(Encrypt.class);
    }

    /**
     * 在Http消息轉(zhuǎn)換器執(zhí)轉(zhuǎn)換,之前執(zhí)行
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return 返回 一個(gè)自定義的HttpInputMessage,可以為null,表示沒(méi)有任何響應(yīng)
     */
    @Override
    public RespBean beforeBodyWrite(RespBean body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        byte[] keyBytes = keyProperties.getKey().getBytes();
        try {
            if (body.getMsg() != null) {
                body.setMsg(AESUtils.encrypt(body.getMsg().getBytes(), keyBytes));
            }
            if (body.getObj() != null) {
                body.setObj(AESUtils.encrypt(objectMapper.writeValueAsBytes(body.getObj()), keyBytes));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return body;
    }
}

6、加解密的key的配置類(lèi),從配置文件中讀取

@ConfigurationProperties(prefix = "spring.encrypt")
public class KeyProperties {

    private final static String DEFAULT_KEY = "1234567890abcdef";
    private String key = DEFAULT_KEY;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}

7、測(cè)試

application中的key配置

spring.encrypt.key=1234567890abcdef
	@GetMapping("/user")
    @Encrypt
    public RespBean getUser() {
        User user = new User();
        user.setId(1L);
        user.setUsername("caocao");
        return RespBean.ok("ok", user);
    }

    @PostMapping("/user")
    public RespBean addUser(@RequestBody @Decrypt User user) {
        System.out.println("user = " + user);
        return RespBean.ok("ok", user);
    }

測(cè)試結(jié)果

在這里插入圖片描述

在這里插入圖片描述

其中g(shù)et請(qǐng)求的接口使用了@Encrypt注解,對(duì)響應(yīng)數(shù)據(jù)進(jìn)行了加密處理;post請(qǐng)求的接口使用了@Decrypt注解作用在參數(shù)上,對(duì)請(qǐng)求數(shù)據(jù)進(jìn)行了解密處理。

到此這篇關(guān)于springboot中request和response的加解密實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)springboot加解密內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot中的@ResponseStatus注解處理異常狀態(tài)碼

    SpringBoot中的@ResponseStatus注解處理異常狀態(tài)碼

    這篇文章主要介紹了SpringBoot中的@ResponseStatus注解處理異常狀態(tài)碼,在?SpringBoot?應(yīng)用程序中,異常處理是一個(gè)非常重要的話題。當(dāng)應(yīng)用程序出現(xiàn)異常時(shí),我們需要對(duì)異常進(jìn)行處理,以保證應(yīng)用程序的穩(wěn)定性和可靠性,需要的朋友可以參考下
    2023-08-08
  • Springboot整合多數(shù)據(jù)源代碼示例詳解

    Springboot整合多數(shù)據(jù)源代碼示例詳解

    這篇文章主要介紹了Springboot整合多數(shù)據(jù)源代碼示例詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • springboot中如何使用openfeign進(jìn)行接口調(diào)用

    springboot中如何使用openfeign進(jìn)行接口調(diào)用

    這篇文章主要介紹了springboot中如何使用openfeign進(jìn)行接口調(diào)用問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • springboot利用easypoi實(shí)現(xiàn)簡(jiǎn)單導(dǎo)出功能

    springboot利用easypoi實(shí)現(xiàn)簡(jiǎn)單導(dǎo)出功能

    本文介紹了如何使用Spring Boot和EasyPoi庫(kù)實(shí)現(xiàn)Excel文件的導(dǎo)出功能,EasyPoi是一個(gè)簡(jiǎn)化Excel和Word操作的工具,通過(guò)簡(jiǎn)單的配置和代碼,可以輕松地將Java對(duì)象導(dǎo)出為Excel文件,并且支持圖片導(dǎo)出等功能,感興趣的朋友一起看看吧
    2024-12-12
  • 關(guān)于實(shí)體類(lèi)中Date屬性格式化@JsonFormat @DateTimeFormat

    關(guān)于實(shí)體類(lèi)中Date屬性格式化@JsonFormat @DateTimeFormat

    這篇文章主要介紹了關(guān)于實(shí)體類(lèi)中Date屬性格式化@JsonFormat @DateTimeFormat問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-07-07
  • 解析Spring中@Controller@Service等線程安全問(wèn)題

    解析Spring中@Controller@Service等線程安全問(wèn)題

    這篇文章主要為大家介紹解析了Spring中@Controller@Service等線程的安全問(wèn)題,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-03-03
  • Java與MySQL導(dǎo)致的時(shí)間不一致問(wèn)題分析

    Java與MySQL導(dǎo)致的時(shí)間不一致問(wèn)題分析

    在使用MySQL的過(guò)程中,你可能會(huì)遇到時(shí)區(qū)相關(guān)問(wèn)題,本文主要介紹了Java與MySQL導(dǎo)致的時(shí)間不一致問(wèn)題分析,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-07-07
  • java常用工具類(lèi) IP、File文件工具類(lèi)

    java常用工具類(lèi) IP、File文件工具類(lèi)

    這篇文章主要為大家詳細(xì)介紹了java常用工具類(lèi),包括IP、File文件工具類(lèi),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-05-05
  • Java字符串去除特殊字符內(nèi)容的實(shí)例

    Java字符串去除特殊字符內(nèi)容的實(shí)例

    下面小編就為大家分享一篇Java字符串去除特殊字符內(nèi)容的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2017-12-12
  • Java-JFrame-swing嵌套瀏覽器的具體步驟

    Java-JFrame-swing嵌套瀏覽器的具體步驟

    下面小編就為大家?guī)?lái)一篇Java-JFrame-swing嵌套瀏覽器的具體步驟。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-10-10

最新評(píng)論

大邑县| 泌阳县| 彰化市| 纳雍县| 临夏县| 丽水市| 富源县| 濮阳县| 大关县| 赤水市| 洞头县| 福鼎市| 桐乡市| 皮山县| 高陵县| 香港 | 阳泉市| 霸州市| 临颍县| 盘锦市| 长子县| 东兰县| 关岭| 福安市| 原平市| 双流县| 安达市| 苏州市| 五大连池市| 南京市| 五常市| 平安县| 册亨县| 乌鲁木齐市| 珠海市| 环江| 兰溪市| 仁寿县| 涟水县| 佛冈县| 德安县|