|
using System;
using System.Configuration;
namespace ConfigEncryption
{
public class ConfigUtility
{
/// <summary>
/// Encrypt the config file an save it
/// </summary>
public static void ConfigEncryptToFile()
{
string encrypted = ConfigurationManager.AppSettings.Get("Encrypted");
if (encrypted == null || !encrypted.Equals("True"))
{
string keysToEncrypt = ConfigurationManager.AppSettings.Get("KeysToEncrypt");
if (keysToEncrypt != null && keysToEncrypt.Length > 0)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection appSettings = config.AppSettings;
string[] keys = keysToEncrypt.Split(',');
foreach (string key in keys)
{
KeyValueConfigurationElement kv = appSettings.Settings[key];
if (kv != null)
{
kv.Value = EncryptUtility.EncryptString(EncryptUtility.ToSecureString(kv.Value));
}
}
appSettings.Settings.Add("Encrypted", "True");
config.Save(ConfigurationSaveMode.Modified);
}
}
}
/// <summary>
/// Decrypt configuration settings into memory
/// </summary>
public static void ConfigDecryptToMemory()
{
ConfigurationManager.RefreshSection("appSettings");
string encrypted = ConfigurationManager.AppSettings.Get("Encrypted");
if (encrypted != null && encrypted.Equals("True"))
{
string keysToDecrypt = ConfigurationManager.AppSettings.Get("KeysToEncrypt");
string[] keys = keysToDecrypt.Split(',');
foreach (string key in keys)
{
string value = ConfigurationManager.AppSettings.Get(key);
value = EncryptUtility.ToInsecureString(EncryptUtility.DecryptString(value));
ConfigurationManager.AppSettings.Set(key, value);
}
}
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Check our technical blog for more tips and articles @ https://curbsidr.com/blog/