简体   繁体   English

C#:需要帮助加密app.config中的连接字符串并将其保存在那里并解密并使用?

[英]C#: Need for help on encrypting connection string in app.config and save it there and decrypting it and use?

我需要帮助加密app.config连接字符串并将其保存在那里并解密它以供使用。

You can use aspnet_regiis.exe -pef for that. 您可以使用aspnet_regiis.exe -pef
See Encrypting the connection string in ASP.NET V2.0 and Encrypting Web.Config Values in ASP.NET 2.0 articles for further explanations. 有关进一步说明,请参阅加密ASP.NET V2.0中的连接字符串加密ASP.NET 2.0文章中的Web.Config值

If you want to do protection manually, you can use class ProtectedData . 如果要手动执行保护,可以使用ProtectedData类。 Some code: 一些代码:

class ConnectionStringProtector
{
    readonly byte[] _salt = new byte[] { 1, 2, 3, 4, 5, 6 };  // Random values
    readonly Encoding _encoding = Encoding.Unicode;
    readonly DataProtectionScope _scope = DataProtectionScope.LocalMachine;

    public string Unprotect(string str)
    {
        var protectedData = Convert.FromBase64String(str);
        var unprotected = ProtectedData.Unprotect(protectedData, _salt, _scope);
        return _encoding.GetString(unprotected);
    }

    public string Protect(string unprotectedString)
    {
        var unprotected = _encoding.GetBytes(unprotectedString);
        var protectedData = ProtectedData.Protect(unprotected, _salt, _scope);
        return Convert.ToBase64String(protectedData);
    }
}

here's a simple test: 这是一个简单的测试:

static void Main(string[] args)
{
    var originalConnectionString = "original string";

    var protector = new ConnectionStringProtector();

    var protectedString = protector.Protect(originalConnectionString);
    Console.WriteLine(protectedString);
    Console.WriteLine();

    var unprotectedConnectionString = protector.Unprotect(protectedString);
    Console.WriteLine(unprotectedConnectionString);

    Console.WriteLine("Press ENTER to finish");
    Console.ReadLine();
}

Further to @Li0liQ's comment, you can use the command line program that comes with the .NET Framework 2.0+ aspnet_regiis . 继@ Li0liQ的评论之后,您可以使用.NET Framework 2.0+ aspnet_regiis附带的命令行程序。 Check out the MSDN documentation here 在这里查看MSDN文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM