Objective
The previous article recorded how to use HTTPS (SSL) in Kestrel, which is actually used in our current project.
Data security is often a part of the developer's easy to overlook, including myself. In the past two years there have been a lot of the industry because of security problems caused a lot of serious things happen, so security is important to our developers, we are responsible for the security of our code.
In the work, we often meet to encode,base64,sha256, RSA, Hash,encryption, MD5, and so on, some people are not clear to them, also do not know when to use them, and some people think that MD5 is the encryption algorithm.
In ASP.net Core, there is a new batch of APIs for data protection related, including encryption and decryption mechanisms, so let's take a look at it.
Directory
• Encrypt, encode, and hash the difference between
• Data Protection (Protection) Introduction
Data protection in Core of asp.net
• Summary
encoding, encrypting, and hashing the difference between
1, coding
Coding is the process by which information is converted from one form or format to another, and they are reversible.
such as URLs, Base64, Jsunicode, Utf-8, and so on.
2, encryption
Encryption is reversible, and similar to encoding is the conversion of data from one form to another, which, through a specific cryptographic key, corresponds to the process of decryption. There are 2 kinds of encryption algorithms: Symmetric encryption algorithm and asymmetric encryption algorithm.
Symmetry: DES, AES, SM1, RC4 and so on.
Asymmetric: RSA, ECC, SM2, and so on.
3, Hash
Also called "Hash", is to convert any length of data into a fixed length of "fingerprint", this process is irreversible. And as long as the input changes, the output of the hash value will be very different.
It also has a feature that the same input always has the same result, and this feature is appropriate for saving the password.
such as: MD5, SHA256, SHA512, RIPEMD, Whirlpool and so on.
Data protection (Protection) Introduction
When looking at data protection official documents, Microsoft's documentation is written in a way that basically means they are developing a set of data-protected libraries to use for trusted clients and untrusted clients, based on a few requirements. These are the following requirements:
1, authenticity, integrity
An example of an authentication cookie is that the server generates a token that contains XYZ permissions and then expires at some point in the future, which requires a request to be made again to make sure that the requested token is not tampered with.
2, the confidentiality of
The server guarantees that the request is trusted, so it requires information that contains a particular operating environment, such as a path, a permission or a handle, or something else that is specific to the server, and that information should not be disclosed to untrusted clients, that is, similar to the private key.
3, the isolation of
Then there is the requirement to make a component, and the component is independent and can depend on other components in the system. As a bearer token component, it does not need to refer to the ANTI-CSRF mechanism if it is to use this component.
Further narrowing the demand range, the encrypted data need not be used in other systems other than the system, and the processing speed is as fast as possible, because each time the Web request uses the cryptographic component once or more times.
Based on the above requirements, Microsoft proposed to use cryptography, because this is a typical cryptography application scenario. It is true that this is a cryptographic application scenario and an asymmetric encryption algorithm. But as you all know, asymmetric encryption is a public and private key to ensure security, even if the public key is compromised, the entire communication is still secure, which is more than symmetric encryption benefits. However, asymmetric encryption is also flawed, that is, encryption and decryption takes a long time, slow speed.
But the above requirements are also required to speed as fast as possible, how to do? So Microsoft's engineers came up with the idea of streamlining and optimizing asymmetric encryption mechanisms to meet this requirement. Because there is no need to cross the system or cross-language or anything, so there is no protocol, and so on, which brings more possibilities for optimization.
Here, I thought, if I were to design and develop such a system based on the above points, how should I design? How to meet the requirements?
With this problem, let's take a closer look at how Microsoft is doing it.
Here are some of the summary design principles:
1, the configuration should be as simple as possible, by default should be zero configuration, developers can run directly.
2, provide a simple API, should be easy to use, and will not easily use the wrong.
3, developers do not need to learn how to manage these keys (public key, private key), the system should automatically select the algorithm and management key lifecycle. Ideally, developers should not access the original files of these keys.
4, the key should be protected, will not be called remotely. The system should have an automatic protection mechanism and can be applied automatically.
If I had to design such a library, I might not have thought so much, and probably would have thought only of the first 3 points.
And look at the audience:
1. Application developers and framework developers (no knowledge is required).
2, application developers and system administrators (do not use the default configuration, just set some paths, etc.).
3. Provide extensible APIs for developers with higher security awareness, or specific requirements extensions (there are unique requirements to rewrite the system's components).
Above, you can see Microsoft in the development of a component of the analysis of the problem, maybe we can learn something from it.
data protection in Core of ASP.net
Web applications often need to store sensitive data (such as user passwords), and Windows systems provide the desktop program with DPAPI for use, but not for web systems. ASP.net core provides a simple and Easy-to-use API for protecting data.
In ASP.net core, data protection is primarily designed to be used in the service side to replace ASP.net 1.x-4.x, machinekey is primarily used to ensure encryption and decryption of cookie data when using form authentication to ensure that it is not modified. Or the encrypted decryption of the ViewState data is not tampered with, and the session status identity is validated.
Let's take a look at the easiest way to use it:
Using System;
Using Microsoft.AspNetCore.DataProtection;
Using Microsoft.Extensions.DependencyInjection; public class Program {public static void Main (string[] args) {//Add data protection to the service var servicecollection = new Serv
Icecollection ();
Servicecollection.adddataprotection ();
var services = Servicecollection.buildserviceprovider ();
Create an instance of MyClass from di var instance = activatorutilities.createinstance<myclass> (services); Instance.
Runsample ();
public class MyClass {Idataprotector _protector; Parameter ' provider ' comes from DI public MyClass (Idataprotectionprovider provider) {_protector = provider.
Createprotector ("Contoso.MyClass.v1");
public void Runsample () {console.write ("Enter input:");
string input = Console.ReadLine (); Encrypted string protectedpayload = _protector.
Protect (input);
Console.WriteLine ($ "Protect returned: {protectedpayload}"); Decrypt String UnprotectedpaylOad = _protector.
Unprotect (Protectedpayload);
Console.WriteLine ($ "unprotect returned: {unprotectedpayload}");
}} * * Output: * * Enter Input:hello world! * Protect returned:cfdj8iccgqwzzhlaltzt ...
ODFH66I1PNGMPCR5E441XQ * Unprotect Returned:hello world!
*/
In Createprotector ("Contoso.MyClass.v1"), the argument "Contoso.MyClass.v1" can be interpreted as a public key because ASP.net Core Data Protection Asymmetric encryption (see earlier), so there should be a key in the system, then the key asp.net Core inside the system to help you maintain.
Read here, some students may ask, that the system is how to help me maintain my key? We might as well do a test first.
First of all, I in my development environment, first in the above program, the decryption part of the code commented out, and then run the above program, enter a "Hello world!", get an encrypted string cfdj8iccgqwzzhlaltzt ... ODFH66I1PNGMPCR5E441XQ (abbreviated).
Then I copy the same program to another development environment machine, and then the above encryption part of the code to comment out, using the first step generated cfdj8iccgqwzzhlaltzt ... Odfh66i1pngmpcr5e441xq to decrypt, note that in both of these steps we use "CONTOSO.MYCLASS.V1" as the public key.
Run the program to see the results:
The program throws the result of a "System.Security.Cryptography.CryptographicException" exception.
for what? this is because each machine has a private key, because in the process of decryption, the private key is different, so decryption failed, throw an exception.
private Key
Where is the private key stored?
1, if the program is hosted under Microsoft Azure, stored in the "%home%\asp.net\dataprotection-keys" folder.
2. If the program is hosted under IIS, it is saved in the Acled Special registry key of the HKLM Registry, and only the worker process can access it using Windows DPAPI encryption.
3. If the current user is available, that is, win10 or win7, it is stored in the "%localappdata%\asp.net\dataprotection-keys" folder, with the same use of Windows DPAPI encryption.
4, if these are not met, then the private key is not persisted, that is, when the process is closed, the generated private key is lost.
The following is the private key file on the BO main machine:
An XML configuration file, located in the C:\Users\ User name \appdata\local\asp.net\dataprotection-keys folder, The name is: Key-c37e3ed9-fbb5-47bc-9e8c-128afaf1c6d9.xml, the contents are as follows:
<?xml version="1.0" encoding="utf-8"?>
<key id="c37e3ed9-fbb5-47bc-9e8c-128afaf1c6d9" version="1">
<creationDate>2016-08-15T05:21:16.7925949Z</creationDate>
<activationDate>2016-08-15T05:21:16.7165905Z</activationDate>
<expirationDate>2016-11-13T05:21:16.7165905Z</expirationDate>
<descriptor deserializerType="Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60">
<descriptor>
<encryption algorithm="AES_256_CBC" />
<validation algorithm="HMACSHA256" />
<encryptedSecret decryptorType="Microsoft.AspNetCore.DataProtection.XmlEncryption.DpapiXmlDecryptor, Microsoft.AspNetCore.DataProtection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60" xmlns="http://schemas.asp.net/2015/03/dataProtection">
<encryptedKey xmlns="">
<!-- This key is encrypted with Windows DPAPI. -->
<value>AQAAANCMnd8BFdERjHoAwE/Cl+sBAAAArS6GBZu5C024S8VcNDckGgAAAAACAAAAAAAQZgAAAAEAACAAAABBUO4j0CscEZsdcHDAStXnDvtx+zFucmsG90sdhyjfgQAAAAAOgAAAAAIAACAAAABGr9fgvZkLAlgIZkGym5uLiufpaEcuVsp35+J96ItTYlABAADEZxVArK0QtxufuaRt/kVR2ZBZEoLhlYJ44BhvQDd6b9tN0L9Y7W2eeBPBefcZaGZk5xILwZYI5box9omwC/mp8t9wopVaratjZuNs21Al+JzxS+PeV9X0iPtRyfx2K7DJYOUT6IqoFR2ykL5MI9jvkIbUxcQOs0BKOwAHl4yAlYF2tR8pz1FkXKqZafovc11aOZeZhkfd2hiA53tan94bQOP43Z4HF+QWSazrq5IIqdFSOyZQemWL9Z7eYyoNpEktf3eGZQu/KBOg/BH5yizWa+6b7RLcEX6JdQ2/jpmnHNl+HPMIah3UZV0mRfAE2j58cUjosnV+LDQZoLn4OP70YWtO/tTBc4tsEY3n/WboL4PgPPmQ+2jfd/zmEQIon+4d7TY+mGh4c6wXAmAZF517UAHQMC1icx4HSJC8DTuWPlINihPyufejuPmLqW6CW8NAAAAA7ziObXv+Ax4Mm0AtZiGw0/IepDv/gJSxhEwLIDhfvQIQJv//G500EYtIbZJW6sWit//ypfjrUZYglHgKV+GpbA==</value>
</encryptedKey>
</encryptedSecret>
</descriptor>
</descriptor>
</key>
The file contains a creation date, an expiration date. The interval is 90 days and the key expires after 90 days, and the system automatically generates a new key and sets the new key as the active key. As long as the expired key still exists on the system, you can still decrypt any protected data.
The article should not be too long, the next chapter and then write.
Summary
This article is a rough introduction to the ASP.net Core Data protection and includes a simple way to use it. In the actual use of the process, in fact, many components will use it inside, such as session middleware, identity middleware, authercation middleware, and so on, for ordinary developers in the code may not be used, But in the system distributed deployment if you do not understand the mechanism may encounter problems (see the Cricket Blog this article), so still can look forward to the following, more in-depth understanding of it, master it.
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.