項目開發中,基於對用戶隱私保護的考慮,需要對敏感信息進行加密顯示,使用特殊字符代替字符中間字符。如手機號,身份證號,姓名等,以下為隱藏字符串的實現:
/// <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; }
上述方法如果輸入字符串為“11111111”或者不進行替換時,程序會出錯。改進程序如下:
public static string HideString(string str, int startLen, int endLen, char replaceChar = '*') { if (string.IsNullOrWhiteSpace(str)) { return string.Empty; } try { int length = str.Length - startLen - endLen; var startStr = str.Substring(0, startLen); var endStr = str.Substring(str.Length - endLen, endLen); var hideStr = string.Empty.PadLeft(length, replaceChar); return $"{startStr}{hideStr}{endStr}"; } catch (Exception ex) { NLogManager.LogWarn(ex); return string.Empty; } }
隱藏手機號方式二:
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)}"; }