【发布时间】:2011-03-05 00:40:51
【问题描述】:
在 app.config 中加密 connstring 的最佳方式是什么?
- 使用
cryptography进行加解密,或者 - 使用
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef "connectionStrings" "C:\documents and settings\bob\projects\myproject",就像Protect App.Config file or Encrypt 中推荐的那样。
关注点:
1)如果我使用 Crytography,一切正常。除了每次遇到using (leDataContext db = new leDataContext()) 时都会调用下面这段代码,这让我觉得它会拖慢系统。
public partial class leDataContext
{
public leDataContext()
: base("")
// : base(ConfigurationManager.ConnectionStrings["leConnString"].ToString())
{
string decrypted = Cryptography.Decrypt(ConfigurationManager.ConnectionStrings["leConnString"].ToString());
base.Connection.ConnectionString = decrypted;
}
}
2) 如果我使用方法 2,听起来不错,因为它会自动进行加密。但是,当我使用 ClickOnce 发布时,是否应该将这些加密的 <CipherValue>rUmEA8h02uMZ5M4uEVtL+5M/UvPuyJ4UJz5d/P...</CipherValue> 保留在我的 app.conf 中?
这是因为方法2只能在客户端机器上完成。那么我是否应该在客户端机器上执行方法2,然后将那些加密的代码复制到一个文件中,并且每次我想使用clickOnce发布时,然后在发布之前将其手动复制回App.config,以便客户端更新正确连串?
密码学代码:
internal static string Encrypt(string sender, string key)
{
string text1;
if (sender == null) sender = "";
byte[] buffer4 = new byte[0];
byte[] buffer1 = buffer4;
byte[] buffer2 = new byte[] { 110, 120, 130, 140, 150, 160, 170, 180 };
try
{
buffer1 = Encoding.UTF8.GetBytes(key.Substring(0, 8));
DESCryptoServiceProvider provider1 = new DESCryptoServiceProvider();
byte[] buffer3 = Encoding.UTF8.GetBytes(sender);
MemoryStream stream1 = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream1, provider1.CreateEncryptor(buffer1, buffer2), CryptoStreamMode.Write);
stream2.Write(buffer3, 0, buffer3.Length);
stream2.FlushFinalBlock();
text1 = Convert.ToBase64String(stream1.ToArray());
}
catch (Exception ex)
{
text1 = string.Empty;
}
return text1;
}
你能建议吗?
【问题讨论】:
-
见stackoverflow.com/questions/2874614/…。它可能会回答你的一些问题。另外,你有没有定时看看第一个选项是否真的会导致减速?我认为与服务器建立连接比解密密钥更昂贵。
-
我已经尝试过第一个选项,我认为系统会变慢,但我只是担心当数据增加时它会变慢......想象一下你每次都必须运行那个加密代码初始化 datacontext()..
标签: c# encryption