使用aop数据加密、解密(3des)

切面类:

import com.alibaba.fastjson.JSONObject;
import com.tasu.server.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.*;

/**
 * @author 26968
 */
@Aspect
@Component
@Slf4j
public class WebRequestAspect {
   
    @Pointcut("execution( * com.tasu.server..controller.*.*(..))")
    public void logPointCut() {
    }

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 校验是否验证token。
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        log.info("请求地址 : " + request.getRequestURL().toString());
        log.info("请求类型 : " + request.getMethod());
        log.info("实现方法: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        log.info("参数 : " + Arrays.toString(joinPoint.getArgs()));

        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        for (Object obj : args) {
            if (obj instanceof Map) {
                Map<String, String> param = (Map<String, String>) obj;
                if (param != null && param.get("data") != null) {
                    String data = param.get("data").toString();
                    if (data == null || data.equals("")) {
                        return;
                    }
                    String result = MD5Utils.decrypt3(data);
//       转化为JSON对象
                    if (result != null && !result.equals("")) {
                        JSONObject json = JSONObject.parseObject(result);
                        Set<String> keys = json.keySet();
//       进行封装
                        for (String key : keys) {
                            ((Map) obj).put(key, json.get(key));
                        }
                    }

                }
            }
        }


    }

    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        log.debug("返回值 : " + ret);
    }


    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        // ob 为方法的返回值
        Object ob = pjp.proceed();
        Map<String, Object> map = new HashMap<>();
        String s = JSON.toJSONString(ob);
        String data = MD5Utils.encrypt3(s);
        map.put("data", data);
        log.info("耗时 : " + (System.currentTimeMillis() - startTime + "ms"));
        return map;
    }
}

加密、解密工具类

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;

/**
 * @author 26968
 */
public class MD5Utils {

   /**
    * 3des秘钥长度必须是24位
    */
   private static final String DES3_KEY ="";//自定义

   
   public static void main(String[] args) {
      System.out.println(encrypt3("{\"id\":\"765\"}"));
   }

   /**
    * 将字符串进行3DES加密,现不支持空字符串加密
    * @param data String
    *         -要加密的字符串
    * @return String
    *         -加密后的字符串
    */
   public static String encrypt3(String data)
   {
      String result = null;
      if(StringUtils.isBlank(data))
      {
         return null;
      }
      String keyStr = DES3_KEY;
      Key key = create3Key(keyStr);
      if(key != null)
      {
         try
         {
            Cipher cipher = Cipher.getInstance("DESede");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] miData = cipher.doFinal(data.getBytes("utf-8"));
            //result = Func.strByte2Hex(miData);//转化为十六进制字符串
            BASE64Encoder encoder = new BASE64Encoder();
            result = encoder.encode(miData);
         }
         catch(Exception e)
         {
            e.printStackTrace();
            return null;
         }
      }
      return result;
   }

   /**
    * 将加密后的字符串解密
    * @param data String
    *         -加密后的字符串
    * @return String
    *         -解密后的字符串
    */
   public static String decrypt3(String data)
   {
      String result = null;
      if(StringUtils.isBlank(data))
      {
         return null;
      }
      String keyStr = DES3_KEY;
      Key key = create3Key(keyStr);
      if(key != null)
      {
         byte[] sData = null;
         try
         {
            BASE64Decoder decoder = new BASE64Decoder();
            sData = decoder.decodeBuffer(data);
            Cipher cipher = Cipher.getInstance("DESede");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] miData = cipher.doFinal(sData);
            result = new String(miData);//转化为十六进制字符串
         }
         catch(Exception e)
         {
            return null;
         }
      }
      return result;
   }

   /**
    * 形成3DES加密的秘钥Key
    * @param keyStr String 密钥(秘钥长度必须是24位)
    * @return Key
    */
   private static Key create3Key(String keyStr)
   {
      if(StringUtils.isBlank(keyStr)|| keyStr.length() < 24)
      {
         return null;
      }
      SecretKey deskey = null;
      try
      {
         byte[] keyByte = keyStr.getBytes("utf-8");
         deskey = new SecretKeySpec(keyByte, "DESede");
      }
      catch(Exception e)
      {
         e.printStackTrace();
         return null;
      }
      return deskey;
   }

}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值