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

发布时间:2023年12月20日

背景

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

编码

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);
    }

}

验证

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!
文章来源:https://blog.csdn.net/CodersCoder/article/details/135105596
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。