Timur Mustafaev
Timur Mustafaev

Reputation: 4929

Encrypt part of appConfig configSection c#

I have custom config section with Server settings, which includes: username, password and IP of the server; I need to get encrypted config with this type:

<ApplicationServerConfiguration>
  <Server UserName="ASDASDASDASDAS [Some encrypted value] ASDASDASF"/>
  <Server Password="ASDASDASDASDAS [Some encrypted value] ASDASDASF"/>
  <Server ServerAddress="192.168.255.255"/> **Not encrypted value!**
</ApplicationServerConfiguration>

I can encrypt whole configSection, but not part of it. Who knows how to encrypt just parts of configSection?

Upvotes: 1

Views: 537

Answers (3)

Matt Smucker
Matt Smucker

Reputation: 5244

You could manually encrypt and decrypt them

    private static string EncryptString(string Value)
    {
        string ReturnValue = string.Empty;

        MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
        byte[] TDESKey = HashProvider.ComputeHash(ASCIIEncoding.ASCII.GetBytes("Bermuda"));

        using (TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider())
        {
            provider.Key = TDESKey;
            provider.Mode = CipherMode.ECB;
            provider.Padding = PaddingMode.PKCS7;

            ICryptoTransform Encryptor = provider.CreateEncryptor();
            byte[] ByteValue = ASCIIEncoding.ASCII.GetBytes(Value);

            ReturnValue = Convert.ToBase64String(Encryptor.TransformFinalBlock(ByteValue, 0, ByteValue.Length));
        }

        return ReturnValue;
    }
    private static string DecryptString(string EncryptedValue)
    {
        string ReturnValue = string.Empty;

        MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
        byte[] TDESKey = HashProvider.ComputeHash(ASCIIEncoding.ASCII.GetBytes("Bermuda"));

        using (TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider())
        {
            provider.Key = TDESKey;
            provider.Mode = CipherMode.ECB;
            provider.Padding = PaddingMode.PKCS7;

            ICryptoTransform Decryptor = provider.CreateDecryptor();
            byte[] ByteValue = Convert.FromBase64String(EncryptedValue);

            ReturnValue = ASCIIEncoding.ASCII.GetString(Decryptor.TransformFinalBlock(ByteValue, 0, ByteValue.Length));
        }

        return ReturnValue;
    }

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1039498

It is not possible to encrypt only part of a section. You will have to put the UserName and Password values into a separate section if you want to be able to encrypt them.

Upvotes: 2

Fischermaen
Fischermaen

Reputation: 12468

The App.config isn't a good place at all to store security credentials!

Upvotes: 0

Related Questions