配置 ASP.NET Core 数据保护Configure ASP.NET Core Data Protection

当数据保护系统已初始化时,它将基于操作环境应用 默认设置When the Data Protection system is initialized, it applies default settings based on the operational environment. 这些设置通常适用于在一台计算机上运行的应用程序。These settings are generally appropriate for apps running on a single machine. 在某些情况下,开发人员可能想要更改默认设置:There are cases where a developer may want to change the default settings:

  • 应用程序分布在多台计算机上。The app is spread across multiple machines.
  • 出于合规性原因。For compliance reasons.

在这些情况下,数据保护系统提供了丰富的配置 API。For these scenarios, the Data Protection system offers a rich configuration API.

警告

与配置文件类似,应使用适当的权限保护数据保护密钥环。Similar to configuration files, the data protection key ring should be protected using appropriate permissions. 你可以选择对静态密钥加密,但这不会阻止攻击者创建新密钥。You can choose to encrypt keys at rest, but this doesn't prevent attackers from creating new keys. 因此,应用的安全将受到影响。Consequently, your app's security is impacted. 使用数据保护配置的存储位置应该将其访问权限限制为应用本身,这与保护配置文件的方式类似。The storage location configured with Data Protection should have its access limited to the app itself, similar to the way you would protect configuration files. 例如,如果选择将密钥环存储在磁盘上,请使用文件系统权限。For example, if you choose to store your key ring on disk, use file system permissions. 确保你的 web 应用在其下运行的标识具有对该目录的读取、写入和创建访问权限。Ensure only the identity under which your web app runs has read, write, and create access to that directory. 如果使用 Azure Blob 存储,则只有 web 应用应能够在 Blob 存储中读取、写入或创建新条目等。If you use Azure Blob Storage, only the web app should have the ability to read, write, or create new entries in the blob store, etc.

扩展方法 AddDataProtection 返回 IDataProtectionBuilderThe extension method AddDataProtection returns an IDataProtectionBuilder. IDataProtectionBuilder 公开扩展方法,你可以将这些方法链接在一起来配置数据保护选项。IDataProtectionBuilder exposes extension methods that you can chain together to configure Data Protection options.

本文中使用的数据保护扩展插件需要以下 NuGet 包:The following NuGet packages are required for the Data Protection extensions used in this article:

ProtectKeysWithAzureKeyVaultProtectKeysWithAzureKeyVault

使用 CLI 登录到 Azure,例如:Log in to Azure using the CLI, for example:

az login

若要在 Azure Key Vault中存储密钥,请在类中配置 ProtectKeysWithAzureKeyVault 系统 StartupTo store keys in Azure Key Vault, configure the system with ProtectKeysWithAzureKeyVault in the Startup class. blobUriWithSasToken 应存储密钥文件的完整 URI。blobUriWithSasToken is the full URI where the key file should be stored. 此 URI 必须包含 SAS 令牌作为查询字符串参数:The URI must contain the SAS token as a query string parameter:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection()
        .PersistKeysToAzureBlobStorage(new Uri("<blobUriWithSasToken>"))
        .ProtectKeysWithAzureKeyVault(new Uri("<keyIdentifier>"), new DefaultAzureCredential());
}

将密钥环存储位置设置 (例如 PersistKeysToAzureBlobStorage) 。Set the key ring storage location (for example, PersistKeysToAzureBlobStorage). 必须设置位置,因为调用 ProtectKeysWithAzureKeyVault 实现了禁用自动数据保护设置的 IXmlEncryptor ,包括密钥环存储位置。The location must be set because calling ProtectKeysWithAzureKeyVault implements an IXmlEncryptor that disables automatic data protection settings, including the key ring storage location. 前面的示例使用 Azure Blob 存储来持久保存密钥环。The preceding example uses Azure Blob Storage to persist the key ring. 有关详细信息,请参阅 密钥存储提供程序: Azure 存储For more information, see Key storage providers: Azure Storage. 还可以通过 PersistKeysToFileSystem将密钥环保存到本地。You can also persist the key ring locally with PersistKeysToFileSystem.

keyIdentifier是用于密钥加密的密钥保管库密钥标识符。The keyIdentifier is the key vault key identifier used for key encryption. 例如,在中名为的密钥保管库中创建的密钥 dataprotection contosokeyvault 具有密钥标识符 https://contosokeyvault.vault.azure.net/keys/dataprotection/For example, a key created in key vault named dataprotection in the contosokeyvault has the key identifier https://contosokeyvault.vault.azure.net/keys/dataprotection/. 向应用提供对密钥保管库的 解包密钥包装密钥 权限。Provide the app with Unwrap Key and Wrap Key permissions to the key vault.

