SecureString

作者:互联网   出处:控件中国网   2014-11-05 19:22:00   阅读:1

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字符的非托管内存缓冲区
            }
        }
    }

Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat