using System; namespace WebApiClientCore.Masking.Strategies { /// /// 表示保留前后若干位,中间用掩码替换的脱敏策略 /// public sealed class TruncateMaskStrategy : IMaskStrategy { /// /// 获取内置策略的名称 /// public const string StrategyName = "Truncate"; /// /// 获取保留的起始位数 /// public int KeepStart { get; } /// /// 获取保留的末尾位数 /// public int KeepEnd { get; } /// /// 获取中间部分的掩码 /// public string MaskText { get; } /// /// 获取策略名称 /// public string Name { get; } /// /// 保留前后若干位,中间用掩码替换的脱敏策略 /// /// 保留的起始位数 /// 保留的末尾位数 /// 中间部分的掩码 /// 策略名称,默认为 Truncate /// /// public TruncateMaskStrategy(int keepStart = 3, int keepEnd = 4, string maskText = "***", string? name = null) { if (keepStart < 0) { throw new ArgumentOutOfRangeException(nameof(keepStart)); } if (keepEnd < 0) { throw new ArgumentOutOfRangeException(nameof(keepEnd)); } this.KeepStart = keepStart; this.KeepEnd = keepEnd; this.MaskText = maskText ?? throw new ArgumentNullException(nameof(maskText)); this.Name = string.IsNullOrWhiteSpace(name) == true ? StrategyName : name!; } /// /// 保留前后若干位,中间用掩码替换 /// /// 字段值 /// public string Mask(string value) { if (value.Length <= this.KeepStart + this.KeepEnd) { return value; } var head = value.Substring(0, this.KeepStart); var tail = value.Substring(value.Length - this.KeepEnd); return $"{head}{this.MaskText}{tail}"; } } }