加密部分appConfig configSection c#

时间:2011-11-16 13:20:47

标签: c# .net encryption app-config

我有自定义配置部分,其中包含服务器设置,包括:用户名,密码和服务器的IP;我需要使用以下类型获得加密配置:

<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>

我可以加密整个configSection,但不能加密它。谁知道如何只加密configSection的部分?

3 个答案:

答案 0 :(得分:4)

您可以手动加密和解密它们

    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;
    }

答案 1 :(得分:2)

无法仅加密部分的部分内容。如果您希望能够对UserName和Password值进行加密,则必须将UserName和Password值放入单独的部分。

答案 2 :(得分:0)

App.config根本不是存储安全凭据的好地方!