如何用自己创建的密钥,以及使用它来加密和解密app.config程序配置?关于加密程序配置,RsaProtectedConfigurationProvider类里面的例子可以加密和解密app.config。用同样的方法,我把app.config里面的连接字符串加了密之后,结果程序却只能在我自己的机器里能解密正常运行程序,在别人的机器就不行了。把msdn看了老半天,从msdn中对web.config的加密内容看,好像可以自己创建密钥,用来加密web.config,然后在别的机器导入密钥,这样就可以在别的机器上使用加了密的web.config了。但msdn上说的都是asp.net的web.config,到处都找不到对winform的app.config怎么弄。对Winform的app.config,是否也可以向web.config的方式那样处理加密呢?创建密钥、导出、导入密钥以及加密解密配置节都要用到那些类?最好能够给出代码细节。
const int validationKeyLength = 64;
// 24 bytes is max size supported by ASP.NET (3DES)
const int decryptionKeyLength = 24; static string GenerateKey()
{ StringBuilder sb = new StringBuilder();
sb.Append("<machineKey validationKey='"); sb.Append(writeKeyAsHexDigits(getRandom(validationKeyLength))); sb.Append("'");
sb.Append(" decryptionKey='"); sb.Append(writeKeyAsHexDigits(getRandom(decryptionKeyLength))); sb.Append("'");
sb.Append(" validation='SHA1'/>");
return sb.ToString();
}
static byte[] getRandom(int cb)
{
byte[] randomData = new byte[cb];
srng.GetBytes(randomData);
return randomData;
}
static string writeKeyAsHexDigits(byte[] key)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < key.Length; ++i)
{ sb.Append(String.Format("{0:X2}", key[i])); }
return sb.ToString();
} protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = GenerateKey();
}