Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use custom Json annotations to desensitize output log fields

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how to use custom Json annotations to desensitize output log fields. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Custom Json annotations to desensitize the background of output log field

When the log is output, sometimes some sensitive information of the user, such as mobile phone number, ID number, bank card number, etc., will be output. Now we need to desensitize these information when the log is output.

Train of thought

Use fastjson's ValueFilter to filter fields with custom annotations

/ * sensitive information type * * @ author worstEzreal * @ version V1.0.0 * @ date 2017-7-19 * / public enum SensitiveType {ID_CARD, BANK_CARD, PHONE} / * desensitization field notes * * @ author worstEzreal * @ version V1.0.0 * @ date 2017-7-19 * / @ Target ({ElementType.TYPE, ElementType.FIELD}) @ Retention (RetentionPolicy.RUNTIME) public @ interface SensitiveInfo {SensitiveType type () * * @ author worstEzreal * @ version V1.0.0 * @ date 2017-7-19 * / public class SensitiveInfoUtils {public static String toJsonString (Object object) {return JSON.toJSONString (object, getValueFilter ());} private static String desensitizePhoneOrIdCard (String num) {if (StringUtils.isBlank (num)) {return "" } return StringUtils.left (num, 3) .concat (StringUtils.removeStart (StringUtils.leftPad (StringUtils.right (num, 4), StringUtils.length (num), "*"), "* *");} private static String desensitizeBankCard (String cardNum) {if (StringUtils.isBlank (cardNum)) {return "" } return StringUtils.left (cardNum, 4) .concat (StringUtils.removeStart (StringUtils.leftPad (StringUtils.right (cardNum, 4), StringUtils.length (cardNum), "*"), "* *")) } private static final ValueFilter getValueFilter () {return new ValueFilter () {@ Override public Object process (Object obj, String key, Object value) {/ / obj- object key- field name value- field value try {Field field = obj.getClass () .getDeclaredField (key); SensitiveInfo annotation = field.getAnnotation (SensitiveInfo.class) If (null! = annotation & & value instanceof String) {String strVal = (String) value If (StringUtils.isNotBlank (strVal)) {switch (annotation.type ()) {case PHONE: return desensitizePhoneOrIdCard (strVal) Case ID_CARD: return desensitizePhoneOrIdCard (strVal); case BANK_CARD: return desensitizeBankCard (strVal); default: break }} catch (NoSuchFieldException e) {/ / missing field has no effect on functionality, null handling} return value;}} } public static void main (String [] args) {CardInfo cardInfo = new CardInfo (); cardInfo.setId ("111111111111111"); cardInfo.setCardId ("6228480402564890018"); System.out.println (SensitiveInfoUtils.toJsonString (cardInfo));} with CardInfo class public class CardInfo {private String userId; private String name; @ SensitiveInfo (type = SensitiveType.ID_CARD) private String certId @ SensitiveInfo (type = SensitiveType.BANK_CARD) private String cardId; private String bank; private String phone; public String getUserId () {return userId;} public void setUserId (String userId) {this.userId = userId;} public String getName () {return name;} public void setName (String name) {this.name = name } public String getCertId () {return certId;} public void setCertId (String certId) {this.certId = certId;} public String getCardId () {return cardId;} public void setCardId (String cardId) {this.cardId = cardId;} public String getBank () {return bank;} public void setBank (String bank) {this.bank = bank } public String getPhone () {return phone;} public void setPhone (String phone) {this.phone = phone;}} java annotated desensitization

With the popularity of the Internet era, users' information is becoming more and more important. In the process of developing software, we also need to desensitize and encrypt users' information. For more complicated work, individuals will explain how to achieve annotation desensitization and support static calls and aop unified interception to achieve desensitization or encrypted return.

The code explains the desensitization enumeration class

Define enumeration classes, handle all desensitization, encryption, etc., while extensibility, here is just annotated invocation methods in order to write samples. If DesensitizationEnum needs other desensitization or encryption methods, simply add the following enumerated types

Package com.lgh.common.sensitive;import com.lgh.common.utils.MaskUtils;import java.lang.reflect.Method;/** * if you need to define a new scanning rule, you can add * * @ author lgh * @ version 1.0 * @ date 2021-1-17 * / public enum DesensitizationEnum {/ / execution class and desensitization method name PHONE (MaskUtils.class, "maskPhone", new Class [] {String.class}); private Class clazz Private Method method; DesensitizationEnum (Class target, String method, Class [] paramTypes) {this.clazz = target; try {this.method = target.getDeclaredMethod (method, paramTypes);} catch (NoSuchMethodException e) {e.printStackTrace ();}} public Method getMethod () {return method;}}

Desensitization tool

Package com.lgh.common.utils;import org.springframework.util.StringUtils;/** * @ author lgh * @ version 1.0 * @ date 2021-1-17 * / public class MaskUtils {public static String maskPhone (String phone) {if (StringUtils.isEmpty (phone) | | phone.length () < 8) {return phone } return phone.replaceAll ("(\\ d {3})\\ d * (\\ d {4})", "$1 please write annotation class");}}

Desensitization can be achieved by adding this class attribute to the class attribute that needs desensitization. Specifically, the desensitization function can be realized by recursively traversing this note and through the reflection mechanism.

Package com.lgh.common.sensitive;import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;/** * Parameter definition Annotation Class * @ author linguohu * @ version 1.0 * @ date 2021-1-17 * * / @ Target ({ElementType.FIELD}) @ Retention (RetentionPolicy.RUNTIME) @ Documentedpublic @ interface SensitiveValid {DesensitizationEnum type ();} desensitization tool class

Special statement: when we recurse, we will have an index recursion, and there will be an endless loop, such as an object referencing an object and a circular address reference, so there will be an endless loop. Here, 10-layer recursion is set up. Generally speaking, we are not allowed to have such a deep object setting.

Package com.lgh.common.utils;import com.lgh.common.sensitive.DesensitizationEnum;import com.lgh.common.sensitive.SensitiveValid;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.util.ReflectionUtils;import java.lang.reflect.Field;import java.util.Collection;import java.util.Map / * author lgh * @ version 1.0 * @ date 2021-1-17 * / public class DesensitizationUtils {private static final Logger log = LoggerFactory.getLogger (DesensitizationUtils.class) Private DesensitizationUtils () {} / * * scan object annotation, desensitization, top layer 8 * * @ param obj * / public static void format (Object obj) {DesensitizationUtils.formatMethod (obj, 10) } / * Recursive traversal of data, because there may be looping problems caused by the application of object addresses, while setting inexplicable and strange exceptions, so set a recursive hierarchy, generally no more than 10 layers * * @ param obj need to reflect objects * @ param level recursive hierarchy You must enter * / private static void formatMethod (Object obj, int level) {if (obj = = null | | isPrimitive (obj.getClass ()) | | level

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report