C#:需要关于加密app.config中的连接字符串并将其保存在那里、解密并使用的帮助吗?
我需要有关在C#:需要关于加密app.config中的连接字符串并将其保存在那里、解密并使用的帮助吗?,c#,encryption,app-config,C#,Encryption,App Config,我需要有关在app.config中加密连接字符串并将其保存在那里并解密以供使用的帮助。您可以使用aspnet\u regiis.exe-pef。 看见 关于@Li0liQ的评论,您可以使用.NET Framework 2.0+aspnet\u regiis附带的命令行程序。查看MSDN文档如果要手动执行保护,可以使用classProtectedData。一些代码: class ConnectionStringProtector { readonly byte[] _salt = new
app.config
中加密连接字符串并将其保存在那里并解密以供使用的帮助。您可以使用aspnet\u regiis.exe-pef
。看见
关于@Li0liQ的评论,您可以使用.NET Framework 2.0+
aspnet\u regiis附带的命令行程序。查看MSDN文档如果要手动执行保护,可以使用classProtectedData
。一些代码:
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();
}
描述了一种参考实现。