java注解实现AES base64加解密

昨天学习了反射与注解,因为公司使用的是AES base64加解密进行数据规则脱敏的,今天就抽空使用注解做了个简单的Dome
代码 如下:
注解代码

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Aes加解密方法
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AesAnnotation {

    /**
     * 加密
     * @return
     */
    boolean ENCRYPTION() default false;

    /**
     * 解密
     * @return
     */
    boolean DECRYPT() default false;

    /**
     * 脱敏
     * @return
     */
    boolean DESENSITIZATION() default false;

    /**
     * 脱敏样式
     * @return
     */
    String STYLE() default "*";


}

AES加解密工具类

package com.gwh.aes_test.utils;

import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;


/**
 * AES加密解密
 * @ClassName	AesUtil
 * @Copyright (c) All Rights Reserved, 2020.
 */
public final class AesUtil {

    /**
     * 加密算法
     */
    private static final String ENCRY_ALGORITHM = "AES";

    /**
     * 加密算法/加密模式/填充类型
     * 本例采用AES加密,ECB加密模式,PKCS5Padding填充
     */
    private static final String CIPHER_MODE = "AES/ECB/PKCS5Padding";

    /**
     * 设置iv偏移量
     * 本例采用ECB加密模式,不需要设置iv偏移量
     */
    private static final String IV = null;

    /**
     * 设置加密字符集
     * 本例采用 UTF-8 字符集
     */
    private static final String CHARACTER = "UTF-8";

    /**
     * 设置加密密码处理长度。
     * 不足此长度补0;
     */
    private static final int PWD_SIZE = 16;
    
    /**
     * AES加密秘钥
     */
    private static final String AES_KEY = "token";

    /**
     * 密码处理方法
     * 如果加解密出问题,
     * 请先查看本方法,排除密码长度不足填充0字节,导致密码不一致
     * @param password 待处理的密码
     * @return
     * @throws UnsupportedEncodingException
     */
    private static byte[] pwdHandler(String password) throws UnsupportedEncodingException {
        byte[] data = null;
        if (password != null) {
            byte[] bytes = password.getBytes(CHARACTER);
            if (password.length() < PWD_SIZE) {
                System.arraycopy(bytes, 0, data = new byte[PWD_SIZE], 0, bytes.length);
            } else {
                data = bytes;
            }
        }
        return data;
    }

    //======================>原始加密<======================

    /**
     * 原始加密
     * @param clearTextBytes 明文字节数组,待加密的字节数组
     * @param pwdBytes 加密密码字节数组
     * @return 返回加密后的密文字节数组,加密错误返回null
     */
    public static byte[] encrypt(byte[] clearTextBytes, byte[] pwdBytes) {
        try {
            
            // 1 获取加密密钥
            SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);
            // 2 获取Cipher实例
            Cipher cipher = Cipher.getInstance(CIPHER_MODE);
            // 查看数据块位数 默认为16(byte) * 8 =128 bit
           // System.out.println("数据块位数(byte):" + cipher.getBlockSize());
            // 3 初始化Cipher实例。设置执行模式以及加密密钥
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            // 4 执行
            byte[] cipherTextBytes = cipher.doFinal(clearTextBytes);
            // 5 返回密文字符集
            return cipherTextBytes;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 原始解密
     * @param cipherTextBytes 密文字节数组,待解密的字节数组
     * @param pwdBytes 解密密码字节数组
     * @return 返回解密后的明文字节数组,解密错误返回null
     */
    public static byte[] decrypt(byte[] cipherTextBytes, byte[] pwdBytes) {

        try {
            // 1 获取解密密钥
            SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);
            // 2 获取Cipher实例
            Cipher cipher = Cipher.getInstance(CIPHER_MODE);
            // 查看数据块位数 默认为16(byte) * 8 =128 bit
//            System.out.println("数据块位数(byte):" + cipher.getBlockSize());
            // 3 初始化Cipher实例。设置执行模式以及加密密钥
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            // 4 执行
            byte[] clearTextBytes = cipher.doFinal(cipherTextBytes);
            // 5 返回明文字符集
            return clearTextBytes;

        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解密错误 返回null
        return null;
    }
    
    //======================>BASE64<======================

    /**
     * BASE64加密
     * @param clearText 明文,待加密的内容
     * @param password 密码,加密的密码
     * @return 返回密文,加密后得到的内容。加密错误返回null
     */
    @SuppressWarnings("restriction")
    public static String encryptBase64(String clearText, String password) {
        if(StringUtils.isEmpty(clearText)){
            return clearText;
        }
        try {
            // 1 获取加密密文字节数组
            byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));
            // 2 对密文字节数组进行BASE64 encoder 得到 BASE6输出的密文
            String cipherText = (new BASE64Encoder()).encode(cipherTextBytes);
            // 3 返回BASE64输出的密文
            return cipherText;
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 加密错误 返回null
        return null;
    }

