正如瑞摩斯指出的那樣,有用戶/機器級加密提供。
我總是害怕這樣的事情,因爲這些數據可能會相對容易地丟失。
如果我是你,我會推出自己的系統。使用應用程序中硬編碼的密鑰加密連接字符串,轉換爲Base64,並將生成的加密連接字符串存儲在註冊表中。
下面的函數需要一個字符串,用AES-256和指定密鑰加密它和Base64的結果所以它的背部,作爲可打印字符串:
用法示例:
String connectionString = EncryptString(
"Provider=SQLOLEDB;Data Source=Lithium;User Id=sa;Password=hello",
"A fairly complicated password, like a guid: 8B4B0D73-84C9-4A1E-8DD2-9A189F84FD9B");
public static string EncryptString(string source, string key)
{
Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(key, salt);
byte[] derivedKey = deriveBytes.GetBytes(derivedKeySize);
Rijndael rijndael = Rijndael.Create();
rijndael.Mode = cipherMode;
rijndael.Padding = paddingMode;
rijndael.KeySize = keySize;
rijndael.BlockSize = blockSize;
rijndael.FeedbackSize = blockSize; // no bigger than the blocksize
rijndael.Key = derivedKey;
rijndael.IV = iv;
ICryptoTransform transform = rijndael.CreateEncryptor();
byte[] encoded = Encoding.UTF8.GetBytes(source);
byte[] target = transform.TransformFinalBlock(encoded, 0, encoded.Length);
return Convert.ToBase64String(target);
}
public static string DecryptString(string source, string key)
{
Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(key, salt);
byte[] derivedKey = deriveBytes.GetBytes(derivedKeySize);
Rijndael rijndael = Rijndael.Create();
rijndael.Mode = cipherMode;
rijndael.Padding = paddingMode;
rijndael.KeySize = keySize;
rijndael.BlockSize = blockSize;
rijndael.FeedbackSize = blockSize; // no bigger than the blocksize
rijndael.Key = derivedKey;
rijndael.IV = iv;
ICryptoTransform transform = rijndael.CreateDecryptor();
byte[] decoded = Convert.FromBase64String(source);
byte[] target = transform.TransformFinalBlock(decoded, 0, decoded.Length);
return Encoding.UTF8.GetString(target);
}
private static readonly byte[] iv = {
0x30,0xA6,0x65,0xDE,0x8C,0x63,0x17,0x44,
0xB6,0xFD,0xEA,0x5F,0x76,0xA1,0x1C,0x5F
};
private static readonly byte[] salt = {
0xF9,0x39,0x0C,0xE0,0x22,0xE0,0x8E,0x84,
0xB2,0x05,0x1E,0xA8,0x6D,0x1C,0x39,0xAC
};
private const int keySize = 256;
private const int blockSize = 128;
private const CipherMode cipherMode = CipherMode.CBC;
private const PaddingMode paddingMode = PaddingMode.PKCS7;
private const int derivedKeySize = 32;
看來,我可以使用DPAPI,並存儲在用戶存儲的關鍵,所以它不是在機器上的任何其他用戶訪問。這看起來正是我想要做的 - 謝謝! – SqlRyan 2009-07-01 20:55:56
我在這裏結束了使用相同的修改後的版本:http://www.obviex.com/samples/dpapi.aspx – SqlRyan 2009-07-01 21:03:16