Critical Developers

Programmers Knowledge Base

Encrypt Decrypt in ASP.Net Core

Here we will discuss encryption and decryption with an example in asp.net core.
We use Protect() and Unprotect() methods of IDataProtector interface in ASP.Net Core to encrypt and decrypt respectively.
Using IDataProtector we can encrypt/decrypt querystring, any sensitive data, connection string and etc.
So Lets start,

Create a class as shown below:-

using Microsoft.AspNetCore.DataProtection;
namespace MyDemo
{
    public class CustomIDataProtection
    {
        private readonly IDataProtector _protector;
        public CustomIDataProtection(IDataProtectionProvider provider)
        {
            _protector = provider.CreateProtector("YOURSECRETKEY"); // you can pass any string as key
        }
        public string ProtectData(string data)
        {
            return _protector.Protect(data);
        }
        public string UnProtectData(string data)
        {
            return _protector.Unprotect(data);
        }
    }
}

Now In your PageModel or Controller use above class as shown below:-

    public class IndexModel : PageModel
    {
        private readonly CustomIDataProtection _protector;
        public IndexModel(CustomIDataProtection provider)
        {
            _protector = provider;
        }
        public void OnGet()
        {
	string encrypted= _protector.ProtectData("mysensitivedata");
	string decrypted= _protector.UnProtectData(encrypted);
        }
   }

Thats it !!
Comments are closed