Basic of Data Protection
- Asp.net Core came up with the nice solution for protecting data.
- When ever we say data protection it relates us to Encryption and decryption of data.
- Now no more machine key related methods, that was in asp.net where we where storing machine key in to web.config file for each application.
- System.Web.Security.MachineKey.Protect();
- System.Web.Security.MachineKey.UnProtect();
- It was hard to handle the situation where we were mess up with multiple machine key and it was very confusing to use which key to decrypt data.
- Swapping application on other system and
- Web farm
What we have now are
- Key on demand, Now we an use any of them
- Custom algorithm
- Digital certificate
- Shareable Key, We can store key in shared location like
- Shareable Directory
- Local Store
- HSM/Azure vault
- Auto key rotation, Application tack care of expiration of key and creation of new key.
- (n - level) isolation for different context. Set key on each level of processing.
Building blocks
IDataProtectionProvider
Factory used to create IDataProtection instances.
IDataProtector
Service used to protect and unprotect data.
IServiceCollection.AddDataProtection()
Service configuration used to protect and unprotect data.
Snippet looks like
services.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(@"D:\\DotNetCore\\Shareable"))//"\\server\share directory\", default %appdata%
.UseCryptographicAlgorithms(
new AuthenticatedEncryptorConfiguration()
{
EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
}); ;
// .ProtectKeysWithCertificate("5AD833A5B4AE808BB68A2BEDEE9248AB79F292A6");//thumbprint of digital certificate
//.SetDefaultKeyLifetime(TimeSpan.FromMinutes(14));//default is 90 days, minimum is 7 days
.PersistKeysToFileSystem(new DirectoryInfo(@"D:\\DotNetCore\\Shareable"))//"\\server\share directory\", default %appdata%
.UseCryptographicAlgorithms(
new AuthenticatedEncryptorConfiguration()
{
EncryptionAlgorithm = EncryptionAlgorithm.AES_256_CBC,
ValidationAlgorithm = ValidationAlgorithm.HMACSHA256
}); ;
// .ProtectKeysWithCertificate("5AD833A5B4AE808BB68A2BEDEE9248AB79F292A6");//thumbprint of digital certificate
//.SetDefaultKeyLifetime(TimeSpan.FromMinutes(14));//default is 90 days, minimum is 7 days
dataProtector = _dataProtectionProvider.CreateProtector("HomeInstance");
string PlainText = "AspTricks.net";
string EncryptedText = dataProtector.Protect(PlainText);
string DecryptedText = dataProtector.Unprotect(EncryptedText);
string PlainText = "AspTricks.net";
string EncryptedText = dataProtector.Protect(PlainText);
string DecryptedText = dataProtector.Unprotect(EncryptedText);