Java使用自定义注解实现数据脱敏以及字段加解密

背景

要求对敏感信息进行脱敏操作,要求对密码等信息进行加密存储,在服务调用以及相关查询时,显示明文。

编码

1.创建需要脱敏以及加密的相关枚举类

public enum SensitiveType {
    EMAIL, PHONE, ID_CARD, BANK_CARD, PASSWORD
}

2.创建自定义注解,要求到属性字段

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SensitiveInfo {
    SensitiveType type();
}

3.创建脱敏以及加解密,通过反射机制

public class Desensitize {
    private static final String KEY = "1234567890123456";
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
    public static void desensitize(Object obj) throws IllegalAccessException, IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            SensitiveInfo sensitiveInfo = field.getAnnotation(SensitiveInfo.class);
            if (sensitiveInfo != null) {
                field.setAccessible(true);
                Object value = field.get(obj);
                if (value != null) {
                    String desensitizedValue = desensitize(value.toString(), sensitiveInfo.type());
                    field.set(obj, desensitizedValue);
                }
            }
        }
    }

    private static String desensitize(String value, SensitiveType type) throws IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        switch (type) {
            case EMAIL:
                return desensitizeEmail(value);
            case PHONE:
                return desensitizePhone(value);
            case ID_CARD:
                return "1..todo";
            case BANK_CARD:
                return "2..todo";
            case PASSWORD:
                return encrypt(value);
            default:
                return value;
        }
    }

    private static String desensitizePhone(String phone) {
        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    private static String desensitizeEmail(String email) {
        int index = email.indexOf("@");
        if (index <= 2) {
            return email;
        }
        return email.substring(0, 2) + "****" + email.substring(index);
    }

    public static String encrypt(String str) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException, NoSuchAlgorithmException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encrypted = cipher.doFinal(str.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static String decrypt(String str) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(str));
        return new String(decrypted);
    }

}

验证

@Data
public class User {
    @SensitiveInfo(type = SensitiveType.PHONE)
    private String phone;
    @SensitiveInfo(type = SensitiveType.EMAIL)
    private String email;

    private String name;
    private String code;
    @SensitiveInfo(type = SensitiveType.PASSWORD)
    private String password;
}

public class Main {
    public static void main(String[] args) throws IllegalAccessException, IllegalBlockSizeException, NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException {
        User user = new User();
        user.setPhone("13812345678");
        user.setEmail("test@example.com");
        user.setName("aaaaaa");
        user.setCode("bnbbbbb");
        user.setPassword("Hello, world!");
        desensitize(user);
        System.out.println(user);
        System.out.println(Desensitize.decrypt(user.getPassword()));
    }
}

结果:

User(phone=138****5678, email=te****@example.com, name=aaaaaa, code=bnbbbbb, password=SyyaYH+Y+RtQID7v3kRKRA==)
Hello, world!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值