ProtectKeysWithAzureKeyVault 重载ProtectKeysWithAzureKeyVault overloads:

如果应用使用以前的 Azure 包 (Microsoft.AspNetCore.DataProtection.AzureStorageMicrosoft.AspNetCore.DataProtection.AzureKeyVault) 并结合了 Azure Key Vault 和 Azure 存储来存储和保护密钥,则 System.UriFormatException 会在密钥存储的 blob 不存在时引发。If the app uses the prior Azure packages (Microsoft.AspNetCore.DataProtection.AzureStorage and Microsoft.AspNetCore.DataProtection.AzureKeyVault) and a combination of Azure Key Vault and Azure Storage to store and protect keys, System.UriFormatException is thrown if the blob for key storage doesn't exist. 可以在 Azure 门户中运行应用之前手动创建 blob,也可以使用以下过程:The blob can be manually created ahead of running the app in the Azure portal, or use the following procedure:

  1. 删除对的调用,以便 ProtectKeysWithAzureKeyVault 在首次运行时创建 blob。Remove the call to ProtectKeysWithAzureKeyVault for the first run to create the blob in place.
  2. 将对的调用添加到 ProtectKeysWithAzureKeyVault 后面的运行。Add the call to ProtectKeysWithAzureKeyVault for subsequent runs.

ProtectKeysWithAzureKeyVault建议删除首次运行,因为它可确保创建的文件具有正确的架构和值。Removing ProtectKeysWithAzureKeyVault for the first run is advised, as it ensures that the file is created with the proper schema and values in place.

建议升级到 AspNetCore DataProtectionAspNetCore 包,因为如果 blob 不存在,则该 API 会自动创建该 blob 的包。We recommended upgrading to the Azure.Extensions.AspNetCore.DataProtection.Blobs and Azure.Extensions.AspNetCore.DataProtection.Keys packages because the API provided automatically creates the blob if it doesn't exist.

services.AddDataProtection()
    //This blob must already exist before the application is run
    .PersistKeysToAzureBlobStorage("<storage account connection string", "<key store container name>", "<key store blob name>")
    //Removing this line below for an initial run will ensure the file is created correctly
    .ProtectKeysWithAzureKeyVault(new Uri("<keyIdentifier>"), new DefaultAzureCredential());

PersistKeysToFileSystemPersistKeysToFileSystem

