项目开发中,基于对用户隐私保护的考虑,需要对敏感信息进行加密显示,使用特殊字符代替字符中间字符。如手机号,身份证号,姓名等,以下为隐藏字符串的实现:
/// <summary>
/// 将传入的字符串中间部分字符替换成特殊字符.
/// </summary>
/// <param name="number">要替换的字符串</param>
/// <param name="startLen">前保留长度</param>
/// <param name="endLen">尾部保留长度</param>
/// <param name="replaceChar">替换的特殊字符</param>
/// <returns></returns>
public static string HideString(string number, int startLen, int endLen, char replaceChar = '*') { try { if (string.IsNullOrWhiteSpace(number)) { number = string.Empty; } else { int length = number.Length - startLen - endLen; string replaceStr = number.Substring(startLen, length); string specialStr = string.Empty; for (int i = 0; i < replaceStr.Length; i++) { specialStr += replaceChar; } number = number.Replace(replaceStr, specialStr); } } catch (Exception e) { throw; } return number; }
隐藏手机号方式二:
public static string HidePhone(string phone) { if (string.IsNullOrWhiteSpace(phone)) { return string.Empty; } if (phone.Length == 11) { return $"{phone.Substring(0, 3)}****{phone.Substring(7, 4)}"; } int hideLength = (int)Math.Floor((double)phone.Length / 2); int displayLength = phone.Length - hideLength; int displayHalfLength = (int)Math.Floor((double)displayLength / 2); int prefixLength = displayHalfLength; int suffixLength = displayLength - prefixLength; return $"{phone.Substring(0, displayHalfLength).PadRight(prefixLength + hideLength, '*')}{phone.Substring(phone.Length - suffixLength, suffixLength)}"; }