ASP. NET Core Data Protection (coreprotection)
Preface
The previous article briefly introduced the Data Protection of ASP. NET Core. This article mainly introduces APIs and usage methods.
API
ASP. NET Core Data Protectio provides two interfaces for common developers: IDataProtectionProvider and IDataProtector.
Let's take a look at the relationship between the two interfaces:
Namespace Microsoft. aspNetCore. dataProtection {// Abstract: // An interface that can provide data protection services. public interface IDataProtector: IDataProtectionProvider {byte [] Protect (byte [] plaintext); byte [] Unprotect (byte [] protectedData );}}
As you can see, IDataProtector inherits from IDataProtectionProvider and provides two methods: Protect and Unprotect. In terms of name, one is encryption and the other is decryption. Their signatures all pass in a byte array, which means they can encrypt and decrypt all objects. The returned byte array is also returned. That is to say, in actual use, we should add or use some extension methods of the system to reflect our needs.
Let's take a look at the IDataProtectionProvider interface:
namespace Microsoft.AspNetCore.DataProtection{ public interface IDataProtectionProvider { IDataProtector CreateProtector(string purpose); }}
IDataProtectionProvider provides a method to generate an IDataProtector interface object by passing in a purpose string (see the following description.
From the perspective of the interface name, it ends with a Provider, that is, we can implement our own set of encryption and decryption.
When we read the source code of Microsoft projects, we often read objects ending with xxxxProvider. What is its role and role?
In fact, Microsoft specializes in ASP. A design pattern designed by NET, called the Provider Model Design pattern. It can also be said that it was invented by Microsoft. It does not belong to one of the 23 design patterns. In terms of functions, it should be a combination of factories and strategies. Microsoft has introduced this design pattern since ASP. NET 2.0. It was initially used to implement multiple implementations of application configurations. For example, in the web. config that developers are most familiar with, there are many configuration items for database connection strings, as well as binary files, such as XML, and so on. Currently, this mode is increasingly used elsewhere.
Let's take a look at the purpose string in the CreateProtector method signature. In the previous blog post, for readers, I described the imported purpose as a public key. In fact, this statement is not rigorous, it can be understood as an identifier that indicates the purpose of the current Protector.
When using IDataProtector, you will find some extension methods in the Microsoft. AspNetCore. DataProtection namespace:
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);}
As you can see, CreateProtector also provides the method (IEnumerable, params string []) for uploading multiple purpose. Why is this requirement required?
In fact, DataProtector has a hierarchical structure. Let's take a look at the IDataProtector interface, which also implements the IDataProtectionProvider interface, that is, IDataProtector itself can also create IDataProtector.
For example:We are working on a message communication system. In the process of message communication, we need to encrypt the user's session. We use CreateProtector ("Security. BearerToken") for encryption. However, during encryption, messages cannot be sent from untrusted clients. Therefore, CreateProtector ("username") is used for encryption, in this case, assume that the user name is "Security. bearerToken. bearerToken is used as the identified Protector conflict, so we can use
CreateProtector (["Security. BearerToken", "User: username. It is equivalent
Provider. CreateProtector ("Security. BearerToken). CreateProtector (" User: username "). This means to create a Protector named "Security. BearerToken", and then create a Protector named "User: username" under purpose1.
User password hash
In the Microsoft. AspNetCore. Cryptography. KeyDerivation namespace, A KeyDerivation. Pbkdf2 method is provided to hash users' passwords.
Encryption with lifecycle restrictions
Sometimes, we need encrypted strings with expiration or expiration time. For example, when a user recovers the password, we send an email with a reset command to the user's mailbox, this reset command requires an expiration time, which will expire after the expiration time. In the past, we may need to store a time to mark the sending time, then decrypt the comparison and verify the time difference between the database.
Now we don't need to do this. ASP. NET Core provides an interface by default, ITimeLimitedDataProtector. Let's take a look at the definition of this interface:
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) : stringProtect(string plaintext, TimeSpan lifetime) : stringProtect(string plaintext) : string
ITimeLimitedDataProtector provides several overload methods to set encryption methods with lifecycles. You can set the time using Date TimeOffset, TimeSpan, and other parameters.
There is a corresponding encryption, and there is a corresponding decryption method, which will not be detailed here. If you are interested, you can go to the official documents.
Configure Data Protection
In our ASP. when running. NET Core, the system configures Data Protection based on the running environment of the current machine by default. However, you may need to make some changes to these configurations, for example, I mentioned it at the end of the previous blog post during distributed deployment. Let's take a look at how to configure it.
As mentioned in the previous article, we use the following methods to register Data Protection to the service:
public void ConfigureServices(IServiceCollection services){ services.AddDataProtection();}
Here, AddDataProtection returns an IDataProtectionBuilder interface, which provides an extension method PersistKeysToFileSystem () to store the private key. You can pass in a path to specify the location of the private key storage:
public void ConfigureServices(IServiceCollection services){ services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(@"\\server\share\directory\"));}
You can input a shared folder to store the private key, so that the private key of different machines can be saved to a location. In this way, machine differentiation can be isolated during distributed deployment.
If you feel insecure, you can configure an X.509 Certificate for encryption:
public void ConfigureServices(IServiceCollection services){ services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(@"\\server\share\directory\")) .ProtectKeysWithCertificate("thumbprint");}
As mentioned in the previous article, Data Protection is saved for 90 days by default. You can modify the default storage time in the following ways:
public void ConfigureServices(IServiceCollection services){ services.AddDataProtection() .SetDefaultKeyLifetime(TimeSpan.FromDays(14));}
By default, even if the same physical keystore is used, Data Protection isolates different applications, because this prevents you from obtaining the keys of another application from one application. Therefore, if the application is the same, you can set the same application name:
public void ConfigureServices(IServiceCollection services){ services.AddDataProtection() .SetApplicationName("my application");}
Sometimes you need to disable the application to generate a key, or say that I only have one program to generate or manage the key. If other programs are only responsible for reading the key, you can do this:
public void ConfigureServices(IServiceCollection services){ services.AddDataProtection() .DisableAutomaticKeyGeneration();}
Modify Encryption Algorithm
You can use UseCryptographicAlgorithms to modify the default encryption algorithm of ASP. NET Core Data Protection, as follows:
services.AddDataProtection() .UseCryptographicAlgorithms(new AuthenticatedEncryptionSettings() { EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC, ValidationAlgorithm = ValidationAlgorithm.HMACSHA256 });
Summary:
This article mainly introduces some common APIs and introduces some advanced usage.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.