ASP.NET Core 数据保护(Data Protection)中篇(2)

有些时候,我们需要一些具有过期或者到期时间的加密字符串,比如一个用户在找回密码的时候,我们向用户的邮箱发送一封带有重置命令的一封邮件,这个重置命令就需要有一个过期时间了,超过这个过期时间后就失效,在以前我们可能需要向数据库存储一个时间来标记发送时间,然后再解密对比和数据库的时间差来验证。 

现在我们不需要这么做了,ASP.NET Core 默认提供了一个接口叫 ITimeLimitedDataProtector ,我们先看一下这个接口的定义:

CreateProtector(string purpose) : ITimeLimitedDataProtector This API is similar to the existing IDataProtectionProvider.CreateProtector in that it can be used to create purpose chains from a root time-limited protector. Protect(byte[] plaintext, DateTimeOffset expiration) : byte[] Protect(byte[] plaintext, TimeSpan lifetime) : byte[] Protect(byte[] plaintext) : byte[] Protect(string plaintext, DateTimeOffset expiration) : string Protect(string plaintext, TimeSpan lifetime) : string Protect(string plaintext) : string

ITimeLimitedDataProtector提供了数个重载方法用来设定带有生命周期的加密方法,用户可以通过Date TimeOffset,TimeSpan等参数来设置时间。 

有对应的加密,就有相对应的解密方法,在这里就不详细介绍了。有兴趣的同学可以去看一下官方文档。 

配置数据保护 

在我们的 ASP.NET Core 运行的时候,系统会基于当前机器的运行环境默认配置一些关于 Data Protection 的东西,但是有些时候可能需要对这些配置做一些改变,比如在分布式部署的时候,在上一篇博文的末尾也提到过,下面就来看一下具体怎么配置的吧。 

上篇文章已经提到过,我们通过以下方式来把 Data Protection 注册到服务中:

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

其中AddDataProtection 返回的是一个 IDataProtectionBuilder 接口,这个接口提供了一个扩展方法PersistKeysToFileSystem() 来存储私钥。可以通过它传入一个路径来指定私钥存储的位置:

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

可以传入一个共享文件夹,来存储私钥,这样在不同机器的私钥就可以保存到一个位置了。可以通过此种方式在分布式部署的时候,隔离开了机器的差异化。
 如果你觉得不安全,还可以配置一个X.509证书来,进行加密:

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

上篇文章讲过,Data Protection 的默认保存时间是90天,你可以通过以下方式来修改默认的保存时间:

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

默认情况下,即使使用相同的物理密钥库,Data Protection 也会把不同的应用程序隔离开,因为这样可以防止从一个应用程序获取另外一个应用程序的密钥。所以如果是相同的应用程序,可以设置相同的应用程序名称:

public void ConfigureServices(IServiceCollection services) { services.AddDataProtection() .SetApplicationName("my application"); }

有时候需要禁用应用程序生成密钥,或者是说我只有一个程序用来生成或者管理密钥,其他程序只是负责读的话,那么可以这样:

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

修改加密算法 

可以使用UseCryptographicAlgorithms方法来修改ASP.NET Core Data Protection的默认加密算法,如下:

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

总结:

本篇主要是介绍了一些常用的API, 下篇介绍一些高级的用法。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjygfp.html