asp.net Core data protection (Protection) Medium _ Practical Tips

Source: Internet
Author: User
Tags decrypt hash static class

Preface

The last chapter is mainly on the ASP.net Core of the Data Protection made a simple introduction, this article is mainly about the API and use methods.

API Interface

The asp.net core Data Protectio provides two interfaces for ordinary developers, Idataprotectionprovider and Idataprotector.
Let's take a look at the relationship between the two interfaces:

 Namespace Microsoft.AspNetCore.DataProtection
{
 ///
 Summary:
 //A  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, from the name point of view, one is encryption, the other is decryption. And their signatures are passed in a byte array, which means they can encrypt and decrypt all objects. Returns a byte array, which means that in the actual use, we should add or use some of the system's extension methods to materialize our requirements.

Let's take another 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 (described later in detail).
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 with Xxxxprovider, so what is its responsibility and what role does it play?
In fact, this is a Microsoft designed for asp.net design model, called provider model design mode, it can also be said that it was invented by Microsoft, it does not belong to 23 kinds of design patterns, from the functional point of view, it should be a combination of factories and strategies. Since the start of ASP.net 2.0, Microsoft has introduced this design pattern, primarily to implement multiple implementations of the application's configuration. For example, developers most familiar with the web.config, for the database connection string configuration, there are binaries, such as XML, and so many, and now other places this mode is also used more and more.

Let's talk about the Createprotector method signature in the purpose this string, in the last article posting for the reader to understand, I put the incoming purpose can be understood as a public key, in fact this argument is not rigorous, can be understood as a logo, Indicates the purpose of the current protector.

When using Idataprotector, it is found that there are some extension methods 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 demand?

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

For Example: We are doing a message communication system, in the process of message communication, we need to encrypt the user's session, we use Createprotector ("Security.bearertoken") encryption. But when the encryption does not guarantee that the message is untrusted client sent over, so think of Createprotector ("username") to encrypt, this time if there is a user's name "Security.bearertoken", So 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
Provider. Createprotector ("Security.bearertoken"). Createprotector ("User:username"). The idea is to create 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.

Life-cycle-limited encryption

There are times when we need some encrypted string with expiration or expiration time, for example, when a user retrieves the password, we send an email with a reset command to the user's mailbox, and the Reset command needs an expiration date, which expires after the expiration date. In the past we might have to store a time for the database to mark the sending time, and then decrypt the contrast and the database differences to verify.

Now we don't have to do this, ASP.net Core defaults to provide an interface called Itimelimiteddataprotector, 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, 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[]< C3/>protect (byte[] plaintext): byte[]
Protect (string plaintext, DateTimeOffset expiration): String
Protect ( string plaintext, TimeSpan lifetime): string

Itimelimiteddataprotector provides a number of overloaded methods for setting the life-cycle encryption method that allows the user to set the time by using parameters such as the date Timeoffset,timespan.

There is a corresponding encryption, there is a corresponding decryption method, here is not described in detail. Interested students can take a look at the official documents.

Configure Data Protection

When our ASP.net Core runs, the system defaults to configuring something about Data Protection based on the current machine's operating environment, but sometimes it may be necessary to make some changes to these configurations, as in distributed deployments, as mentioned at the end of the previous post. Here is a look at the specific how to configure it.

As mentioned in the previous article, we register the Data Protection in the following ways:

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

Where Adddataprotection returns a Idataprotectionbuilder interface that provides an extension method Persistkeystofilesystem () to store the private key. You can pass it through 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 location. In this way, the differentiation of machines can be separated from each other in a distributed deployment.
If you feel insecure, you can also configure a X.509 certificate to encrypt:

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

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);
} 

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

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

Sometimes you need to disable the application generation key, or if I have only one program to generate or manage the key, and other programs are only responsible for reading, then you can:

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

Modify 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 commonly used APIs, the next chapter introduces some advanced usage.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.