tags:

views:

47

answers:

6

I am working on a small winform application. Here i am having some configuration settings e.g. User Name and password kinda stuff.

Now my requirement is that i want to encrypt this particular detail. So can somebody tell me as how this can be done in .NET (C#).

A: 

This article on Code Project describes how to encrypt and decrypt strings. It's a class you call, but the source code is provided so you can see how it works.

This article on Sharper Tutorials actually covers the case of encrypting a connection string.

Unfortunately both are too long to quote here.

ChrisF
A: 

You have some datas like this. Encrypt your data with these codes, and store it in appSettings. When u call them to use, decrypt to use.

<add key="SmtpServerHost" value="blablablabla" />
<add key="SmtpServerPost" value="25" />
<add key="SmtpServerUserName" value="blablablabla" />
<add key="SmtpServerPassword" value="blablablabla" />

then make a class library TripleDES.cs for ex.

and this is how to encrypt or decrypt your Appsetting values

public class TripleDes
{
    readonly byte[] _key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
    readonly byte[] _iv = { 8, 7, 6, 5, 4, 3, 2, 1 };

    // define the triple des provider
    private readonly TripleDESCryptoServiceProvider _mDes = new TripleDESCryptoServiceProvider();

    // define the string handler
    private readonly UTF8Encoding _mUtf8 = new UTF8Encoding();

    // define the local property arrays
    private readonly byte[] _mKey;
    private readonly byte[] _mIv;

    /// <summary>
    /// Default constructor
    /// </summary>
    public TripleDes()
    {
        _mKey = _key;
        _mIv = _iv;
    }

    /// <summary>
    /// Parameterized constructor
    /// </summary>
    /// <param name="key"></param>
    /// <param name="iv"></param>
    public TripleDes(byte[] key, byte[] iv)
    {
        _mKey = key;
        _mIv = iv;
    }

    /// <summary>
    /// Encrypts the given byte array input
    /// </summary>
    /// <param name="input">Input value</param>
    /// <returns>Encrypted result</returns>
    public byte[] Encrypt(byte[] input)
    {
        return Transform(input, _mDes.CreateEncryptor(_mKey, _mIv));
    }

    /// <summary>
    /// Decrypts the given encrypted byte array input
    /// </summary>
    /// <param name="input">Encrypted byte array input</param>
    /// <returns>Decrypted result</returns>
    public byte[] Decrypt(byte[] input)
    {
        return Transform(input, _mDes.CreateDecryptor(_mKey, _mIv));
    }

    /// <summary>
    /// Encrypts the given string input
    /// </summary>
    /// <param name="text">Input value</param>
    /// <returns>Encrypted result</returns>
    public string Encrypt(string text)
    {
        byte[] input = _mUtf8.GetBytes(text);
        byte[] output = Transform(input, _mDes.CreateEncryptor(_mKey, _mIv));
        return Convert.ToBase64String(output);
    }

    /// <summary>
    /// Decrypts the given encrypted string input
    /// </summary>
    /// <param name="text">Encrypted string input</param>
    /// <returns>Decrypted result</returns>
    public string Decrypt(string text)
    {
        byte[] input = Convert.FromBase64String(text);
        byte[] output = Transform(input, _mDes.CreateDecryptor(_mKey, _mIv));
        return _mUtf8.GetString(output);
    }

    private static byte[] Transform(byte[] input, ICryptoTransform cryptoTransform)
    {
        // create the necessary streams
        using (MemoryStream memStream = new MemoryStream())
        {
            using (CryptoStream cryptStream = new CryptoStream(memStream, cryptoTransform, CryptoStreamMode.Write))
            {
                // transform the bytes as requested
                cryptStream.Write(input, 0, input.Length);
                cryptStream.FlushFinalBlock();
                // Read the memory stream andconvert it back into byte array
                memStream.Position = 0;
                byte[] result = memStream.ToArray();
                // close and release the streams
                memStream.Close();
                cryptStream.Close();
                // hand back the encrypted buffer
                return result;
            }
        }
    }
}
Serkan Hekimoglu
A: 

You can use RsaProtectedConfigurationProvider http://msdn.microsoft.com/en-us/library/system.configuration.rsaprotectedconfigurationprovider.aspx

Maksym Markov
+1  A: 

You can encrypt sections of your app.config using DPAPI provider. Put your username/pwd pair in appSettings section. Nothing else need to change in your application. you still keep reading appsettings strings as usual. Use this code below to encrypt/decrypt parts of your config file.

//call: ProtectSection("appSettings","DataProtectionConfigurationProvider"); 
private void ProtectSection(string sectionName, string provider) 
{ 
    Configuration config = 
        WebConfigurationManager. 
            OpenWebConfiguration(Request.ApplicationPath); 

    ConfigurationSection section = config.GetSection(sectionName); 

    if (section != null && !section.SectionInformation.IsProtected) 
    { 
        section.SectionInformation.ProtectSection(provider); 
        config.Save(); 
    } 
} 

//call: UnProtectSection("appSettings"); 
private void UnProtectSection(string sectionName) 
{ 
    Configuration config = 
        WebConfigurationManager. 
            OpenWebConfiguration(Request.ApplicationPath); 

    ConfigurationSection section = config.GetSection(sectionName); 

    if (section != null && section.SectionInformation.IsProtected) 
    { 
        section.SectionInformation.UnprotectSection(); 
        config.Save(); 
    } 
} 
this. __curious_geek
A: 

There is build-in support for encrypting configuration files for ASP.NET applications using Windows Data Protection API but I have never tried if this can be applied to App.config, too. The advantage of this is that the keys are stored in a key store under control of the operating system.

Besides this I am not aware of any other build-in solutions and we usually do decryption ourself after reading the encrypted values. This requires to store a key somewhere - usually included in the code - and is far from optimal. Therefore if possible one should use Windows integrated security (SQL Sever authentication for example is deprecated) or any other advanced infrastructure like Kerberos if available.

Daniel Brückner
Works for **any** .NET application - see http://weblogs.asp.net/jgalloway/archive/2008/04/13/encrypting-passwords-in-a-net-app-config-file.aspx
marc_s
I already read it in another answer, good to know, thanks anyway!
Daniel Brückner