The ASP. NET Core Data Protection not only provides asymmetric encryption capabilities, but also provides flexible key storage and a consistent encryption and decryption interface (protect and unprotect). It was used in the session, it was used in the cookie validation, and it was openidconnect in the ... Of course, you can also use it in app development, such as this blog post, which is used to generate authentication tokens for the activation account.
First register the DataProtection service (the implementation of the injected Idataprotectionprovider interface) in Startup.configureservices ():
public void Configureservices (iservicecollection services) { services. Adddataprotection ();}
Then add the Idataprotectionprovider interface in the constructor of the class that uses dataprotection, create the dataprotector with that interface, then create the Securedataformat, and finally use the The Securedataformat.protect () method generates tokens for the activation account, decrypts tokens with securedataformat.uprotect (), and the complete sample code is as follows:
public class homecontroller:controller{ private readonly isecuredataformat<string> _dataformat; Public HomeController (Idataprotectionprovider _dataprotectionprovider) { var dataprotector = _ Dataprotectionprovider.createprotector (typeof (HomeController). FullName); _dataformat = new Securedataformat<string> (new Stringserializer (), dataprotector); } public string Generatetoken () { return _dataformat.protect (Guid.NewGuid (). ToString () + ";" + DateTime.Now.AddHours (Ten)); public string Decrypttoken (string token) { return _dataformat.unprotect (token); } Private class stringserializer:idataserializer<string> {public string deserialize (byte[] data) { return Encoding.UTF8.GetString (data); } Public byte[] Serialize (string model) { return Encoding.UTF8.GetBytes (model); } }
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.