shreyas35
shreyas35

Reputation: 175

How can I add key protection in web.config for .NET 4.5 framework

I want to add protection key in web.config file (for .NET framework 4.5) as we add api key in web api. How can I go about this?

Should I use following key type:

<machineKey validationKey="..." decryption="3DES" 
            compatibilityMode="Framework20SP2" decryptionKey="..." 
            validation="3DES" />

Thanks in advance

Upvotes: 0

Views: 392

Answers (1)

JJablonski
JJablonski

Reputation: 31

Here I share you an example with protectedData class:

using System.Configuration;
using System.Security.Cryptography;
using System.Text;

// Encrypts a string using the ProtectedData class
private static byte[] ProtectString(string text)
{
    byte[] textBytes = Encoding.Unicode.GetBytes(text);
    return ProtectedData.Protect(textBytes, null, DataProtectionScope.LocalMachine);
}

// Decrypts a byte array using the ProtectedData class
private static string UnprotectBytes(byte[] encryptedBytes)
{
    byte[] unprotectedBytes = ProtectedData.Unprotect(encryptedBytes, null, DataProtectionScope.LocalMachine);
    return Encoding.Unicode.GetString(unprotectedBytes);
}

// Store the protected key in the web.config file
private static void StoreProtectedKey(string key)
{
    byte[] protectedBytes = ProtectString(key);
    string base64String = Convert.ToBase64String(protectedBytes);

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    config.AppSettings.Settings["ApiKey"].Value = base64String;
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");
}

// Retrieve the protected key from the web.config file
private static string RetrieveProtectedKey()
{
    string base64String = ConfigurationManager.AppSettings["ApiKey"];
    byte[] protectedBytes = Convert.FromBase64String(base64String);
    return UnprotectBytes(protectedBytes);
}

To store the protected key, you can call the StoreProtectedKey method, passing in the key you want to protect:

string apiKey = "your_api_key_here";
StoreProtectedKey(apiKey);

This method will encrypt the key using the ProtectedData class and store the encrypted value in the web.config file.

To retrieve the protected key, you can call the RetrieveProtectedKey method:

string apiKey = RetrieveProtectedKey();

This method will retrieve the encrypted key from the web.config file, decrypt it using the ProtectedData class, and return the original key.

Remember to handle exceptions, secure the web.config file, and apply appropriate access controls to protect the encryption keys.

Upvotes: 1

Related Questions