This ASP.NET Security tutorial explains how to manage secret keys in ASP.NET.
Microsoft Windows supports a built-in way for storing and protecting secrets and it uses a machine key generated with the system installation for encrypting data. Only the local operating system has access to this machine key which is unique for every installation. Windows supports the DPAPI for protecting data with this key. You don’t have direct access to the key when using this API. You can ask the system to encrypt or decrypt something with the machine’s key. In this way your application could encrypt the key used by it through DPAPI and .NET Framework supports the class System.Security.Cryptography.ProtectedData, which you can use as follows:
byte ProtData = ProtectedData.Protect(ClearBytes, null, DataProtectionScope.LocalMachine);
Dim ProtData As Byte() = ProtectedData.Protect(ClearBytes, Nothing, DataProtectionScope.LocalMachine)
1. You should add a reference to the System.Security.dll assembly and import the System.Security.Cryptography namespace when you want to use the ProtectedData class for protecting sensitive information. Possible scopes are LocalMachine and CurrentUser.
2. You can select the LocalMachine when you want to use the machine key.
3. You can select the CurrentUser when you want to use a key generated for the currently logged-on user’s profile. In the case of Active Directory roaming profiles that allow reusing a Windows user profile on several Windows machines within an Active Directory domain, this key is machine independent.
4. Administrator of the machine can decrypt the data by writing a program that calls the previous function.
5. If the user is not the administrator and has no permission to use the DPAPI, he/she cannot decrypt data encrypted with the machine key.
6. You should not use DPAPI to encrypt information in your database, because encrypted data is bound to the machine if you use the DataProtectionScope.LocalMachine setting. If the machine crashes and you have to restore your data on another machine, you will lose all the encrypted information.
7. You should have a backup of the key in another secure place, if you use the DPAPI for encrypting the key as described previously.
8. You have to run your application under a domain user account and use the key created for the user’s profile (DataProtectionScope.CurrentUser) if you want to use the DPAPI in web farm scenarios. You should create a separate domain for your web farm so that you don’t have to use a domain user of your company’s internal domain network.