close
文章出處

前言

上篇主要是對 ASP.NET Core 的 Data Protection 做了一個簡單的介紹,本篇主要是介紹一下API及使用方法。

API 接口

ASP.NET Core Data Protectio 主要對普通開發人員提供了兩個接口,IDataProtectionProviderIDataProtector
我們先看一下這兩個接口的關系:

namespace Microsoft.AspNetCore.DataProtection
{
    //
    // 摘要:
    //     An interface that can provide data protection services.
    public interface IDataProtector : IDataProtectionProvider
    {

        byte[] Protect(byte[] plaintext);

        byte[] Unprotect(byte[] protectedData);
    }
}

可以看到,IDataProtector繼承自IDataProtectionProvider ,并且提供了兩個方法 ProtectUnprotect ,從命名來看,一個是加密,一個是解密。而他們的簽名都是傳入一個byte數組,這也就意味著他們可以加密和解密一切對象。返回的也是byte數組,也就是說在實際的使用過程中,我們應該自己添加或者使用系統的一些擴展方法來具體化我們的需求。

我們再看一下IDataProtectionProvider接口:

namespace Microsoft.AspNetCore.DataProtection
{
    public interface IDataProtectionProvider
    {

        IDataProtector CreateProtector(string purpose);
    }
}

IDataProtectionProvider提供了一個方法,通過傳入一個 purpose字符串(見后面詳細介紹)來生成一個IDataProtector接口對象。
從這個接口的命名來看,它以Provider結尾,也就是說這部分我們可以實現自己的一套加解密的東西。

我們在閱讀微軟項目的源代碼的時候,經常看一些以xxxxProvider結尾的對象,那么它的職責是什么,同時扮演什么樣的角色呢?
其實這是微軟專門為ASP.NET設計的一個設計模式,叫Provider Model設計模式,也可以說它是由微軟發明的,它不屬于23種設計模式中的一種,從功能上來看的話,應該是工廠和策略的結合體。自ASP.NET 2.0開始,微軟就開始引入這種設計模式,最開始主要是用于實現應用程序的配置的多個實現。比如開發者最熟悉的web.config中, 針對于數據庫連接字符串的配置, 還有二進制,再比如XML啊等等很多,現在其他地方這種模式也用的越來越多起來。

再來說一下CreateProtector方法簽名中的 purpose 這個字符串,在上一篇博文中為了讀者好理解,我把傳入的purpose說成可以理解為一個公鑰,其實這個說法是不嚴謹的,可以理解為一個標識,指示當前Protector的用途。

在使用IDataProtector的時候,會發現它還有一些擴展方法位于Microsoft.AspNetCore.DataProtection命名空間下:

public static class DataProtectionCommonExtensions
{
    public static IDataProtector CreateProtector(this IDataProtectionProvider provider, IEnumerable<string> purposes);

    public static IDataProtector CreateProtector(this IDataProtectionProvider provider, string purpose, params string[] subPurposes);

    public static IDataProtector GetDataProtector(this IServiceProvider services, IEnumerable<string> purposes);

    public static IDataProtector GetDataProtector(this IServiceProvider services, string purpose, params string[] subPurposes);

    public static string Protect(this IDataProtector protector, string plaintext);

    public static string Unprotect(this IDataProtector protector, string protectedData);
}

可以看到,CreateProtector還提供了可以傳多個purpose的方法(IEnumerable,params string[]),為什么會有這種需求呢?

其實DataProtector是有層次結構的,再看一下IDataProtector接口,它自身也實現了IDataProtectionProvider接口,就是說IDataProtector自身也可以再創建IDataProtector

舉個例子:我們在做一個消息通訊的系統,在消息通訊的過程中,需要對用戶的會話進行加密,我們使用CreateProtector("Security.BearerToken")加密。但是加密的時候并不能保證消息是不受信任的客戶端發過來的,所以想到了CreateProtector("username")來進行加密,這個時候假如有一個用戶的用戶名叫“Security.BearerToken”,那么就和另外一個使用Security.BearerToken作為標示的 Protector 沖突了,所以我們可以使用
CreateProtector([ “Security.BearerToken”, “User: username” ])這種方式。它相當于
provider.CreateProtector(“Security.BearerToken).CreateProtector(“User: username”)。 意思就是先創建一個Protector叫“Security.BearerToken”,然后再在purpose1下創建一個名為“User: username”的Protector。

用戶密碼哈希

Microsoft.AspNetCore.Cryptography.KeyDerivation命名空間下提供了一個KeyDerivation.Pbkdf2方法用來對用戶密碼進行哈希。

具有生命周期限制的加密

有些時候,我們需要一些具有過期或者到期時間的加密字符串,比如一個用戶在找回密碼的時候,我們向用戶的郵箱發送一封帶有重置命令的一封郵件,這個重置命令就需要有一個過期時間了,超過這個過期時間后就失效,在以前我們可能需要向數據庫存儲一個時間來標記發送時間,然后再解密對比和數據庫的時間差來驗證。

現在我們不需要這么做了,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 TimeOffsetTimeSpan等參數來設置時間。

有對應的加密,就有相對應的解密方法,在這里就不詳細介紹了。有興趣的同學可以去看一下官方文檔。

配置數據保護

在我們的 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, 下篇介紹一些高級的用法。


本文地址:http://www.cnblogs.com/savorboard/p/dotnet-core-data-protection.html
作者博客:Savorboard
歡迎轉載,請在明顯位置給出出處及鏈接


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜

    AutoPoster 發表在 痞客邦 留言(0) 人氣()