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

Example Analysis of desensitization Annotation of SpringBoot Custom Annotation

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

Share

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

This article will explain in detail the example analysis of desensitization annotations for SpringBoot custom annotations. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Desensitization annotation of custom annotation

Data desensitization refers to the deformation of some sensitive information through desensitization rules to achieve the reliable protection of sensitive private data. The requirement is to desensitize the data returned to the front end so as to avoid the disclosure of private information.

First, the effect after desensitization

It's not a good display. All the information has been leaked.

That's good, right?

Second, Code 1. Desensitization annotation @ Retention (RetentionPolicy.RUNTIME) @ Target (ElementType.FIELD) @ JacksonAnnotationsInside@JsonSerialize (using = SensitiveSerialize.class) public @ interface Sensitive {/ * * desensitized data type * / SensitiveTypeEnum type () default SensitiveTypeEnum.CUSTOMER; / * * prefixed length * / int prefixNoMaskLen () default 0 / int suffixNoMaskLen () default 0; / * * how to code * / String symbol () default "*";} 2. Define the desensitization type public enum SensitiveTypeEnum {/ * Custom * / CUSTOMER, / * name * / NAME, / * * ID * / ID_NUM, / * Mobile phone number * / PHONE_NUM} 3. Sensitive tool class public class DesensitizedUtils {/ * desensitize strings * * @ param origin original string * @ param prefixNoMaskLen A few bits of plaintext field * @ param suffixNoMaskLen need to be retained on the left side * @ param maskStr string used for masking For example, the desensitized result of'*'* @ return is * / public static String desValue (String origin, int prefixNoMaskLen, int suffixNoMaskLen, String maskStr) {if (origin = = null) {return null } StringBuilder sb = new StringBuilder (); for (int I = 0, n = origin.length (); I

< n; i++) { if (i < prefixNoMaskLen) { sb.append(origin.charAt(i)); continue; } if (i >

(n-suffixNoMaskLen-1)) {sb.append (origin.charAt (I)); continue;} sb.append (maskStr);} return sb.toString () } / * * [Chinese name] shows only the last Chinese character, and others are hidden as asterisks, such as: * * Dream * @ param fullName name * @ return result * / public static String chineseName (String fullName) {if (fullName = = null) {return null;} return desValue (fullName, 1,0, "*") } / * * [ID card number] shows the first 4 digits, the last 2 digits, and other hidden digits. * * @ param id ID number * @ return result * / public static String idCardNum (String id) {return desValue (id, 4, 2, "*");} / * * [Mobile phone number] the first three digits, the last four digits, and the other hidden digits. * * @ param num Mobile number * @ return result * / public static String mobilePhone (String num) {return desValue (num, 3,4, "*");}} 4. Desensitization serialization information @ NoArgsConstructor@AllArgsConstructorpublic class SensitiveSerialize extends JsonSerializer implements ContextualSerializer {/ * desensitization type * / private SensitiveTypeEnum sensitiveTypeEnum; / * * the first few bits are not desensitized * / private Integer prefixNoMaskLen; / * the last bits are not desensitized * / private Integer suffixNoMaskLen; / * * how to code * / private String symbol Override public void serialize (final String origin, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException {switch (sensitiveTypeEnum) {case CUSTOMER: jsonGenerator.writeString (DesensitizedUtils.desValue (origin, prefixNoMaskLen, suffixNoMaskLen, symbol)); break; case NAME: jsonGenerator.writeString (DesensitizedUtils.chineseName (origin)); break Case ID_NUM: jsonGenerator.writeString (DesensitizedUtils.idCardNum (origin)); break; case PHONE_NUM: jsonGenerator.writeString (DesensitizedUtils.mobilePhone (origin)); break; default: throw new IllegalArgumentException ("unknown sensitive type enum" + sensitiveTypeEnum) } @ Override public JsonSerializer createContextual (final SerializerProvider serializerProvider, final BeanProperty beanProperty) throws JsonMappingException {if (beanProperty! = null) {if (Objects.equals (beanProperty.getType (). GetRawClass (), String.class)) {Sensitive sensitive = beanProperty.getAnnotation (Sensitive.class) If (sensitive = = null) {sensitive = beanProperty.getContextAnnotation (Sensitive.class);} if (sensitive! = null) {return new SensitiveSerialize (sensitive.type (), sensitive.prefixNoMaskLen (), sensitive.suffixNoMaskLen (), sensitive.symbol ()) }} return serializerProvider.findValueSerializer (beanProperty.getType (), beanProperty);} return serializerProvider.findNullValueSerializer (null);}} summary

This annotation is used for desensitization of private data and only works on the properties of the class. The annotation has four attributes. Type represents the desensitized data type (the default is CUSTOMER customization, and the last three attributes are valid). PrefixNoMaskLen represents the length of the front that does not require coding (default is 0), suffixNoMaskLen represents the length of the post that does not need to be typed (default is 0), and symbol indicates what to code (default is *).

It is generally used to return objects to front-end objects that contain private data such as ID cards and detailed addresses that need to be desensitized.

Example:

Public class UserInfo {@ Sensitive (type = SensitiveTypeEnum.NAME) private String name; @ Sensitive (type = SensitiveTypeEnum.ID_NUM) private String idNum; @ Sensitive (type = SensitiveTypeEnum.PHONE_NUM) private String phone; @ Sensitive (type = SensitiveTypeEnum.CUSTOMER, prefixNoMaskLen = 3, suffixNoMaskLen = 2, symbol = "#") private String address; @ Sensitive (prefixNoMaskLen = 1, suffixNoMaskLen = 2, symbol = "*") private String password;}

If you have any questions, I have written a demo, you can download it and run it.

Link: desensitization note demo.

An efficient handwritten self-defined string desensitization annotation

The manager asked to write a custom desensitization note, Baidu checked a bunch. They are all relatively inefficient.

I wrote a reference only / * description: data desensitization * 1, default no position, all fields desensitized when the number of * symbols is not displayed * * the total length of the original string adminis calculates the total from 0 * index= (0Magne2) size = 1, that is, the character annotation "*" from 0 to 2 Size=1 only fills in a * size that cannot exceed the intercepted character * index= (2Magazine 3) size= 2 subscript that is a character annotation "*" from 2 to 3. For size=2, only two * size cannot exceed the intercepted characters * * date: 2020-3-13 15:56 * * @ author oakdog * @ version 1.0 * / @ Target ({ElementType.FIELD}) @ Retention (RetentionPolicy.RUNTIME) @ JacksonAnnotationsInside@JsonSerialize (using = Desensitization.ConvertDesensitization.class) public @ interface Desensitization {/ * incoming subscript index * the first starting subscript of the rule is End subscript default value 6-digit subscript * * / int [] index () default {0jue 6} / * * character length to be desensitized * enter 3: according to the index subscript index, desensitization corresponds to desensitization with a default length of 6 characters * * / int size () default 6; class ConvertDesensitization extends StdSerializer implements ContextualSerializer {private int [] index; private int size; public ConvertDesensitization () {super (Object.class) } private ConvertDesensitization (int [] index,int size) {super (Object.class); this.size = size; this.index = index;} @ Override public void serialize (Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {char [] str = value.toString () .toCharArray () StringBuilder builder = new StringBuilder (); String char1 = (String) value; if (str.length > 0) {/ / character length extra long processing if (index [0])

< str.length && index[1] < str.length) { //使用默认初始值的脱敏处理 if(index[0] == 0) { //如果输入脱敏大小长度小于0或大于原始脱敏字符长度,则全脱敏字符 if (size < 0 || size < str.length) { char[] charStr = char1.substring(index[1], str.length).toCharArray(); char[] charStr1 = char1.substring(index[0], index[1]).toCharArray(); builder.append(charStr1); for (int i = 0; i < charStr.length; i++) { if(size >

I) {builder.append ("*");} else {builder.append (charstre [I]) } else {builder.append (getDefaultChar ((String) value, "left")) }} else {/ / intercept desensitization from the middle position / / if the input desensitization size length is less than 0 or greater than the original desensitization character length, the full desensitization character if (size)

< 0 || size < str.length) { char[] charStr = char1.substring(index[0], str.length - index[1] + 1).toCharArray(); //2 6-4 2 //中间截取部分 List prefix = getPrefix(index[0], (String) value); //List suffix = getSuffix(index[0],index[1], (String) value); for (Integer integer : prefix) { builder.append(str[integer]); } for (int i = 0; i < charStr.length; i++) { if (size >

I) {builder.append ("*");} else {builder.append (charstre [I]) }} char [] chars = Arrays.copyOfRange (str, index [1], str.length); builder.append (String.valueOf (chars)) } else {builder.append (getDefaultChar ((String) value, "right"));} else {/ / default processing builder.append (getDefaultChar ((String) value, "") }} jgen.writeString (builder.toString ());} / * * default padding method * @ param str original string * @ param position location * @ return * / String getDefaultChar (String str,String position) {char [] desensitizationStr = str.toCharArray () For (int iTuno Bandi)

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