加密部分appConfig configSection c#

本文关键字:configSection appConfig 加密部 | 更新日期: 2023-09-27 18:14:55

我有自定义配置部分与服务器设置,其中包括:用户名,密码和服务器的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?

加密部分appConfig configSection c#

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

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

不可能只加密部分。如果您希望能够对UserName和Password值进行加密,则必须将它们放在单独的部分中。

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