ASP. NET Core Data protection (Protection)

Source: Internet
Author: User
Tags decrypt
API interface

The ASP. NET Core Data Protectio provides two interfaces for general developers, Idataprotectionprovider and Idataprotector.
Let's look at the relationship between the two interfaces:

namespace microsoft.aspnetcore.dataprotection{////Abstract://An  interface that can provide data protection services. Pu Blic 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, from the name point of view, one is encryption, one is decryption. And their signatures are all passing in a byte array, which means they can encrypt and decrypt everything. The return is also a byte array, that is, in the actual use of the process, we should add or use some of the system's extension methods to materialize 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 way to generate a Idataprotector interface object by passing in a purpose string (see details later in this article).
From the name of this interface, it ends with provider, which means that we can implement our own set of decrypted things.

When we read the source code of the Microsoft Project, we often look at some objects that end in Xxxxprovider, so what are their responsibilities and what role do they play?
In fact, this is a Microsoft specifically for the design of the design mode, called provider model design mode, it is invented by Microsoft, it is not part of the 23 design patterns of one, from a functional point of view, it should be a combination of factory and strategy. Since the start of ASP. 2.0, Microsoft has introduced this design pattern, initially primarily for implementing multiple implementations of the application's configuration. For example, developers most familiar with the Web. config, for the database connection string configuration, as well as the binary, such as XML AH and so many, and now other places this pattern is also used more and more up.

Just a second. Createprotector method signature In the purpose this string, in the previous article blog post for the reader to understand, I put the incoming purpose to be understood as a public key, in fact, this statement is not rigorous, can be understood as an identity, Indicates the purpose of the current protector.

When using Idataprotector, you will find that there are some extension methods that are located under 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 a way to pass multiple purpose (Ienumerable,params string[]), why is there such a requirement?

In fact, DataProtector is a hierarchical structure, and then look at the Idataprotector interface, it also implements the Idataprotectionprovider interface, This means that Idataprotector itself can also create idataprotector.

For example: We are doing a messaging system where we need to encrypt the user's session in the process of message communication, and we use Createprotector ("Security.bearertoken") encryption. However, when encryption does not guarantee that the message is not trusted by the client sent, so think of Createprotector ("username") to encrypt, this time if there is a user named "Security.bearertoken", Then there's a conflict with another Protector that uses Security.bearertoken as a marker, so we can use
Createprotector (["Security.bearertoken", "User:username"]) this way. It is equivalent to
Provider. Createprotector ("Security.bearertoken"). Createprotector ("User:username"). It means creating a protector called "Security.bearertoken" before creating a protector named "User:username" under Purpose1.

User Password Hash

A KEYDERIVATION.PBKDF2 method is provided under the Microsoft.AspNetCore.Cryptography.KeyDerivation namespace to hash the user's password.

Encryption with lifecycle restrictions

Sometimes we need an encrypted string with expiration or expiry time, such as when a user retrieves the password, we send a message with the reset command to the user's mailbox, and the Reset command needs an expiration time, which expires after the expiration time. In the past, we might need to store a time in the database to mark the sending time, and then decrypt the comparison and the database's difference to verify.

Now that we don't need to do this, ASP. NET Core provides an interface by default called Itimelimiteddataprotector, so let's look at the definition of this interface first:

Createprotector (String purpose): Itimelimiteddataprotector This API was similar to the existing IDATAPROTECTIONPROVIDER.C Reateprotector in so 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 overloaded methods for setting the encryption method with a lifetime, and the user can set the time by parameters such as Date Timeoffset,timespan.

There is corresponding encryption, there is a corresponding method of decryption, here is not detailed introduction. Interested students can take a look at the official documents.

Configure Data protection

When we run our ASP. NET Core, the system will configure some things about Data Protection based on the current machine's operating environment, but there may be times when you need to make some changes to these configurations, such as in distributed deployments, as mentioned at the end of the previous blog post. Let's take a look at how to configure it.

As mentioned in the previous article, we have registered the Data Protection in the service in the following ways:

public void Configureservices (Iservicecollection services) {services. Adddataprotection ();}


Where Adddataprotection returns a Idataprotectionbuilder interface, this interface provides an extension method Persistkeystofilesystem () to store the private key. It is possible to pass in a path to specify the location of the private key store:

public void Configureservices (Iservicecollection services) {services. Adddataprotection ()  . Persistkeystofilesystem (New DirectoryInfo (@ "\\server\share\directory\")); }

You can pass in a shared folder to store the private key so that the private key of the different machines can be saved to a single location. In this way, the differentiation of machines can be separated from each other in a distributed deployment.
If you do not feel secure, you can also configure a certificate to encrypt:

public void Configureservices (Iservicecollection services) {services. Adddataprotection ()  . Persistkeystofilesystem (New DirectoryInfo (@ "\\server\share\directory\"))  . Protectkeyswithcertificate ("thumbprint");}


As mentioned in the previous article, the default save time for Data Protection is 90 days, and you can modify the default save time in the following ways:

public void Configureservices (Iservicecollection services) {services. Adddataprotection ()  . Setdefaultkeylifetime (Timespan.fromdays (14));}


By default, Data Protection isolates different applications even if the same physical keystore is used, because it prevents one application from getting a key for another application. So if the application is the same, you can set the same application name:

public void Configureservices (Iservicecollection services) {services. Adddataprotection ()  . Setapplicationname ("My Application");}


Sometimes it is necessary to disable the application generation key, or to say that I have only one program to generate or manage the key, and that the other program is only responsible for reading, then you can:

public void Configureservices (Iservicecollection services) {services. Adddataprotection ()  . Disableautomatickeygeneration ();}


Modifying the encryption algorithm

You can use the Usecryptographicalgorithms method to modify the default encryption algorithm for the ASP. NET Core Data protection, as follows:

Services. Adddataprotection (). Usecryptographicalgorithms (New Authenticatedencryptionsettings () {encryptionalgorithm = EncryptionAlgorithm.AES_ 256_CBC, validationalgorithm = validationalgorithm.hmacsha256});


Summarize:

This article mainly introduces some common API, the next chapter introduces some advanced usage.

The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support topic.alibabacloud.com.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.