之所以这里只提到解密,是因为加密在VUE前端已经实现了,前端返给后端的就是加密后的对象,而后端只负责解密就行了。如果需要后端进行加密,建议在ResponseBodyAdvice中进行。
@ApiOperationSupport(author = ApiAuthor.wenhao) @ApiOperation(value = "手机+密码 登陆",notes = "手机+密码 登陆",nickname = "loginByPhoneAndPassWord",tags={"登陆,用户接口"}) @PostMapping (value= "/loginByPhoneAndPassWord",produces = "application/json;charset=UTF-8") @DesDecrypt(aeskey = "eyJzdWgfgOiJ0b2tl") public R<SysLoginsDto> loginByPhoneAndPassWord(@RequestBody @ApiParam @Valid loginByPhoneAndPassWord p){ return R.success(loginimp.loginByPhoneAndPassWord(p)); };
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface DesDecrypt { String aeskey(); }
@AllArgsConstructor @NoArgsConstructor @Builder @Accessors(fluent = true) public class DecryptHttpInputMessage implements HttpInputMessage { private HttpHeaders headers; private InputStream body; @Override public InputStream getBody() throws IOException { return this.body; } @Override public HttpHeaders getHeaders() { return this.headers; } }
@RestControllerAdvice(annotations = RestController.class) @Configuration @Order(1) public class DecryptRequestBodyAdvice extends RequestBodyAdviceAdapter { private String supportRequest(MethodParameter methodParameter) { Method method = methodParameter.getMethod(); //拦截DesDecrypt注解的方法进行解密 if (method.isAnnotationPresent(DesDecrypt.class)) { DesDecrypt ddec = (DesDecrypt)method.getAnnotation(DesDecrypt.class); return ddec.aeskey(); }else{ return ""; } } @Value("${spring.profiles.active}") private String profiles; @Override public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) { return true; } @Override public HttpInputMessage beforeBodyRead(HttpInputMessage request, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException { String httpBody = StreamUtils.copyToString(request.getBody(), Charset.defaultCharset()); if(!profiles.equals("pro")){ //非生成环境打印原始密文 Tool.logByController.info(httpBody); } String aeskey = supportRequest(methodParameter); if (!"".equals(aeskey)) { try { httpBody = DesUtil.desEncrypt(httpBody, aeskey); } catch (Exception e) { throw new RuntimeException("提供的密文与密钥不匹配!"); } } return DecryptHttpInputMessage.builder().headers(request.getHeaders()).body(new ByteArrayInputStream(httpBody.getBytes("UTF-8"))).build(); } }
/** * 解密方法工具用的hutool * * @param data 要解密的数据 * @param key 解密key * @return 解密的结果 * @throws Exception */ public static String desEncrypt(String data, String key) throws Exception { try { //DES des = SecureUtil.des(key.getBytes()); DES des = new DES(Mode.ECB, Padding.PKCS5Padding,key.getBytes()); return des.decryptStr(data, CharsetUtil.CHARSET_UTF_8); } catch (Exception e) { throw new Exception("解密失败"); } }