zoukankan      html  css  js  c++  java
  • 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字符的非托管内存缓冲区
    }
    }
    }
  • 相关阅读:
    复杂JSON字符串转换为Java嵌套对象的方法
    好代码是如何炼成的
    让数据流转换代码更加健壮流畅:List的Stream包装
    由一个重构示例引发的对可扩展性的思考
    如何高效搜索信息
    个人安全防护简明指南
    YAML配置解析
    事件处理业务的简易组件编排框架
    lambda表达式滥用之殇:解耦三层嵌套lambda表达式
    碎碎念四六
  • 原文地址:https://www.cnblogs.com/smailxiaobai/p/2289963.html
Copyright © 2011-2022 走看看