    /**
     * BASE64解密
     * @param cipherText 密文,带解密的内容
     * @param password 密码,解密的密码
     * @return 返回明文,解密后得到的内容。解密错误返回null
     */
    @SuppressWarnings("restriction")
    public static String decryptBase64(String cipherText, String password) {
        if(StringUtils.isEmpty(cipherText)){
            return cipherText;
        }
        try {
            // 1 对 BASE64输出的密文进行BASE64 decodebuffer 得到密文字节数组
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] cipherTextBytes = base64Decoder.decodeBuffer(cipherText);
            // 2 对密文字节数组进行解密 得到明文字节数组
            byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));
            // 3 根据 CHARACTER 转码,返回明文字符串
            return new String(clearTextBytes, CHARACTER);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 解密错误返回null
        return null;
    }
    
    /**
     * 加密方法
     * @param clearText
     * @return
     * @return String
     * @since  1.0.0
     */
    public static String encryptBase64(String clearText){
        return encryptBase64(clearText,AES_KEY);
    }
    
    /**
     * 解密方法
     * @param cipherText
     * @return
     * @return String
     * @since  1.0.0
     */
    public static String decryptBase64(String cipherText){
        return decryptBase64(cipherText,AES_KEY);
    }

    //======================>HEX<======================

    /**
     * HEX加密
     * @param clearText 明文,待加密的内容
     * @param password 密码,加密的密码
     * @return 返回密文,加密后得到的内容。加密错误返回null
     */
    public static String encryptHex(String clearText, String password) {
        try {
            // 1 获取加密密文字节数组
            byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER),password.getBytes());
            // 2 对密文字节数组进行 转换为 HEX输出密文
            String cipherText = byte2hex(cipherTextBytes);
            // 3 返回 HEX输出密文
            return cipherText;
        }  catch (Exception e) {
            e.printStackTrace();
        }
        // 加密错误返回null
        return null;
    }

    /**
     * HEX解密
     * @param cipherText 密文,带解密的内容
     * @param password 密码,解密的密码
     * @return 返回明文,解密后得到的内容。解密错误返回null
     */
    public static String decryptHex(String cipherText, String password) {
        try {
            // 1 将HEX输出密文 转为密文字节数组
            byte[] cipherTextBytes = hex2byte(cipherText);
            // 2 将密文字节数组进行解密 得到明文字节数组
            byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));
            // 3 根据 CHARACTER 转码,返回明文字符串
            return new String(clearTextBytes, CHARACTER);
        }catch (Exception e) {
            e.printStackTrace();
        }
        // 解密错误返回null
        return null;
    }

    /**
     * 字节数组转成16进制字符串
     * @param bytes
     * @return
     * @return String
     * @since  1.0.0
     */
    public static String byte2hex(byte[] bytes) { // 一个字节的数,
        StringBuffer sb = new StringBuffer(bytes.length * 2);
        String tmp = "";
        for (int n = 0; n < bytes.length; n++) {
            // 整数转成十六进制表示
            tmp = (Integer.toHexString(bytes[n] & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase(); // 转成大写
    }

    /**
     * 将hex字符串转换成字节数组
     * @param str
     * @return
     * @return byte[]
     * @since  1.0.0
     */
    private static byte[] hex2byte(String str) {
        if (str == null || str.length() < 2) {
            return new byte[0];
        }
        str = str.toLowerCase();
        int l = str.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            String tmp = str.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }
}

反射工具类

package com.gwh.aes_test.utils;


import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 反射工具类
 */
public class ReflectionUtil {

    /**
     * 递归所有Field
     *
     * @param clazz
     * @return
     */
    public static List<Field> getFields(Class clazz) {
        List<Field> fields = new ArrayList<>();
        Class current = clazz;
        while (!current.getName().equals(Object.class.getName())) {
            getFields(fields, current);
            current = current.getSuperclass();
        }
        return fields;
    }

    private static void getFields(List<Field> fields, Class clazz) {
        fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
    }

    /**
     * 通过反射,设置指定对象中拥有指定注解的值
     */
    public static void setFieldValueByAnnotation(final Object obj, final Class annotation, final Object value) {
        List<Field> fields = getFields(obj.getClass());
        for (Field field : fields) {
            if (field.isAnnotationPresent(annotation)) {
                // 存在此注解,赋值
                setFieldValue(obj, field.getName(), value);
            }
        }
    }

    /**
     * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
     */
    public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
        Field field = getAccessibleField(obj, fieldName);

        if (field == null) {
            throw new IllegalArgumentException("没有找到 [" + fieldName + "] 属性。对象为 [" + obj + "]");
        }

        try {
            field.set(obj, value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    /**
     * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
     * <p>
     * 如向上转型到Object仍无法找到, 返回null.
     */
    public static Field getAccessibleField(final Object obj, final String fieldName) {
        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass()) {
            try {
                Field field = superClass.getDeclaredField(fieldName);
                makeAccessible(field);
                return field;
            } catch (NoSuchFieldException e) {
                // Field不在当前类定义,继续向上转型
            }
        }
        return null;
    }

    /**
     * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
     */
    public static void makeAccessible(Field field) {
        boolean flag = (!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
                || Modifier.isFinal(field.getModifiers())) && !field.isAccessible();
        if (flag) {
            field.setAccessible(true);
        }
    }

}

在实体类上增加加密注解

package com.gwh.aes_test.entity;

import com.alibaba.fastjson.annotation.JSONField;
import com.gwh.aes_test.annotation.AesAnnotation;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "test_customer")
public class TestCustomer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
    private Integer id;

    @AesAnnotation(ENCRYPTION = true)
    private String name;
    @AesAnnotation(ENCRYPTION = true)
    private String idNumber;
    @AesAnnotation(ENCRYPTION = true)
    private String phone;

    @JSONField(format = "yyyy-MM-dd")
    private Date createDate;

    @JSONField(format = "yyyy-MM-dd")
    private Date updateDate;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIdNumber() {
        return idNumber;
    }

    public void setIdNumber(String idNumber) {
        this.idNumber = idNumber;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }



}

执行测试方法
在这里插入图片描述
保存到数据库中的是加密字符
在这里插入图片描述

前台查询数据时候,返回给前台的实体类进行解密脱敏

package com.gwh.aes_test.vo;

import com.alibaba.fastjson.annotation.JSONField;
import com.gwh.aes_test.annotation.AesAnnotation;

import java.util.Date;

public class CustomerVo {

    @AesAnnotation(DECRYPT = true,DESENSITIZATION = true,STYLE = "*")
    private String name;
    @AesAnnotation(DECRYPT = true,DESENSITIZATION = true,STYLE = "*")
    private String idNumber;
    @AesAnnotation(DECRYPT = true,DESENSITIZATION = true,STYLE = "*")
    private String phone;

    @JSONField(format = "yyyy-MM-dd")
    private Date createDate;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIdNumber() {
        return idNumber;
    }

    public void setIdNumber(String idNumber) {
        this.idNumber = idNumber;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }
}

在这里插入图片描述
完整代码可访问 git工具

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值