方案一:
DTO中处理:
private string idNumber; /// <summary> /// 身份证号码 /// </summary> [Column("id_number")] public string IdNumber { get { return idNumber; } set { idNumber = SensitiveHelper.GetIdNumber(value); } }
方案二:
业务层处理:
核心方法如下:
/// <summary> /// 根据输入参数T中的特性,对属性进行敏感数据处理 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="source"></param> /// <returns></returns> public static List<T> GetSensitiveResult<T>(List<T> source) { if (!SysConfigHelper.Instance.GetBool("Para")) { return source; } List<PropertyInfo> props = GetPropertyInfos<SensitiveAttribute>(typeof(T)); if (props.Count() > 0) { source.ForEach(r => { foreach (var prop in props) { var p = prop.GetCustomAttributes(true).OfType<SensitiveAttribute>().FirstOrDefault(); var accesor = new PropertyAccessor(typeof(T), prop.Name); var value = accesor.Get(r)?.ToString(); switch (p.SensitiveType) { case SensitiveType.IdNumber: accesor.Set(r, GetSensitiveIdNumber(value)); break; case SensitiveType.Name: accesor.Set(r, GetSensitiveName(value)); break; default: break; } } }); } return source; } /// <summary> /// 姓名敏感处理 /// </summary> /// <param name="fullName"></param> /// <returns></returns> public static string GetSensitiveName(string fullName) {if (string.IsNullOrEmpty(fullName)) { return ""; } string familyName = fullName.Substring(0, 1); return familyName.PadRight(fullName.Length - 1, '*'); } /// <summary> /// 证件号码敏感处理 /// </summary> /// <param name="idNumber"></param> /// <returns></returns> public static string GetSensitiveIdNumber(string idNumber) {if (string.IsNullOrEmpty(idNumber)) { return ""; } string number = idNumber.Substring(0, 6); return number.PadRight(idNumber.Length - 6, '*'); }
在第一个方法中的类型T中,需要对要敏感处理的属性增加特性Attribute
public class SensitiveAttribute: Attribute { #region Fields public SensitiveType SensitiveType { get; set; } #endregion #region Constructors and Destructors public SensitiveAttribute() { } public SensitiveAttribute(SensitiveType type) { this.SensitiveType = type; } #endregion #region Public Methods and Operators #endregion } public enum SensitiveType { Name, IdNumber }
在DTO中使用:
[Sensitive(SensitiveType.Name)] public string BillPatientName { get; set; }
两个方案各有利弊:
方案一:
优点:性能最好,不需要再循环对数据进行处理。
缺点:不推荐在DTO中的get,set方法中写逻辑。
方案二:
优点:方法简单,各司其职
缺点:性能不高。
最终我们选择的方案一,希望有高手指点。