若要将密钥存储在 UNC 共享上,而不是存储在 % LOCALAPPDATA% 默认位置,请使用 PersistKeysToFileSystem配置系统:To store keys on a UNC share instead of at the %LOCALAPPDATA% default location, configure the system with PersistKeysToFileSystem:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection()
        .PersistKeysToFileSystem(new DirectoryInfo(@"\\server\share\directory\"));
}

警告

如果更改密钥持久性位置,系统将不再自动加密静态密钥,因为它不知道 DPAPI 是否为适当的加密机制。If you change the key persistence location, the system no longer automatically encrypts keys at rest, since it doesn't know whether DPAPI is an appropriate encryption mechanism.

ProtectKeysWith*ProtectKeysWith*

可以通过调用任何ProtectKeysWith * 配置 api 将系统配置为保护静态密钥。You can configure the system to protect keys at rest by calling any of the ProtectKeysWith* configuration APIs. 请考虑以下示例,该示例将密钥存储在 UNC 共享上,并使用特定的 x.509 证书对静态密钥进行加密:Consider the example below, which stores keys on a UNC share and encrypts those keys at rest with a specific X.509 certificate:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection()
        .PersistKeysToFileSystem(new DirectoryInfo(@"\\server\share\directory\"))
        .ProtectKeysWithCertificate(Configuration["Thumbprint"]);
}

在 ASP.NET Core 2.1 或更高版本中,你可以提供ProtectKeysWithCertificateX509Certificate2 ,例如从文件中加载的证书:In ASP.NET Core 2.1 or later, you can provide an X509Certificate2 to ProtectKeysWithCertificate, such as a certificate loaded from a file:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection()
        .PersistKeysToFileSystem(new DirectoryInfo(@"\\server\share\directory\"))
        .ProtectKeysWithCertificate(
            new X509Certificate2("certificate.pfx", Configuration["Thumbprint"]));
}

有关内置密钥加密机制的更多示例和讨论,请参阅 静态密钥加密See Key Encryption At Rest for more examples and discussion on the built-in key encryption mechanisms.

UnprotectKeysWithAnyCertificateUnprotectKeysWithAnyCertificate

在 ASP.NET Core 2.1 或更高版本中,你可以使用UnprotectKeysWithAnyCertificateX509Certificate2In ASP.NET Core 2.1 or later, you can rotate certificates and decrypt keys at rest using an array of X509Certificate2 certificates with UnprotectKeysWithAnyCertificate:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection()
        .PersistKeysToFileSystem(new DirectoryInfo(@"\\server\share\directory\"))
        .ProtectKeysWithCertificate(
            new X509Certificate2("certificate.pfx", Configuration["MyPasswordKey"));
        .UnprotectKeysWithAnyCertificate(
            new X509Certificate2("certificate_old_1.pfx", Configuration["MyPasswordKey_1"),
            new X509Certificate2("certificate_old_2.pfx", Configuration["MyPasswordKey_2"));
}

SetDefaultKeyLifetimeSetDefaultKeyLifetime

若要将系统配置为使用14天的密钥生存期而不是默认的90天,请使用 SetDefaultKeyLifetimeTo configure the system to use a key lifetime of 14 days instead of the default 90 days, use SetDefaultKeyLifetime:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection()
        .SetDefaultKeyLifetime(TimeSpan.FromDays(14));
}

SetApplicationNameSetApplicationName

默认情况下,数据保护系统基于其 内容根 路径将应用彼此隔离,即使它们共享相同的物理密钥存储库。By default, the Data Protection system isolates apps from one another based on their content root paths, even if they're sharing the same physical key repository. 这可防止应用了解彼此的受保护负载。This prevents the apps from understanding each other's protected payloads.

在应用之间共享受保护的负载:To share protected payloads among apps:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection()
        .SetApplicationName("shared app name");
}

DisableAutomaticKeyGenerationDisableAutomaticKeyGeneration

你可能会遇到这样的情况:你不希望应用程序自动滚动更新密钥 (创建新密钥) ,因为它们接近过期。You may have a scenario where you don't want an app to automatically roll keys (create new keys) as they approach expiration. 这种情况的一个示例可能是在主/辅助关系中设置的应用,其中只有主应用负责密钥管理问题,辅助应用只是具有密钥环的只读视图。One example of this might be apps set up in a primary/secondary relationship, where only the primary app is responsible for key management concerns and secondary apps simply have a read-only view of the key ring. 可以将辅助应用配置为使用以下配置系统将密钥环视为只读 DisableAutomaticKeyGenerationThe secondary apps can be configured to treat the key ring as read-only by configuring the system with DisableAutomaticKeyGeneration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDataProtection()
        .DisableAutomaticKeyGeneration();
}

每应用程序隔离Per-application isolation

当数据保护系统由 ASP.NET Core 主机提供时,它会自动将应用彼此隔离,即使这些应用在相同的工作进程帐户下运行并且使用相同的主密钥材料也是如此。When the Data Protection system is provided by an ASP.NET Core host, it automatically isolates apps from one another, even if those apps are running under the same worker process account and are using the same master keying material. 这有点类似于 System.web 元素中的 IsolateApps 修饰符 <machineKey>This is somewhat similar to the IsolateApps modifier from System.Web's <machineKey> element.

隔离机制的工作原理是将本地计算机上的每个应用视为唯一的租户,因此, IDataProtector 任何给定应用的根都将自动包括应用 ID 作为鉴别器。The isolation mechanism works by considering each app on the local machine as a unique tenant, thus the IDataProtector rooted for any given app automatically includes the app ID as a discriminator. 应用的唯一 ID 是应用的物理路径:The app's unique ID is the app's physical path:

  • 对于在 IIS 中托管的应用,唯一 ID 是应用的 IIS 物理路径。For apps hosted in IIS, the unique ID is the IIS physical path of the app. 如果在 web 场环境中部署了应用,则此值是稳定的,假定在 web 场中的所有计算机上配置了类似的 IIS 环境。If an app is deployed in a web farm environment, this value is stable assuming that the IIS environments are configured similarly across all machines in the web farm.
  • 对于在 Kestrel 服务器上运行的自承载应用程序,唯一 ID 是指向磁盘上的应用程序的物理路径。For self-hosted apps running on the Kestrel server, the unique ID is the physical path to the app on disk.

唯一标识符旨在重置 — 单独的应用程序和计算机本身。The unique identifier is designed to survive resets—both of the individual app and of the machine itself.

此隔离机制假定应用不是恶意的。This isolation mechanism assumes that the apps are not malicious. 恶意应用始终会影响在同一工作进程帐户下运行的任何其他应用。A malicious app can always impact any other app running under the same worker process account. 在应用不受信任的共享主机环境中,托管提供商应采取措施来确保应用之间的操作系统级隔离,包括分离应用程序的底层密钥存储库。In a shared hosting environment where apps are mutually untrusted, the hosting provider should take steps to ensure OS-level isolation between apps, including separating the apps' underlying key repositories.

如果 ASP.NET Core 主机未提供数据保护系统 (例如,如果通过具体类型对其进行实例化 DataProtectionProvider) 则默认情况下禁用应用程序隔离。If the Data Protection system isn't provided by an ASP.NET Core host (for example, if you instantiate it via the DataProtectionProvider concrete type) app isolation is disabled by default. 禁用应用隔离后,只要提供相应的 用途,同一密钥材料支持的所有应用就可以共享有效负载。When app isolation is disabled, all apps backed by the same keying material can share payloads as long as they provide the appropriate purposes. 若要在此环境中提供应用隔离,请对配置对象调用 SetApplicationName 方法,并为每个应用提供唯一的名称。To provide app isolation in this environment, call the SetApplicationName method on the configuration object and provide a unique name for each app.

用 UseCryptographicAlgorithms 更改算法Changing algorithms with UseCryptographicAlgorithms

数据保护堆栈允许您更改新生成的密钥使用的默认算法。The Data Protection stack allows you to change the default algorithm used by newly-generated keys. 执行此操作的最简单方法是从配置回调调用 UseCryptographicAlgorithmsThe simplest way to do this is to call UseCryptographicAlgorithms from the configuration callback:

services.AddDataProtection()
    .UseCryptographicAlgorithms(
        new AuthenticatedEncryptorConfiguration()
    {
        EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
        ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
    });
services.AddDataProtection()
    .UseCryptographicAlgorithms(
        new AuthenticatedEncryptionSettings()
    {
        EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
        ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
    });

默认 EncryptionAlgorithm 为 AES-256-CBC,默认 ValidationAlgorithm 为 HMACSHA256。The default EncryptionAlgorithm is AES-256-CBC, and the default ValidationAlgorithm is HMACSHA256. 系统管理员可以通过 计算机范围内的策略来设置默认策略,但会对 UseCryptographicAlgorithms 替代默认策略进行显式调用。The default policy can be set by a system administrator via a machine-wide policy, but an explicit call to UseCryptographicAlgorithms overrides the default policy.

通过调用, UseCryptographicAlgorithms 可以从预定义的内置列表中指定所需的算法。Calling UseCryptographicAlgorithms allows you to specify the desired algorithm from a predefined built-in list. 您无需担心算法的实现。You don't need to worry about the implementation of the algorithm. 在上述方案中,如果在 Windows 上运行,数据保护系统将尝试使用 AES 的 CNG 实现。In the scenario above, the Data Protection system attempts to use the CNG implementation of AES if running on Windows. 否则,它会回退到托管的系统。Otherwise, it falls back to the managed System.Security.Cryptography.Aes class.

可以通过调用 UseCustomCryptographicAlgorithms手动指定实现。You can manually specify an implementation via a call to UseCustomCryptographicAlgorithms.

提示

更改算法不会影响密钥环中的现有密钥。Changing algorithms doesn't affect existing keys in the key ring. 它仅影响新生成的键。It only affects newly-generated keys.

指定自定义托管算法Specifying custom managed algorithms

若要指定自定义托管算法,请创建一个指向实现类型的 ManagedAuthenticatedEncryptorConfiguration 实例:To specify custom managed algorithms, create a ManagedAuthenticatedEncryptorConfiguration instance that points to the implementation types:

serviceCollection.AddDataProtection()
    .UseCustomCryptographicAlgorithms(
        new ManagedAuthenticatedEncryptorConfiguration()
    {
        // A type that subclasses SymmetricAlgorithm
        EncryptionAlgorithmType = typeof(Aes),

        // Specified in bits
        EncryptionAlgorithmKeySize = 256,

        // A type that subclasses KeyedHashAlgorithm
        ValidationAlgorithmType = typeof(HMACSHA256)
    });

若要指定自定义托管算法,请创建一个指向实现类型的 ManagedAuthenticatedEncryptionSettings 实例:To specify custom managed algorithms, create a ManagedAuthenticatedEncryptionSettings instance that points to the implementation types:

serviceCollection.AddDataProtection()
    .UseCustomCryptographicAlgorithms(
        new ManagedAuthenticatedEncryptionSettings()
    {
        // A type that subclasses SymmetricAlgorithm
        EncryptionAlgorithmType = typeof(Aes),

        // Specified in bits
        EncryptionAlgorithmKeySize = 256,

        // A type that subclasses KeyedHashAlgorithm
        ValidationAlgorithmType = typeof(HMACSHA256)
    });

通常, * 类型属性必须指向具体的可实例化 (通过 System.security.cryptography.symmetricalgorithmKeyedHashAlgorithm的公共无参数的) ctor 实现,尽管系统特别适用于一些值, typeof(Aes) 以便于方便。Generally the *Type properties must point to concrete, instantiable (via a public parameterless ctor) implementations of SymmetricAlgorithm and KeyedHashAlgorithm, though the system special-cases some values like typeof(Aes) for convenience.

备注

System.security.cryptography.symmetricalgorithm 必须具有≥128位的密钥长度和≥64位的块大小,并且必须支持 PKCS #7 填充的 CBC 模式加密。The SymmetricAlgorithm must have a key length of ≥ 128 bits and a block size of ≥ 64 bits, and it must support CBC-mode encryption with PKCS #7 padding. KeyedHashAlgorithm 的摘要大小必须为 >= 128 位,并且它必须支持长度等于哈希算法摘要长度的键。The KeyedHashAlgorithm must have a digest size of >= 128 bits, and it must support keys of length equal to the hash algorithm's digest length. KeyedHashAlgorithm 不一定是 HMAC。The KeyedHashAlgorithm isn't strictly required to be HMAC.

指定自定义 Windows CNG 算法Specifying custom Windows CNG algorithms

若要通过 HMAC 验证使用 CBC 模式加密指定自定义 Windows CNG 算法,请创建包含算法信息的 CngCbcAuthenticatedEncryptorConfiguration 实例:To specify a custom Windows CNG algorithm using CBC-mode encryption with HMAC validation, create a CngCbcAuthenticatedEncryptorConfiguration instance that contains the algorithmic information:

services.AddDataProtection()
    .UseCustomCryptographicAlgorithms(
        new CngCbcAuthenticatedEncryptorConfiguration()
    {
        // Passed to BCryptOpenAlgorithmProvider
        EncryptionAlgorithm = "AES",
        EncryptionAlgorithmProvider = null,

        // Specified in bits
        EncryptionAlgorithmKeySize = 256,

        // Passed to BCryptOpenAlgorithmProvider
        HashAlgorithm = "SHA256",
        HashAlgorithmProvider = null
    });

若要通过 HMAC 验证使用 CBC 模式加密指定自定义 Windows CNG 算法,请创建包含算法信息的 CngCbcAuthenticatedEncryptionSettings 实例:To specify a custom Windows CNG algorithm using CBC-mode encryption with HMAC validation, create a CngCbcAuthenticatedEncryptionSettings instance that contains the algorithmic information:

services.AddDataProtection()
    .UseCustomCryptographicAlgorithms(
        new CngCbcAuthenticatedEncryptionSettings()
    {
        // Passed to BCryptOpenAlgorithmProvider
        EncryptionAlgorithm = "AES",
        EncryptionAlgorithmProvider = null,

        // Specified in bits
        EncryptionAlgorithmKeySize = 256,

        // Passed to BCryptOpenAlgorithmProvider
        HashAlgorithm = "SHA256",
        HashAlgorithmProvider = null
    });

备注

对称块加密算法的密钥长度必须为 >= 128 位,块大小为 >= 64 位,并且它必须支持 PKCS #7 填充的 CBC 模式加密。The symmetric block cipher algorithm must have a key length of >= 128 bits, a block size of >= 64 bits, and it must support CBC-mode encryption with PKCS #7 padding. 哈希算法的摘要大小必须为 >= 128 位,并且必须支持使用 BCRYPT _ ALG _ 句柄 _ HMAC _ 标志标志打开。The hash algorithm must have a digest size of >= 128 bits and must support being opened with the BCRYPT_ALG_HANDLE_HMAC_FLAG flag. *提供程序属性可以设置为 null,以将默认提供程序用于指定的算法。The *Provider properties can be set to null to use the default provider for the specified algorithm. 有关详细信息,请参阅 BCryptOpenAlgorithmProvider 文档。See the BCryptOpenAlgorithmProvider documentation for more information.

若要使用 Galois/Counter 模式加密和验证来指定自定义 Windows CNG 算法,请创建包含算法信息的 CngGcmAuthenticatedEncryptorConfiguration 实例:To specify a custom Windows CNG algorithm using Galois/Counter Mode encryption with validation, create a CngGcmAuthenticatedEncryptorConfiguration instance that contains the algorithmic information:

services.AddDataProtection()
    .UseCustomCryptographicAlgorithms(
        new CngGcmAuthenticatedEncryptorConfiguration()
    {
        // Passed to BCryptOpenAlgorithmProvider
        EncryptionAlgorithm = "AES",
        EncryptionAlgorithmProvider = null,

        // Specified in bits
        EncryptionAlgorithmKeySize = 256
    });

若要使用 Galois/Counter 模式加密和验证来指定自定义 Windows CNG 算法,请创建包含算法信息的 CngGcmAuthenticatedEncryptionSettings 实例:To specify a custom Windows CNG algorithm using Galois/Counter Mode encryption with validation, create a CngGcmAuthenticatedEncryptionSettings instance that contains the algorithmic information:

services.AddDataProtection()
    .UseCustomCryptographicAlgorithms(
        new CngGcmAuthenticatedEncryptionSettings()
    {
        // Passed to BCryptOpenAlgorithmProvider
        EncryptionAlgorithm = "AES",
        EncryptionAlgorithmProvider = null,

        // Specified in bits
        EncryptionAlgorithmKeySize = 256
    });

备注

对称块密码算法的密钥长度必须为 >= 128 位,块大小正好为128位,并且必须支持 GCM 加密。The symmetric block cipher algorithm must have a key length of >= 128 bits, a block size of exactly 128 bits, and it must support GCM encryption. 可以将 EncryptionAlgorithmProvider 属性设置为 null,以将默认提供程序用于指定的算法。You can set the EncryptionAlgorithmProvider property to null to use the default provider for the specified algorithm. 有关详细信息,请参阅 BCryptOpenAlgorithmProvider 文档。See the BCryptOpenAlgorithmProvider documentation for more information.

指定其他自定义算法Specifying other custom algorithms

尽管不是作为第一类 API 公开的,但数据保护系统的扩展能力足以允许指定几乎任何类型的算法。Though not exposed as a first-class API, the Data Protection system is extensible enough to allow specifying almost any kind of algorithm. 例如,可以将硬件安全模块中包含的所有密钥保留 (HSM) ,并提供核心加密和解密例程的自定义实现。For example, it's possible to keep all keys contained within a Hardware Security Module (HSM) and to provide a custom implementation of the core encryption and decryption routines. 有关详细信息,请参阅核心加密扩展性中的IAuthenticatedEncryptorSee IAuthenticatedEncryptor in Core cryptography extensibility for more information.

在 Docker 容器中托管时保持密钥Persisting keys when hosting in a Docker container

Docker 容器中托管时,应在以下任一项中维护密钥:When hosting in a Docker container, keys should be maintained in either:

  • 一个文件夹,它是在容器的生存期之外保留的 Docker 卷,如共享卷或主机装入的卷。A folder that's a Docker volume that persists beyond the container's lifetime, such as a shared volume or a host-mounted volume.
  • 外部提供程序,如 Azure Key VaultRedisAn external provider, such as Azure Key Vault or Redis.

通过 Redis 保持密钥Persisting keys with Redis

只应使用支持 Redis 数据暂留 的 Redis 版本来存储密钥。Only Redis versions supporting Redis Data Persistence should be used to store keys. Azure Blob 存储 是持久性的,可用于存储密钥。Azure Blob storage is persistent and can be used to store keys. 有关详细信息,请参阅此 GitHub 问题For more information, see this GitHub issue.

其他资源Additional resources