public static class Program
{
public static void Main()
{
using (SecureString ss = new SecureString())
{
Console.Write("Please enter password: ");
while (true)
{
ConsoleKeyInfo cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.Enter) break;
// Append password characters into the SecureString
ss.AppendChar(cki.KeyChar);
Console.Write("*");
}
Console.WriteLine();
// Password entered, display it for demonstration purposes
DisplaySecureString(ss);
}
// After 'using', the SecureString is Disposed; no sensitive data in memory
}
// This method is unsafe because it accesses unmanaged memory
private unsafe static void DisplaySecureString(SecureString ss)
{
Char* pc = null;
try
{
// Decrypt the SecureString into an unmanaged memory buffer
pc = (Char*)Marshal.SecureStringToCoTaskMemUnicode(ss);
// Access the unmanaged memory buffer that
// contains the decrypted SecureString
for (Int32 index = 0; pc[index] != 0; index++)
Console.Write(pc[index]);
}
finally
{
// Make sure we zero and free the unmanaged memory buffer that contains
// the decrypted SecureString characters
if (pc != null)
Marshal.ZeroFreeCoTaskMemUnicode((IntPtr)pc);
}
}
}
2 回答
您将无法将其隐藏于已经有权访问您的计算机的确定攻击者以及您的Windows用户名和密码 .
话虽这么说,ProtectedData class可能是使没有适当凭据的用户无法访问数据的最简单方法 .
是的,如果将密钥存储为简单字符串,则可以读取密钥 . 但是您可以使用SecureString类并最小化易失性访问 .
此外,永远不要将SecureString的内容放入String:如果这样做,String将在堆中保持未加密状态,并且在垃圾收集后重复使用内存之前不会将其字符清零 .
CLR通过C#的示例: