栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA 后端对api接口进行加解密

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA 后端对api接口进行加解密

废话不多说,直接上代码,若对你有用帮忙点点赞,感谢支持 

目录

1、新增过滤器,对web资源进行拦截

2、新增一个切面类,⽬标⽅法执⾏前后分别执⾏

3、加解密工具类

4、接口测试 


1、新增过滤器,对web资源进行拦截
@WebFilter(urlPatterns = "/api
    private void throwFilterError(HttpServletResponse response, CloudsantHttpStatus status) throws IOException {

        Result result = new Result(status);

        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setStatus(200);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(Json.toJsonString(result));

    }

   
    private Boolean loginFilter(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //登录校验
        if (!request.getRequestURI().contains("login")) {
            String token = request.getHeader("token");
            Object userInfo = RedisUtil.get(RedisKey.API_TOKEN + token);
            if (ObjectUtil.isNull(userInfo)) {
                throwFilterError(response, CloudsantHttpStatus.UNAUTHORIZED);
                return false;
            }
            //设置token
            RedisUtil.set(RedisKey.API_TOKEN + token, userInfo, 7 * 24 * 24 * 60);
            //设置当前用户
            ApiUserUtil.putUser(Json.parseObject(userInfo.toString(), ApiUser.class));
        }
        return true;
    }
}
@Data
@Component
public class AesConfig {

    
	@Value("${aes.key}")
	private String key;

    
	@Value("${aes.open}")
	private Boolean open;
}

 配置文件application.yml中添加配置:

aes:
    key: wba2022041620221
    open: true
public class ApiWrapper extends HttpServletRequestWrapper {

    private byte[] requestBody = null;//用于将流保存下来

    public ApiWrapper(HttpServletRequest request, String key) throws IOException {
        super(request);
        requestBody = IOUtils.toByteArray(request.getInputStream());
        String salt = request.getHeader("timestamp");
        // 这里做request处理逻辑(参数解密)
        requestBody = AESEncrypt.decrypt(new String(requestBody, StandardCharsets.UTF_8), key, salt).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public ServletInputStream getInputStream() {
        // 返回的是我们处理之后的数据
        final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
        return new ServletInputStream() {
            @Override
            public int read() {
                return bais.read();  // 读取 requestBody 中的数据
            }
            @Override
            public boolean isFinished() {
                return false;
            }
            @Override
            public boolean isReady() {
                return false;
            }
            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }

}

2、新增一个切面类,⽬标⽅法执⾏前后分别执⾏
@Component
@Aspect
@Slf4j
public class AESAspect {

    @Autowired
    private AesConfig aesConfig;

    private final HttpServletRequest request;

    public AESAspect(HttpServletRequest request) {
        this.request = request;
    }

    
    @Pointcut(value = "execution(* com.cloudsant.api.controller..*.*(..))")
    public void encrypt() {

    }

    
    @Around(value = "encrypt()")
    public Result encryptParam(ProceedingJoinPoint joinPoint) {

        try {

            String salt = request.getHeader("timestamp");
            Result result = (Result) joinPoint.proceed();
            Object data = result.getData();
            if (ObjectUtil.isNull(data)) {
                return result;
            }
            //配置需要开启,否则不走加密流程
            if (!aesConfig.getOpen()) {
                return result;
            }
            //返回参数加密
            result.setData(AESEncrypt.encrypt(Json.toJsonString(data), aesConfig.getKey(), salt));
            return result;
        } catch (CloudsantShopBindException e) {
            throw new CloudsantShopBindException(e.getMessage());
        } catch (Throwable e) {
            log.info(e.getMessage());
            throw new CloudsantShopBindException("参数转换失败");
        }
    }

}

3、加解密工具类
public class AESEncrypt {

    public static final String UTF_8 = "UTF-8";
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

    static {
        try {
            //预热
            Cipher.getInstance(ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
    }

    
    private static SecretKey generateSecretKey(String secret, String salt) {
        return new SecretKeySpec(secret.getBytes(), "AES");
    }

    
    private static byte[] encryptAES(byte[] content, SecretKey secretKey) {
        byte[] str = null;
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
            str = cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return str;
    }

    
    private static byte[] decryptAES(byte[] bytes, SecretKey secretKey) {
        byte[] decryptStr = null;
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv));
            decryptStr = cipher.doFinal(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return decryptStr;
    }

    
    public static String encrypt(String content, String key, String salt) throws UnsupportedEncodingException {
        SecretKey secretKey = generateSecretKey(key, salt);
        byte[] bytes = content.getBytes(UTF_8);
        return Base64.encodeBase64String(encryptAES(bytes, secretKey));
    }

    
    public static String decrypt(String content, String key, String salt) throws UnsupportedEncodingException {
        SecretKey secretKey = generateSecretKey(key, salt);
        return new String(decryptAES(Base64.decodeBase64(content), secretKey), UTF_8);
    }


    public static void main(String[] args) {
        try {
            //参数加密
            String context = "{"password":"123456","account":"zhouhz"}";
            String s = encrypt(context, "wba2022041620221", "123456");
            System.out.println(s);

            //参数解密
            String s1 = decrypt("DiqP8oyUDPpNMK2eUaGVg62MXAgY7vjhyEZMa1Kzpgp0Sen53p/S+di1znmeJGCk", "wba2022041620221", null);
            System.out.println(s1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 以上三个步骤是api接口加解密流程,下面讲解接口测试如何使用

4、接口测试 

首先要把接口入参进行加密,用AESEncrypt类的main方法encrypt加密入参,所得到加密后的参数可以用测试工具入参,如下:

发送请求得到的返回参数也是加密的,用AESEncrypt类的main方法decrypt解密,得到的数据如下:

{"token":"7ce1a224519e651bee228fb716ae7bc2","agentNo":"JH3828","isExistGesture":true}


到这里就结束了,若有不对或不理解的地方评论留言,感谢~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/961792.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号