In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail about the use of data protection Data Protection in ASP.NETCore. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.
API interface
ASP.NET Core DataProtectio mainly provides two interfaces for ordinary developers, IDataProtectionProvider and IDataProtector.
Let's first take a look at the relationship between these 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, one is encryption and the other is decryption in terms of name. Their signatures are passed in a byte array, which means they can encrypt and decrypt all objects. What is returned is also the byte array, that is, in the actual use, we should add or use some extension methods of the system to specify 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 method to generate an purpose interface object by passing in an IDataProtector string (described in more detail below).
Judging from the name of this interface, it ends with Provider, which means that we can implement our own set of encryption and decryption.
When we read the source code of Microsoft projects, we often look at objects that end in xxxxProvider, so what is its responsibility and what role does it play at the same time?
In fact, this is a design pattern specially designed by Microsoft for ASP.NET, called 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, from a functional point of view, it should be a combination of factory and strategy. Microsoft has introduced this design pattern since ASP.NET 2.0, primarily as multiple implementations for implementing the configuration of applications. For example, in web.config, which developers are most familiar with, there are also binaries for the configuration of database connection strings, such as XML, and so on. Now this mode is also used more and more in other places.
Let's talk about the string purpose in the CreateProtector method signature. In the previous blog post, I said that the incoming purpose can be understood as a public key. In fact, this statement is not rigorous and can be understood as an identification indicating the purpose of the current Protector.
When using IDataProtector, you will find that it also has some extension methods under the Microsoft.AspNetCore.DataProtection namespace:
Public static class DataProtectionCommonExtensions {public static IDataProtector CreateProtector (this IDataProtectionProvider provider, IEnumerable purposes); public static IDataProtector CreateProtector (this IDataProtectionProvider provider, string purpose, params string [] subPurposes); public static IDataProtector GetDataProtector (this IServiceProvider services, IEnumerable 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 need?
In fact, DataProtector has a hierarchical structure. If you take a look at the IDataProtector interface, it also implements the IDataProtectionProvider interface, which means that IDataProtector itself can also create an 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 encrypting, there is no guarantee that the message is sent by an untrusted client, so we think of CreateProtector ("username") to encrypt. At this time, if there is a user whose name is "Security.BearerToken", it conflicts with another Protector that uses Security.BearerToken as a logo, so we can use the
CreateProtector (["Security.BearerToken", "User: username"]) this way. It's the equivalent of
Provider.CreateProtector ("Security.BearerToken) .CreateProtector (" User: username "). It means to create a Protector called" Security.BearerToken "first, and then create a Protector called" 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 limit
Sometimes, we need some encrypted strings with expiration or expiration time. For example, when a user retrieves a password, we send an email with a reset command to the user's mailbox. This reset command needs to have an expiration time, after which it will expire. In the past, we may need to store a time in the database to mark the sending time. Then decrypt the comparison and the time difference of the database to verify.
Now we don't need to do this. ASP.NET Core provides an interface called ITimeLimitedDataProtector by default. 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 overloaded methods to set encryption methods with life cycle, and users can set the time through parameters such as Date TimeOffset,TimeSpan.
If there is a corresponding encryption, there is a corresponding decryption method, which will not be introduced in detail here. Students who are interested can take a look at the official documents.
Configure data protection
When our ASP.NET Core is running, the system will configure something about Data Protection by default based on the running environment of the current machine, but sometimes we may need to make some changes to these configurations, for example, in distributed deployment, as mentioned at the end of the previous blog post, let's take a look at how to configure them.
As mentioned in the previous article, we register Data Protection with the service in the following ways:
Public void ConfigureServices (IServiceCollection services) {services.AddDataProtection ();}
Where AddDataProtection returns an IDataProtectionBuilder interface that provides an extension method PersistKeysToFileSystem () to store the private key. You can pass in a path to specify the location where the private key is stored:
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 on different machines can be saved to one location. In this way, the differentiation of machines can be isolated when distributed deployment.
If you feel insecure, you can also configure an X.509 certificate to encrypt:
Public void ConfigureServices (IServiceCollection services) {services.AddDataProtection () .PersistKeysToFileSystem (new DirectoryInfo (@ "\\ server\ share\ directory\")) .ProtectKeysWithCertificate ("thumbprint");}
As mentioned in the last article, the default save time for Data Protection is 90 days. 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 this prevents one application from obtaining the key of another application. So if it is 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 to generate keys, or if I have only one program to generate or manage keys, and other programs are just responsible for reading, then you can do this:
Public void ConfigureServices (IServiceCollection services) {services.AddDataProtection () .DisableAutomaticKeyGeneration ();}
Modify encryption algorithm
You can use the UseCryptographicAlgorithms method to modify the default encryption algorithm for ASP.NET Core Data Protection, as follows:
Services.AddDataProtection () .UseCryptographicAlgorithms (new AuthenticatedEncryptionSettings () {EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC, ValidationAlgorithm = ValidationAlgorithm.HMACSHA256}); this is how the usage of DataProtection for data protection in ASP.NETCore is shared. I hope the above content can be helpful to everyone and learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.