数据加密传输

数据加密传输

Scroll Down

1、前端加密数据返回

@ControllerAdvice
public class ReturnDataEncrypt implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (!(request instanceof ServletServerHttpRequest)) {
            return body;
        }
        if (!(response instanceof ServletServerHttpResponse)) {
            return body;
        }

	 .....

        /*
         * 构造秘钥
         */
        .....

        /* 加密处理, 指堆返回的Response实例进行加密处理 */
        if (body instanceof AppResultVo) {
            if (((AppResultVo<?>) body).getCode() != 1) {
                return body;
            }

            httpResponse.setHeader("encrypt", "aes");
            httpResponse.setHeader("content-Type", "text/plain");
            httpResponse.setHeader("Access-Control-Expose-Headers", "encrypt");
            String bodyString = JSON.toJSONString(body, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.WriteMapNullValue);

            try (OutputStream stream = response.getBody()) {
                String responseSecret = EncryptUtils.getMd5Long(xx);
                stream.write(CryptUtils.encrypt(bodyString, responseSecret).getBytes(StandardCharsets.UTF_8));
                stream.flush();
                return null;
            } catch (IOException e1) {
              xx
            }
        }

        return body;
    }

 /**
     * aes加密
     */
    public static String encrypt(String str, String secret) throws NoSuchPaddingException, NoSuchAlgorithmException,
            InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = common(secret, true);
        byte[] data = cipher.doFinal(str.getBytes());
        return Base64.encodeBase64String(data);
    }

    /**
     * aes解密
     */
    public static String aesDecode(String base64Str, String secret) throws Exception {
        byte[] encryptedBytes = Base64.decodeBase64(base64Str);
        byte[] key = secret.getBytes();
        SecretKeySpec keySpec = new SecretKeySpec(key, AES);
        Cipher cipher = Cipher.getInstance(ALGORITHEM);
        cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(IV));
        byte[] id = cipher.doFinal(encryptedBytes);
        return new String(id);
    }

2、https证数加密