.NET 中的数据编辑

修订有助于清理或屏蔽日志、错误消息或其他输出中的敏感信息。 这可让你遵守隐私规则并保护敏感数据。 它适用于处理个人数据、财务信息或其他机密数据点的应用。

安装修订包

若要开始,请安装 📦 Microsoft.Extensions.Compliance.Redaction NuGet 包:

dotnet add package Microsoft.Extensions.Compliance.Redaction

或者,如果使用的是 .NET 10+ SDK:

dotnet package add Microsoft.Extensions.Compliance.Redaction

可用的编辑器

编修器负责编辑敏感数据。 它们对敏感信息进行修订、替换或掩码。 请考虑图书馆提供的以下可用编辑器:

用法示例

要使用内置编辑器,必须注册所需的服务。 按照以下列表中所述,使用可用 AddRedaction 方法之一注册服务:

配置编辑器

使用 IRedactorProvider 在运行时提取编修器。 你可以实现自己的提供程序,并在 AddRedaction 调用中注册它,或者使用默认提供程序。 使用以下 IRedactionBuilder 方法配置编辑器:

// This will use the default redactor, which is the ErasingRedactor
var serviceCollection = new ServiceCollection();
serviceCollection.AddRedaction();

// Using the default redactor provider:
serviceCollection.AddRedaction(redactionBuilder =>
{
    // Assign a redactor to use for a set of data classifications.
    redactionBuilder.SetRedactor<StarRedactor>(
        MyTaxonomyClassifications.Private,
        MyTaxonomyClassifications.Personal);
    // Assign a fallback redactor to use when processing classified data for which no specific redactor has been registered.
    // The `ErasingRedactor` is the default fallback redactor. If no redactor is configured for a data classification then the data will be erased.
    redactionBuilder.SetFallbackRedactor<MyFallbackRedactor>();
});

// Using a custom redactor provider:
builder.Services.AddSingleton<IRedactorProvider, StarRedactorProvider>();

在代码中给定此数据分类:

public static class MyTaxonomyClassifications
{
    public static string Name => "MyTaxonomy";

    public static DataClassification Private => new(Name, nameof(Private));
    public static DataClassification Public => new(Name, nameof(Public));
    public static DataClassification Personal => new(Name, nameof(Personal));
}

配置 HMAC 编辑器

使用这些 IRedactionBuilder 方法配置 HMAC 编辑器:

var serviceCollection = new ServiceCollection();
serviceCollection.AddRedaction(builder =>
{
    builder.SetHmacRedactor(
        options =>
        {
            options.KeyId = 1234567890;
            options.Key = Convert.ToBase64String("1234567890abcdefghijklmnopqrstuvwxyz");
        },

        // Any data tagged with Personal or Private attributes will be redacted by the Hmac redactor.
        MyTaxonomyClassifications.Personal, MyTaxonomyClassifications.Private,

        // "DataClassificationSet" lets you compose multiple data classifications:
        // For example, here the Hmac redactor will be used for data tagged
        // with BOTH Personal and Private (but not one without the other).
        new DataClassificationSet(MyTaxonomyClassifications.Personal,
                                  MyTaxonomyClassifications.Private));
});

或者,按以下方式对其进行配置:

var serviceCollection = new ServiceCollection();
serviceCollection.AddRedaction(builder =>
{
    builder.SetHmacRedactor(
        Configuration.GetSection("HmacRedactorOptions"), MyTaxonomyClassifications.Personal);
});

在 JSON 配置文件中包含此部分:

{
    "HmacRedactorOptions": {
        "KeyId": 1234567890,
        "Key": "1234567890abcdefghijklmnopqrstuvwxyz"
    }
}
  • HmacRedactorOptions 需要将其 HmacRedactorOptions.KeyHmacRedactorOptions.KeyId 属性设置。
  • Key 应采用 base 64 格式,并且长度至少为 44 个字符。 对服务的每个主要部署使用不同的密钥。 保留密钥材料机密并定期轮换密钥。
  • KeyId 追加到每个经过修订的值,以标识用于对数据进行哈希处理的键。
  • 不同的键 ID 表示值不相关,不能用于关联。

注释

HmacRedactor 仍然是实验性的,因此上述方法将导致 EXTEXP0002 警告,指示它尚不稳定。 若要使用它,请将<NoWarn>$(NoWarn);EXTEXP0002</NoWarn>添加到项目文件中,或在对#pragma warning disable EXTEXP0002的调用周围添加SetHmacRedactor

配置自定义编辑器

要创建一个自定义编辑器,请定义一个从 Redactor 继承的子类。

public sealed class StarRedactor : Redactor

public class StarRedactor : Redactor
{
    private const string Stars = "****";

    public override int GetRedactedLength(ReadOnlySpan<char> input) => Stars.Length;

    public override int Redact(ReadOnlySpan<char> source, Span<char> destination)
    {
        Stars.CopyTo(destination);

        return Stars.Length;
    }
}

创建自定义编修器提供程序

IRedactorProvider 接口提供基于数据分类的编辑器实例。 若要创建自定义编辑器提供程序,请如以下示例所示继承自 IRedactorProvider

using Microsoft.Extensions.Compliance.Classification;
using Microsoft.Extensions.Compliance.Redaction;

public sealed class StarRedactorProvider : IRedactorProvider
{
    private static readonly StarRedactor _starRedactor = new();

    public static StarRedactorProvider Instance { get; } = new();

    public Redactor GetRedactor(DataClassificationSet classifications) => _starRedactor;
}

记录敏感信息

日志记录是意外数据泄露的常见来源。 不应以纯文本形式将敏感信息(如个人数据、凭据或财务详细信息)写入日志。 若要防止出现这种情况,请始终在记录潜在敏感数据时使用修订。

记录敏感数据的步骤

  1. 安装遥测扩展包:安装Microsoft.Extensions.Telemetry ,以便能够使用扩展记录器启用修订功能。
  2. 设置修订:通过调用 AddRedaction(IServiceCollection) 方法将 redactors 与日志记录管道集成,以便在将敏感字段写入日志之前自动清理或屏蔽敏感字段。
  3. 识别敏感字段:知道应用程序中哪些数据很敏感,需要保护,并使用适当的数据分类对其进行标记。
  4. 查看日志输出:定期审核日志,以确保不会公开任何敏感数据。

示例:对日志中的数据进行修订

使用 Microsoft.Extensions.Logging 时,可以将修订与日志记录相结合,如下所示:

using Microsoft.Extensions.Telemetry;
using Microsoft.Extensions.Compliance.Redaction;

var services = new ServiceCollection();
services.AddLogging(builder =>
{
    // Enable redaction.
    builder.EnableRedaction();
});

services.AddRedaction(builder =>
{
    // configure redactors for your data classifications
    builder.SetRedactor<StarRedactor>(MyTaxonomyClassifications.Private);
});
// Use annotations to mark sensitive data.
// For example, apply the Private classification to SSN data.
[LoggerMessage(0, LogLevel.Information, "User SSN: {SSN}")]
public static partial void LogPrivateInformation(
    this ILogger logger,
    [MyTaxonomyClassifications.Private] string SSN);

public void TestLogging()
{
    LogPrivateInformation("MySSN");
}

输出应如下所示:

User SSN: *****

这可确保在记录之前对敏感数据进行修订,从而减少数据泄漏的风险。