SecureString

  class Program
{
static void Main()
{
SecureString s = new SecureString();
StringBuilder sb = new StringBuilder();
string sr = "";
sr.ToCharArray();
while (true)
{
ConsoleKeyInfo k = Console.ReadKey(true);
if (k.Key == ConsoleKey.Enter) break;
s.AppendChar(k.KeyChar);
Console.Write("*");
}
//Console.Write(s.ToString());没有重写ToString方法,就是为了避免泄漏敏感数据。
dispaly(s);
//public static void Main()//MSDN的例子
//{
//// Instantiate the secure string.
// SecureString securePwd = new SecureString();
// ConsoleKeyInfo key;

// Console.Write("Enter password: ");
// do
// {
// key = Console.ReadKey(true);

//// Ignore any key out of range.
// if (((int)key.Key) >= 65 && ((int)key.Key <= 90))
// {
//// Append the character to the password.
// securePwd.AppendChar(key.KeyChar);
// Console.Write("*");
// }
//// Exit if Enter key is pressed.
// } while (key.Key != ConsoleKey.Enter);
// Console.WriteLine();

// try
// {
// Process.Start("Notepad.exe", "Admin", securePwd, "MYDOMAIN");
// }
// catch (Win32Exception e)
// {
// Console.WriteLine(e.Message);
// }
Console.ReadKey();
}


unsafe static void dispaly(SecureString s)
{
char* c = null;
try
{
c = (char*)System.Runtime.InteropServices.Marshal.SecureStringToBSTR(s);//解密到一个非托管的内存缓存区中
for (int index = 0; c[index] != 0; index++)
{
Console.Write(c[index]);
}
}
catch (Exception)
{

throw;
}
finally
{
if (c != null)
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR((IntPtr)c);//释放包含以解密s字符的非托管内存缓冲区
}
}
}
原文地址:https://www.cnblogs.com/smailxiaobai/p/2289963.html