How to specify the encryption key when using the IDataProtectionProvider in ASP.NET Core 3.1 framework?

1.2k views Asked by At

I have a project written with C# on the top of the ASP.NET Core 3.1 framework.

I need to encrypt some data before it is stored. When the same data is read, I want to decrypt it. I found a way to do it using IDataProtectionProvider. However, the encryption key seems to be stored on the local machine.

How can I control where the key in kept? Also, Is there a way to control what should the key be?

1

There are 1 answers

0
Jay On BEST ANSWER

"Components which consume IDataProtectionProvider must pass a unique purposes parameter to the CreateProtector method."

from the main documentation - https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/consumer-apis/purpose-strings?view=aspnetcore-3.1

It would look something like this. (source)

_protectorTest = provider.CreateProtector("TestProtector");

Assuming you are using IDataProtectionProvider the correct way, the purpose string is under your control. You put it in your project.

For a simplistic case, you would keep this string in your own project, so the purpose string is available to use anytime you want. Of course, this is not what you want ideally.

For a more realistic scenario, you can consider any of the following options to properly store and retrieve your purpose key.

  • ProtectKeysWithAzureKeyVault
  • PersistKeysToFileSystem

more details here - https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-3.1