簡體   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連接字符串並將其保存在那里並解密它以供使用。

您可以使用aspnet_regiis.exe -pef
有關進一步說明,請參閱加密ASP.NET V2.0中的連接字符串加密ASP.NET 2.0文章中的Web.Config值

如果要手動執行保護,可以使用ProtectedData類。 一些代碼:

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

這是一個簡單的測試:

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

繼@ Li0liQ的評論之后,您可以使用.NET Framework 2.0+ aspnet_regiis附帶的命令行程序。 在這里查看MSDN文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM