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

SpringBoot實(shí)現(xiàn)接口數(shù)據(jù)的加解密功能

 更新時(shí)間:2019年10月28日 16:31:10   作者:Java碎碎念  
這篇文章主要介紹了SpringBoot實(shí)現(xiàn)接口數(shù)據(jù)的加解密功能,對(duì)接口的加密解密操作主要有兩種實(shí)現(xiàn)方式,文中給大家詳細(xì)介紹,需要的朋友可以參考下

一、加密方案介紹

對(duì)接口的加密解密操作主要有下面兩種方式:

自定義消息轉(zhuǎn)換器

優(yōu)勢(shì):僅需實(shí)現(xiàn)接口,配置簡(jiǎn)單。
劣勢(shì):僅能對(duì)同一類型的MediaType進(jìn)行加解密操作,不靈活。

使用spring提供的接口RequestBodyAdvice和ResponseBodyAdvice
優(yōu)勢(shì):可以按照請(qǐng)求的Referrer、Header或url進(jìn)行判斷,按照特定需要進(jìn)行加密解密。

比如在一個(gè)項(xiàng)目升級(jí)的時(shí)候,新開(kāi)發(fā)功能的接口需要加解密,老功能模塊走之前的邏輯不加密,這時(shí)候就只能選擇上面的第二種方式了,下面主要介紹下第二種方式加密、解密的過(guò)程。

二、實(shí)現(xiàn)原理

RequestBodyAdvice可以理解為在@RequestBody之前需要進(jìn)行的 操作,ResponseBodyAdvice可以理解為在@ResponseBody之后進(jìn)行的操作,所以當(dāng)接口需要加解密時(shí),在使用@RequestBody接收前臺(tái)參數(shù)之前可以先在RequestBodyAdvice的實(shí)現(xiàn)類中進(jìn)行參數(shù)的解密,當(dāng)操作結(jié)束需要返回?cái)?shù)據(jù)時(shí),可以在@ResponseBody之后進(jìn)入ResponseBodyAdvice的實(shí)現(xiàn)類中進(jìn)行參數(shù)的加密。

RequestBodyAdvice處理請(qǐng)求的過(guò)程:

RequestBodyAdvice源碼如下:

public interface RequestBodyAdvice {
 boolean supports(MethodParameter methodParameter, Type targetType,
   Class<? extends HttpMessageConverter<?>> converterType);
 HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter,
   Type targetType, Class<? extends HttpMessageConverter<?>> converterType) throws IOException;
 Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter,
   Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
 @Nullable
 Object handleEmptyBody(@Nullable Object body, HttpInputMessage inputMessage, MethodParameter parameter,
   Type targetType, Class<? extends HttpMessageConverter<?>> converterType);
}

調(diào)用RequestBodyAdvice實(shí)現(xiàn)類的部分代碼如下:

protected <T> Object readWithMessageConverters(HttpInputMessage inputMessage, MethodParameter parameter,
   Type targetType) throws IOException, HttpMediaTypeNotSupportedException, HttpMessageNotReadableException {
  MediaType contentType;
  boolean noContentType = false;
  try {
   contentType = inputMessage.getHeaders().getContentType();
  }
  catch (InvalidMediaTypeException ex) {
   throw new HttpMediaTypeNotSupportedException(ex.getMessage());
  }
  if (contentType == null) {
   noContentType = true;
   contentType = MediaType.APPLICATION_OCTET_STREAM;
  }
  Class<?> contextClass = parameter.getContainingClass();
  Class<T> targetClass = (targetType instanceof Class ? (Class<T>) targetType : null);
  if (targetClass == null) {
   ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
   targetClass = (Class<T>) resolvableType.resolve();
  }
  HttpMethod httpMethod = (inputMessage instanceof HttpRequest ? ((HttpRequest) inputMessage).getMethod() : null);
  Object body = NO_VALUE;
  EmptyBodyCheckingHttpInputMessage message;
  try {
   message = new EmptyBodyCheckingHttpInputMessage(inputMessage);
   for (HttpMessageConverter<?> converter : this.messageConverters) {
    Class<HttpMessageConverter<?>> converterType = (Class<HttpMessageConverter<?>>) converter.getClass();
    GenericHttpMessageConverter<?> genericConverter =
      (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
    if (genericConverter != null ? genericConverter.canRead(targetType, contextClass, contentType) :
      (targetClass != null && converter.canRead(targetClass, contentType))) {
     if (logger.isDebugEnabled()) {
      logger.debug("Read [" + targetType + "] as \"" + contentType + "\" with [" + converter + "]");
     }
     if (message.hasBody()) {
      HttpInputMessage msgToUse =
        getAdvice().beforeBodyRead(message, parameter, targetType, converterType);
      body = (genericConverter != null ? genericConverter.read(targetType, contextClass, msgToUse) :
        ((HttpMessageConverter<T>) converter).read(targetClass, msgToUse));
      body = getAdvice().afterBodyRead(body, msgToUse, parameter, targetType, converterType);
     }
     else {
      body = getAdvice().handleEmptyBody(null, message, parameter, targetType, converterType);
     }
     break;
    }
   }
  }
  catch (IOException ex) {
   throw new HttpMessageNotReadableException("I/O error while reading input message", ex);
  }
  if (body == NO_VALUE) {
   if (httpMethod == null || !SUPPORTED_METHODS.contains(httpMethod) ||
     (noContentType && !message.hasBody())) {
    return null;
   }
   throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);
  }
  return body;
 }

從上面源碼可以到當(dāng)converter.canRead()message.hasBody()都為true的時(shí)候,會(huì)調(diào)用beforeBodyRead()afterBodyRead()方法,所以我們?cè)趯?shí)現(xiàn)類的afterBodyRead()中添加解密代碼即可。

ResponseBodyAdvice處理響應(yīng)的過(guò)程:

ResponseBodyAdvice源碼如下:

public interface ResponseBodyAdvice<T> {
 boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType);
 @Nullable
 T beforeBodyWrite(@Nullable T body, MethodParameter returnType, MediaType selectedContentType,
   Class<? extends HttpMessageConverter<?>> selectedConverterType,
   ServerHttpRequest request, ServerHttpResponse response);
}

調(diào)用ResponseBodyAdvice實(shí)現(xiàn)類的部分代碼如下:

if (selectedMediaType != null) {
   selectedMediaType = selectedMediaType.removeQualityValue();
   for (HttpMessageConverter<?> converter : this.messageConverters) {
    GenericHttpMessageConverter genericConverter =
      (converter instanceof GenericHttpMessageConverter ? (GenericHttpMessageConverter<?>) converter : null);
    if (genericConverter != null ?
      ((GenericHttpMessageConverter) converter).canWrite(declaredType, valueType, selectedMediaType) :
      converter.canWrite(valueType, selectedMediaType)) {
     outputValue = (T) getAdvice().beforeBodyWrite(outputValue, returnType, selectedMediaType,
       (Class<? extends HttpMessageConverter<?>>) converter.getClass(),
       inputMessage, outputMessage);
     if (outputValue != null) {
      addContentDispositionHeader(inputMessage, outputMessage);
      if (genericConverter != null) {
       genericConverter.write(outputValue, declaredType, selectedMediaType, outputMessage);
      }
      else {
       ((HttpMessageConverter) converter).write(outputValue, selectedMediaType, outputMessage);
      }
      if (logger.isDebugEnabled()) {
       logger.debug("Written [" + outputValue + "] as \"" + selectedMediaType +
         "\" using [" + converter + "]");
      }
     }
     return;
    }
   }
  }

從上面源碼可以到當(dāng)converter.canWrite()為true的時(shí)候,會(huì)調(diào)用beforeBodyWrite()方法,所以我們?cè)趯?shí)現(xiàn)類的beforeBodyWrite()中添加解密代碼即可。

三、實(shí)戰(zhàn)

新建一個(gè)spring boot項(xiàng)目spring-boot-encry,按照下面步驟操作。

pom.xml中引入jar

<dependencies>
  <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>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
   <exclusions>
    <exclusion>
     <groupId>org.junit.vintage</groupId>
     <artifactId>junit-vintage-engine</artifactId>
    </exclusion>
   </exclusions>
  </dependency>

  <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.60</version>
  </dependency>
 </dependencies>

請(qǐng)求參數(shù)解密攔截類

DecryptRequestBodyAdvice代碼如下:

/**
 * 請(qǐng)求參數(shù) 解密操作
 * * @Author: Java碎碎念
 * @Date: 2019/10/24 21:31
 *
 */
@Component
@ControllerAdvice(basePackages = "com.example.springbootencry.controller")
@Slf4j
public class DecryptRequestBodyAdvice implements RequestBodyAdvice {
 @Override
 public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
  return true;
 }
 @Override
 public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> selectedConverterType) throws IOException {
  return inputMessage;
 }
 @Override
 public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
  String dealData = null;
  try {
   //解密操作
   Map<String,String> dataMap = (Map)body;
   String srcData = dataMap.get("data");
   dealData = DesUtil.decrypt(srcData);
  } catch (Exception e) {
   log.error("異常!", e);
  }
  return dealData;
 }
 @Override
 public Object handleEmptyBody(@Nullable Object var1, HttpInputMessage var2, MethodParameter var3, Type var4, Class<? extends HttpMessageConverter<?>> var5) {
  log.info("3333");
  return var1;
 }
}

響應(yīng)參數(shù)加密攔截類

EncryResponseBodyAdvice代碼如下:

/**
 * 請(qǐng)求參數(shù) 解密操作
 *
 * @Author: Java碎碎念
 * @Date: 2019/10/24 21:31
 *
 */
@Component
@ControllerAdvice(basePackages = "com.example.springbootencry.controller")
@Slf4j
public class EncryResponseBodyAdvice implements ResponseBodyAdvice<Object> {
 @Override
 public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
  return true;
 }
 @Override
 public Object beforeBodyWrite(Object obj, MethodParameter returnType, MediaType selectedContentType,
         Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest serverHttpRequest,
         ServerHttpResponse serverHttpResponse) {
  //通過(guò) ServerHttpRequest的實(shí)現(xiàn)類ServletServerHttpRequest 獲得HttpServletRequest
  ServletServerHttpRequest sshr = (ServletServerHttpRequest) serverHttpRequest;
  //此處獲取到request 是為了取到在攔截器里面設(shè)置的一個(gè)對(duì)象 是我項(xiàng)目需要,可以忽略
  HttpServletRequest request = sshr.getServletRequest();
  String returnStr = "";
  try {
   //添加encry header,告訴前端數(shù)據(jù)已加密
   serverHttpResponse.getHeaders().add("encry", "true");
   String srcData = JSON.toJSONString(obj);
   //加密
   returnStr = DesUtil.encrypt(srcData);
   log.info("接口={},原始數(shù)據(jù)={},加密后數(shù)據(jù)={}", request.getRequestURI(), srcData, returnStr);
  } catch (Exception e) {
   log.error("異常!", e);
  }
  return returnStr;
 }

新建controller類

TestController代碼如下:

/** * @Author: Java碎碎念
 * @Date: 2019/10/24 21:40
 */
@RestController
public class TestController {
 Logger log = LoggerFactory.getLogger(getClass());
 /**
  * 響應(yīng)數(shù)據(jù) 加密
  */
 @RequestMapping(value = "/sendResponseEncryData")
 public Result sendResponseEncryData() {
  Result result = Result.createResult().setSuccess(true);
  result.setDataValue("name", "Java碎碎念");
  result.setDataValue("encry", true);
  return result;
 }
 /**
  * 獲取 解密后的 請(qǐng)求參數(shù)
  */
 @RequestMapping(value = "/getRequestData")
 public Result getRequestData(@RequestBody Object object) {
  log.info("controller接收的參數(shù)object={}", object.toString());
  Result result = Result.createResult().setSuccess(true);
  return result;
 }
}

其他類在源碼中,后面有g(shù)ithub地址

四、測(cè)試

訪問(wèn)響應(yīng)數(shù)據(jù)加密接口

使用postman發(fā)請(qǐng)求http://localhost:8888/sendResponseEncryData,可以看到返回?cái)?shù)據(jù)已加密,請(qǐng)求截圖如下:

響應(yīng)數(shù)據(jù)加密截圖

后臺(tái)也打印相關(guān)的日志,內(nèi)容如下:

接口=/sendResponseEncryData

原始數(shù)據(jù)={"data":{"encry":true,"name":"Java碎碎念"},"success":true}

加密后數(shù)據(jù)=vJc26g3SQRU9gAJdG7rhnAx6Ky/IhgioAgdwi6aLMMtyynAB4nEbMxvDsKEPNIa5bQaT7ZAImAL7

3VeicCuSTA==

訪問(wèn)請(qǐng)求數(shù)據(jù)解密接口

使用postman發(fā)請(qǐng)求http://localhost:8888/getRequestData,可以看到請(qǐng)求數(shù)據(jù)已解密,請(qǐng)求截圖如下:


請(qǐng)求數(shù)據(jù)解密截圖

后臺(tái)也打印相關(guān)的日志,內(nèi)容如下:

接收到原始請(qǐng)求數(shù)據(jù)={"data":"VwLvdE8N6FuSxn/jRrJavATopaBA3M1QEN+9bkuf2jPwC1eSofgahQ=="}

解密后數(shù)據(jù)={"name":"Java碎碎念","des":"請(qǐng)求參數(shù)"}

五、踩到的坑

測(cè)試解密請(qǐng)求參數(shù)時(shí)候,請(qǐng)求體一定要有數(shù)據(jù),否則不會(huì)調(diào)用實(shí)現(xiàn)類觸發(fā)解密操作。

到此SpringBoot中如何靈活的實(shí)現(xiàn)接口數(shù)據(jù)的加解密功能的功能已經(jīng)全部實(shí)現(xiàn),有問(wèn)題歡迎留言溝通哦!

完整源碼地址: https://github.com/suisui2019/springboot-study

總結(jié)

以上所述是小編給大家介紹的SpringBoot實(shí)現(xiàn)接口數(shù)據(jù)的加解密功能,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!

相關(guān)文章

  • Struts2 $,#,%詳解及實(shí)例代碼

    Struts2 $,#,%詳解及實(shí)例代碼

    這篇文章主要介紹了Struts2 $,#,%詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下
    2016-12-12
  • springboot實(shí)現(xiàn)https雙向傳輸協(xié)議的示例代碼

    springboot實(shí)現(xiàn)https雙向傳輸協(xié)議的示例代碼

    本文主要介紹了springboot實(shí)現(xiàn)https雙向傳輸協(xié)議的示例代碼,包含配置證書(shū)和私鑰路徑、調(diào)用請(qǐng)求方法等步驟,具有一定的參考價(jià)值,感興趣的可以了解一下
    2025-03-03
  • 解析Spring中的靜態(tài)代理和動(dòng)態(tài)代理

    解析Spring中的靜態(tài)代理和動(dòng)態(tài)代理

    學(xué)習(xí) Spring 的過(guò)程中,不可避免要掌握代理模式。這篇文章總結(jié)一下代理模式。顧名思義,代理,就是你委托別人幫你辦事,所以代理模式也有人稱作委托模式的。比如領(lǐng)導(dǎo)要做什么事,可以委托他的秘書(shū)去幫忙做,這時(shí)就可以把秘書(shū)看做領(lǐng)導(dǎo)的代理
    2021-06-06
  • java org.springframework.boot 對(duì)redis操作方法

    java org.springframework.boot 對(duì)redis操作方法

    在Spring Boot項(xiàng)目中操作Redis,你可以使用Spring Data Redis,Spring Data Redis是Spring提供的一個(gè)用于簡(jiǎn)化Redis數(shù)據(jù)訪問(wèn)的模塊,它提供了一個(gè)易于使用的編程模型來(lái)與Redis交互,本文給大家介紹java org.springframework.boot 對(duì)redis操作方法,感興趣的朋友一起看看吧
    2025-04-04
  • Spring?Boot?如何正確讀取配置文件屬性

    Spring?Boot?如何正確讀取配置文件屬性

    這篇文章主要介紹了Spring?Boot?如何正確讀取配置文件屬性,項(xiàng)目中經(jīng)常會(huì)經(jīng)常讀取配置文件中的屬性的值,Spring?Boot提供了很多注解讀取配置文件屬性,那么如何正確使用呢,下文一起來(lái)參考下面文章內(nèi)容吧
    2022-04-04
  • SpringBoot RedisTemplate分布式鎖的項(xiàng)目實(shí)戰(zhàn)

    SpringBoot RedisTemplate分布式鎖的項(xiàng)目實(shí)戰(zhàn)

    本文主要介紹了SpringBoot RedisTemplate分布式鎖的項(xiàng)目實(shí)戰(zhàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05
  • Java并行執(zhí)行任務(wù)的幾種方案小結(jié)

    Java并行執(zhí)行任務(wù)的幾種方案小結(jié)

    這篇文章主要介紹了Java并行執(zhí)行任務(wù)的幾種方案小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • 使用FormData上傳二進(jìn)制文件、對(duì)象、對(duì)象數(shù)組方式

    使用FormData上傳二進(jìn)制文件、對(duì)象、對(duì)象數(shù)組方式

    這篇文章主要介紹了使用FormData上傳二進(jìn)制文件、對(duì)象、對(duì)象數(shù)組方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • IDEA+Maven打JAR包的兩種方法步驟詳解

    IDEA+Maven打JAR包的兩種方法步驟詳解

    Idea中為一般的非Web項(xiàng)目打Jar包是有自己的方法的,下面這篇文章主要給大家介紹了關(guān)于IDEA+Maven打JAR包的兩種方法,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-09-09
  • Springboot 接口對(duì)接文件及對(duì)象的操作方法

    Springboot 接口對(duì)接文件及對(duì)象的操作方法

    這篇文章主要介紹了Springboot 接口對(duì)接文件及對(duì)象的操作,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-07-07

最新評(píng)論

中西区| 衡阳市| 北京市| 兴宁市| 郧西县| 云霄县| 休宁县| 庆云县| 嘉义县| 合川市| 海兴县| 丰台区| 故城县| 汾阳市| 扎赉特旗| 色达县| 金昌市| 漳平市| 平潭县| 安福县| 辽源市| 鄂温| 彰化县| 获嘉县| 桃园市| 石阡县| 乐业县| 施甸县| 渝北区| 平湖市| 浪卡子县| 永寿县| 蒙城县| 抚州市| 克拉玛依市| 全椒县| 山丹县| 年辖:市辖区| 桂林市| 唐海县| 上杭县|