当前位置:   article > 正文

基于RSA:前/后端数据加密传输流程(大致思路)_hutool rsa后端加密

hutool rsa后端加密

  1. package com.alex.examples.annotation;
  2. import java.lang.annotation.*;
  3. @Documented
  4. @Target(ElementType.METHOD) // 说明该注解只能放在方法上面
  5. @Retention(RetentionPolicy.RUNTIME)
  6. public @interface RsaAnnotation {
  7. String className() default ""; //含包路径的实体名称
  8. String fileName() default ""; //要参与验证的字段名
  9. }
  1. package com.alex.examples.aspect;
  2. import cn.hutool.json.JSONUtil;
  3. import com.alex.examples.annotation.RsaAnnotation;
  4. import com.alex.examples.rsa.TestRSA;
  5. import lombok.extern.slf4j.Slf4j;
  6. import org.apache.commons.lang.StringUtils;
  7. import org.aspectj.lang.ProceedingJoinPoint;
  8. import org.aspectj.lang.annotation.Around;
  9. import org.aspectj.lang.annotation.Aspect;
  10. import org.aspectj.lang.annotation.Pointcut;
  11. import org.springframework.core.annotation.Order;
  12. import org.springframework.stereotype.Component;
  13. import java.lang.reflect.Field;
  14. import java.util.List;
  15. /**
  16. * 定义一个切面类
  17. * 作用:需要清除对应的redis keys
  18. */
  19. @Order(2) //根据这个切面的设定顺序,这个设定的顺序越小则越先执行
  20. @Slf4j
  21. @Aspect
  22. @Component
  23. public class RsaAspect {
  24. private static final String byte2Base64 = "byte2Base64";
  25. //定义切点
  26. //让所有有@DelRedisKeysAnnotation注解的方法都执行切面方法
  27. @Pointcut("@annotation(rsaAnnotation)")
  28. public void excudeService(RsaAnnotation rsaAnnotation) {
  29. }
  30. //@Around注解可以用来在调用一个具体方法前和调用后来完成一些具体的任务。
  31. @Around("excudeService(rsaAnnotation)")
  32. public Object doAround(ProceedingJoinPoint pjp, RsaAnnotation rsaAnnotation) {
  33. log.info("进入rsaAnnotation切面类,参数值:{},{}", rsaAnnotation.className(), rsaAnnotation.fileName());
  34. if (null != pjp.getArgs() && StringUtils.isNotBlank(rsaAnnotation.fileName())) {
  35. String str = JSONUtil.toJsonStr(pjp.getArgs());
  36. try {
  37. Class clazz = Class.forName(rsaAnnotation.className());
  38. List<Object> list1 = JSONUtil.toList(str, clazz);
  39. Object o = list1.get(0);
  40. //提取父类中定义的byte2Base64参数值--开始
  41. Class dto = null;
  42. Object object = null;
  43. List<Object> superList = JSONUtil.toList(str, (Class<Object>) o.getClass().getSuperclass());
  44. Object superObj = superList.get(0);
  45. for (Field field : superObj.getClass().getDeclaredFields()) {
  46. field.setAccessible(true);
  47. String parameterValue = field.get(superObj).toString();// 参数值
  48. if (field.getName().equals(byte2Base64)) {
  49. object = TestRSA.decipherToJson(parameterValue, clazz); //解析加密串,获取明文
  50. dto = object.getClass();
  51. }
  52. }
  53. //提取父类中定义的byte2Base64参数值--结束
  54. //提取子类【className】值,进行篡改判断--开始
  55. Boolean flag = false;
  56. String[] filesName = rsaAnnotation.fileName().split(",");
  57. for (String fileName : filesName) { //循环接口定义的要验证的字段
  58. for (Field field : o.getClass().getDeclaredFields()) { //循环前端传入的参数组
  59. field.setAccessible(true);
  60. String parameterValue = field.get(o).toString(); //参数值
  61. if (field.getName().equals(fileName)) {
  62. for (Field dtoField : dto.getDeclaredFields()) { //循环解密后的明文参数组
  63. dtoField.setAccessible(true);
  64. if (field.getName().equals(fileName) && field.getName().equals(dtoField.getName())) {
  65. if (null != dtoField.get(object)) {
  66. String objParameterValue = dtoField.get(object).toString();// 参数值
  67. if (!dto.getName().equals(field.getName()) && !objParameterValue.equals(parameterValue)) {
  68. flag = true;
  69. break;
  70. }
  71. } else { //当接口定义的需要验证的参数不存在时,则说明密文加密时,没有对其进行加密,所以判断为数据已被篡改
  72. flag = true;
  73. break;
  74. }
  75. }
  76. }
  77. if (flag) {
  78. return "数据已被篡改,操作失败!";
  79. }
  80. }
  81. }
  82. }
  83. //提取子类【className】值,进行篡改判断--结束
  84. } catch (Exception e) {
  85. e.printStackTrace();
  86. }
  87. }
  88. //result的值就是被拦截方法的返回值(这里一定要return,不然进不来业务方法中)
  89. Object result = null;
  90. try {
  91. result = pjp.proceed();
  92. } catch (Throwable throwable) {
  93. throwable.printStackTrace();
  94. }
  95. return result;
  96. }
  97. }
  1. package com.alex.examples.rsa;
  2. import cn.hutool.json.JSONUtil;
  3. import com.alex.examples.vo.UserInfoDTO;
  4. import org.apache.commons.lang.StringUtils;
  5. import java.security.KeyPair;
  6. import java.security.PrivateKey;
  7. import java.security.PublicKey;
  8. /**
  9. * 备注:公钥和私钥必须是同时生成的那一对,不然则会解密失败
  10. */
  11. public class TestRSA {
  12. private static String publicKeyStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuo2EucVhaEMK/K4swqru7hWTBioO0c2a\n" +
  13. "X44EbaBKloWWH5Yku+9sxz7364Y34cSNcEO/wE7AwImDdtWqXHTSHNqlK7eTjvWO0XEgkLyPiaX1\n" +
  14. "iUA7PaCi0fw4FvZqjZfOt341asjQe43BDYPf6IHzrybOACaRcgM2JkWphhva5kNP6t7oENvRmVpR\n" +
  15. "5xnoyo32aw+hrGUewBytA6vpcro498jqAGxCsWbmhlhM9LWFdI2aiHwV/uCwFVNrcL5bi5cNHxrO\n" +
  16. "HAdlNJbpXz2orH4/GzdTF8XED9ygQRTYNmFVSMyMX7QcWP4AfmRsg4UyoL/IPBWKySYAPdjmlNML\n" +
  17. "nsT50wIDAQAB";
  18. private static String privateKeyStr = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC6jYS5xWFoQwr8rizCqu7uFZMG\n" +
  19. "Kg7RzZpfjgRtoEqWhZYfliS772zHPvfrhjfhxI1wQ7/ATsDAiYN21apcdNIc2qUrt5OO9Y7RcSCQ\n" +
  20. "vI+JpfWJQDs9oKLR/DgW9mqNl863fjVqyNB7jcENg9/ogfOvJs4AJpFyAzYmRamGG9rmQ0/q3ugQ\n" +
  21. "29GZWlHnGejKjfZrD6GsZR7AHK0Dq+lyujj3yOoAbEKxZuaGWEz0tYV0jZqIfBX+4LAVU2twvluL\n" +
  22. "lw0fGs4cB2U0lulfPaisfj8bN1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EAu1WBhhS48wda\n" +
  35. "VWHQVlk5JGuWi5My7g0B4HRMh92SYlyb+LhxPbSH1RNteb7GOEV2/OSPA/IlPgC4mORgbm7dn58G\n" +
  36. "oH9Ee4yihnJeuZqmu9HKQmybvsNETEgpWR13yq6lk6F4EgqhnnT3AfnlzzF1K3uDmuXA2WJVFpJm\n" +
  37. "DpBDHCECgYBOYmXrdMUBjA7YFfMx7N+400ddpLQMnj+lMT64Xe2IJDtRk2mKlBEXa3BjpM3LXjYs\n" +
  38. "ZB+QqGEqe5A4OHUSB7s3+5sgFekQqRy3xLSnFbiiuM6oBjD9P1VnxXKijcQFX+ak2MWKksDLCyE+\n" +
  39. "eTlNcgTG4pmcpstBp8Lmsz8c5LoDwA==";
  40. public static void main(String[] args) {
  41. try {
  42. //===============生成公钥和私钥,公钥传给客户端,私钥服务端保留==================
  43. //生成RSA公钥和私钥,并Base64编码
  44. if (StringUtils.isBlank(publicKeyStr) || StringUtils.isBlank(privateKeyStr)) {
  45. KeyPair keyPair = RSAUtil.getKeyPair();
  46. publicKeyStr = RSAUtil.getPublicKey(keyPair); //RSA公钥Base64编码
  47. privateKeyStr = RSAUtil.getPrivateKey(keyPair); //RSA私钥Base64编码
  48. }
  49. //=================客户端=================
  50. UserInfoDTO dto = new UserInfoDTO();
  51. dto.setName("哈哈");
  52. dto.setAmount(10000L);
  53. //将Base64编码后的公钥转换成PublicKey对象
  54. PublicKey publicKey = RSAUtil.string2PublicKey(publicKeyStr);
  55. //用公钥加密
  56. byte[] publicEncrypt = RSAUtil.publicEncrypt(JSONUtil.toJsonStr(dto).getBytes(), publicKey);
  57. //加密后的内容Base64编码(公钥加密并Base64编码的结果)
  58. String byte2Base64 = RSAUtil.byte2Base64(publicEncrypt);
  59. //############## 网络上传输的内容有Base64编码后的公钥 和 Base64编码后的公钥加密的内容 #################
  60. //===================服务端================
  61. //将Base64编码后的私钥转换成PrivateKey对象
  62. PrivateKey privateKey = RSAUtil.string2PrivateKey(privateKeyStr);
  63. //加密后的内容Base64解码
  64. byte[] base642Byte = RSAUtil.base642Byte(byte2Base64);
  65. //用私钥解密
  66. byte[] privateDecrypt = RSAUtil.privateDecrypt(base642Byte, privateKey);
  67. //解密后的明文
  68. UserInfoDTO bo = JSONUtil.toBean(new String(privateDecrypt), UserInfoDTO.class);
  69. System.out.println("解密后的明文: " + bo);
  70. } catch (Exception e) {
  71. e.printStackTrace();
  72. }
  73. }
  74. // public static UserInfoDTO decipherToJson(String byte2Base64){
  75. // try {
  76. // //将Base64编码后的私钥转换成PrivateKey对象
  77. // PrivateKey privateKey = RSAUtil.string2PrivateKey(privateKeyStr);
  78. // //加密后的内容Base64解码
  79. // byte[] base642Byte = RSAUtil.base642Byte(byte2Base64);
  80. // //用私钥解密
  81. // byte[] privateDecrypt = RSAUtil.privateDecrypt(base642Byte, privateKey);
  82. // //解密后的明文
  83. // UserInfoDTO bo = JSONUtil.toBean(new String(privateDecrypt), UserInfoDTO.class);
  84. // return bo;
  85. // }catch (Exception e){
  86. // e.printStackTrace();
  87. // }
  88. // return null;
  89. // }
  90. public static Object decipherToJson(String byte2Base64, Class clazz) {
  91. try {
  92. //将Base64编码后的私钥转换成PrivateKey对象
  93. PrivateKey privateKey = RSAUtil.string2PrivateKey(privateKeyStr);
  94. //加密后的内容Base64解码
  95. byte[] base642Byte = RSAUtil.base642Byte(byte2Base64);
  96. //用私钥解密
  97. byte[] privateDecrypt = RSAUtil.privateDecrypt(base642Byte, privateKey);
  98. //解密后的明文
  99. Object bo = JSONUtil.toBean(new String(privateDecrypt), clazz);
  100. return bo;
  101. } catch (Exception e) {
  102. e.printStackTrace();
  103. }
  104. return null;
  105. }
  106. }
  1. package com.alex.examples.rsa;
  2. import java.io.IOException;
  3. import java.security.KeyFactory;
  4. import java.security.KeyPair;
  5. import java.security.KeyPairGenerator;
  6. import java.security.PrivateKey;
  7. import java.security.PublicKey;
  8. import java.security.spec.PKCS8EncodedKeySpec;
  9. import java.security.spec.X509EncodedKeySpec;
  10. import javax.crypto.Cipher;
  11. import sun.misc.BASE64Decoder;
  12. import sun.misc.BASE64Encoder;
  13. public class RSAUtil {
  14. //生成秘钥对
  15. public static KeyPair getKeyPair() throws Exception {
  16. KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
  17. keyPairGenerator.initialize(2048);
  18. KeyPair keyPair = keyPairGenerator.generateKeyPair();
  19. return keyPair;
  20. }
  21. //获取公钥(Base64编码)
  22. public static String getPublicKey(KeyPair keyPair){
  23. PublicKey publicKey = keyPair.getPublic();
  24. byte[] bytes = publicKey.getEncoded();
  25. return byte2Base64(bytes);
  26. }
  27. //获取私钥(Base64编码)
  28. public static String getPrivateKey(KeyPair keyPair){
  29. PrivateKey privateKey = keyPair.getPrivate();
  30. byte[] bytes = privateKey.getEncoded();
  31. return byte2Base64(bytes);
  32. }
  33. //将Base64编码后的公钥转换成PublicKey对象
  34. public static PublicKey string2PublicKey(String pubStr) throws Exception{
  35. byte[] keyBytes = base642Byte(pubStr);
  36. X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
  37. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  38. PublicKey publicKey = keyFactory.generatePublic(keySpec);
  39. return publicKey;
  40. }
  41. //将Base64编码后的私钥转换成PrivateKey对象
  42. public static PrivateKey string2PrivateKey(String priStr) throws Exception{
  43. byte[] keyBytes = base642Byte(priStr);
  44. PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
  45. KeyFactory keyFactory = KeyFactory.getInstance("RSA");
  46. PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
  47. return privateKey;
  48. }
  49. //公钥加密
  50. public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws Exception{
  51. Cipher cipher = Cipher.getInstance("RSA");
  52. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  53. byte[] bytes = cipher.doFinal(content);
  54. return bytes;
  55. }
  56. //私钥解密
  57. public static byte[] privateDecrypt(byte[] content, PrivateKey privateKey) throws Exception{
  58. Cipher cipher = Cipher.getInstance("RSA");
  59. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  60. byte[] bytes = cipher.doFinal(content);
  61. return bytes;
  62. }
  63. //字节数组转Base64编码
  64. public static String byte2Base64(byte[] bytes){
  65. BASE64Encoder encoder = new BASE64Encoder();
  66. return encoder.encode(bytes);
  67. }
  68. //Base64编码转字节数组
  69. public static byte[] base642Byte(String base64Key) throws IOException{
  70. BASE64Decoder decoder = new BASE64Decoder();
  71. return decoder.decodeBuffer(base64Key);
  72. }
  73. }
  1. package com.alex.examples.vo;
  2. import com.alex.examples.vo.supper.RsaVo;
  3. import lombok.Data;
  4. import java.io.Serializable;
  5. @Data
  6. public class UserInfoDTO extends RsaVo implements Serializable {
  7. private String name;
  8. private Long amount; //金额,单位分
  9. private Integer userId;
  10. }
  1. package com.alex.examples.vo.supper;
  2. import lombok.Data;
  3. @Data
  4. public class RsaVo {
  5. private String byte2Base64; //加密后的数据
  6. }
  1. package com.alex.examples.controller;
  2. import com.alex.examples.annotation.RsaAnnotation;
  3. import io.swagger.annotations.Api;
  4. import io.swagger.annotations.ApiOperation;
  5. import org.springframework.web.bind.annotation.PostMapping;
  6. import org.springframework.web.bind.annotation.RequestBody;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import java.util.Map;
  10. @Api(tags = "用户管理")
  11. @RestController
  12. @RequestMapping(value = "/rsa")
  13. public class RsaController {
  14. @RsaAnnotation(className = "com.alex.examples.vo.UserInfoDTO", fileName = "name,amount") //默认金额充值时,对客户端数据进行篡改验证
  15. @ApiOperation("测试默认金额充值时,对客户端数据进行篡改验证")
  16. @PostMapping(value = "/test")
  17. public String test(@RequestBody Map<String, Object> map) {
  18. return "充值成功!";
  19. }
  20. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/948507
推荐阅读
相关标签
  

闽ICP备14008679号