隐藏手机号、邮箱等敏感信息
Intro
做项目的时候,页面上有一些敏感信息,需要用“*”隐藏一些比较重要的信息,于是打算写一个通用的方法。
Let's do it !
Method 1:指定左右字符数量
Method 1.1 中间的*的个数和实际长度有关
1 /// <summary> 2 /// 隐藏敏感信息 3 </summary> 4 <param name="info">信息实体</param> 5 <param name="left">左边保留的字符数 6 <param name="right">右边保留的字符数 7 <param name="basedOnLeft">当长度异常时,是否显示左边 8 <code>true</code>显示左边,false显示右边 9 10 <returns></returns> 11 public static string HideSensitiveInfo(string info,int left,1)">int right,1)">bool basedOnLeft=true) 12 { 13 if (String.IsNullOrEmpty(info)) 14 { 15 return ""; 16 } 17 StringBuilder sbText = new StringBuilder(); 18 int hiddenCharCount = info.Length - left - right; 19 if (hiddenCharCount > 020 21 string prefix = info.Substring(0,left),suffix = info.Substring(info.Length - right); 22 sbText.Append(prefix); 23 for (int i = 0; i < hiddenCharCount; i++24 { 25 sbText.Append("*"); 26 } 27 sbText.Append(suffix); 28 29 else 30 31 (basedOnLeft) 32 33 if (info.Length > left && left > 34 { 35 sbText.Append(info.Substring(****36 } 37 38 39 sbText.Append(info.Substring(1) + 40 41 42 43 44 if (info.Length > right && right > 45 46 sbText.Append(" + info.Substring(info.Length - right)); 47 48 49 50 sbText.Append(" + info.Substring(info.Length - 1)); 51 52 53 54 return sbText.ToString(); 55 }
Method 1.2 : 中间的*的个数固定
10 string HideSensitiveInfo1(bool basedOnLeft = 11 12 13 14 15 16 StringBuilder sbText = 17 19 20 21 22 sbText.Append(23 25 27 29 if (info.Length > left && left >31 sbText.Append(info.Substring(37 38 39 40 if (info.Length > right && right>42 sbText.Append(48 50 51 }
Method 2 : “*”数量一定,设置为4个,按信息总长度的比例来取,默认左右各取1/3
信息<param name="sublen">信息总长与左子串(或右子串)的比例当长度异常时,是否显示左边,默认true,默认显示左边 9 int sublen = 3,1)">10 11 13 15 if (sublen<=17 sublen = 318 int subLength = info.Length / sublen; 20 if (subLength > 0 && info.Length > (subLength*2) ) 22 subLength); return prefix + " + suffix; string prefix = subLength > 0 ? info.Substring(30 31 32 33 34 string suffix = subLength > 0 ? info.Substring(info.Length-subLength) : info.Substring(info.Length-35 "+suffix; 38 }
扩展
手机号 1
隐藏手机号详情 <param name="phone">手机号左边保留字符数右边保留字符数 8 string HideTelDetails(string phone,1)">int left = int right = 4 9 10 HideSensitiveInfo(phone,left,right); 11 }
测试结果如下:
手机号 2
HideSensitiveInfo1(phone,1)">11 }
测试结果如下:
邮件地址
隐藏右键详情 <param name="email">邮件地址邮件头保留字符个数,默认值设置为3 7 string HideEmailDetails(string email,1)"> 8 9 (String.IsNullOrEmpty(email)) 11 if (System.Text.RegularExpressions.Regex.IsMatch(email,1)">@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))//如果是邮件地址 int suffixLen =email.Length - email.LastIndexOf('@'16 return HideSensitiveInfo(email,suffixLen,1)">false17 HideSensitiveInfo(email); 22 }
测试结果如下:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。