RemoveAt() public method

public RemoveAt ( int index ) : void
index int
return void
Ejemplo n.º 1
0
        public static SecureString GetSecureStringFromConsole()
        {
            var password = new SecureString();

            Console.Write("Enter Password: ");
            while (true)
            {
                ConsoleKeyInfo cki = Console.ReadKey(true);

                if (cki.Key == ConsoleKey.Enter) break;
                if (cki.Key == ConsoleKey.Escape)
                {
                    password.Dispose();
                    return null;
                }
                if (cki.Key == ConsoleKey.Backspace)
                {
                    if (password.Length != 0)
                        password.RemoveAt(password.Length - 1);
                }
                else password.AppendChar(cki.KeyChar);
            }

            return password;
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Reads a password from the user in a safe fashion.
        /// </summary>
        /// <param name="prompt">A string, shown to the user as prompt.</param>
        /// <returns>An instance of <see cref="SecureString"/>.</returns>
        public SecureString ReadPassword(string prompt)
        {
            Console.WriteLine(prompt);

            // http://stackoverflow.com/questions/3404421/password-masking-console-application

            Console.Write("Password: "******"\b \b");
                    }
                }
                else
                {
                    pwd.AppendChar(i.KeyChar);
                    //Console.Write("*");
                }
            }
            Console.WriteLine();
            return pwd;
        }
Ejemplo n.º 3
0
		private SecureString takePassword ()
		{
			SecureString result = new SecureString();

			Console.Write("Password: "******"\b \b");
					}
				}
				else if (i.Key == ConsoleKey.Spacebar || result.Length > 20) {}
				else
				{
					result.AppendChar(i.KeyChar);
					Console.Write("*");
				}
			}
			Console.WriteLine();

			return result;
		}
        /// <summary>
        /// Get a password from the console
        /// </summary>
        /// <returns>Password stored in a SecureString</returns>
        private static SecureString GetPassword()
        {
            var password = new SecureString();
            while (true)
            {
                var keyInfo = Console.ReadKey(true);
                if (keyInfo.Key == ConsoleKey.Enter)
                {
                    break;
                }

                if (keyInfo.Key == ConsoleKey.Backspace)
                {
                    if (password.Length > 0)
                    {
                        password.RemoveAt(password.Length - 1);
                        Console.Write("\b \b");
                    }
                }
                else
                {
                    password.AppendChar(keyInfo.KeyChar);
                    Console.Write("*");
                }
            }
            return password;
        }
Ejemplo n.º 5
0
 public static SecureString ReadConsoleByKeySecure(bool hideCharacters = false)
 {
     var running = true;
     var finalString = new SecureString();
     while (running)
     {
         var letter = Console.ReadKey(hideCharacters).KeyChar;
         if (letter == (char)13)
             running = false;
         else if (letter == (char)8 && finalString.Length >= 1)
         {
             finalString.RemoveAt(finalString.Length - 1);
             Console.CursorLeft--;
             Console.Write('\0');
             Console.CursorLeft--;
         }
         else if (letter != (char)8)
         {
             finalString.AppendChar(letter);
             if (hideCharacters)
                 Console.Write('*');
         }
     }
     Console.WriteLine();
     return finalString;
 }
Ejemplo n.º 6
0
		public unsafe void UnsafeConstructor ()
		{
			try {
				SecureString ss = null;
				char[] data = new char[] { 'a', 'b', 'c' };
				fixed (char* p = &data[0]) {
					ss = new SecureString (p, data.Length);
				}
				Assert.IsFalse (ss.IsReadOnly (), "IsReadOnly");
				Assert.AreEqual (3, ss.Length, "3");
				ss.AppendChar ('a');
				Assert.AreEqual (4, ss.Length, "4");
				ss.Clear ();
				Assert.AreEqual (0, ss.Length, "0b");
				ss.InsertAt (0, 'b');
				Assert.AreEqual (1, ss.Length, "1b");
				ss.SetAt (0, 'c');
				Assert.AreEqual (1, ss.Length, "1c");
				ss.RemoveAt (0);
				Assert.AreEqual (0, ss.Length, "0c");
				ss.Dispose ();
			}
			catch (NotSupportedException) {
				Assert.Ignore (NotSupported);
			}
		}
Ejemplo n.º 7
0
 public static SecureString EnterPassword()
 {
     SecureString pwd = new SecureString();
     while (true)
     {
         ConsoleKeyInfo i = Console.ReadKey(true);
         if (i.Key == ConsoleKey.Enter)
         {
             break;
         }
         else if (i.Key == ConsoleKey.Backspace)
         {
             if (pwd.Length > 0)
             {
                 pwd.RemoveAt(pwd.Length - 1);
                 Console.Write("\b \b");
             }
         }
         else
         {
             pwd.AppendChar(i.KeyChar);
             Console.Write("*");
         }
     }
     return pwd;
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Read a password from the console and return it as SecureString
        /// </summary>
        /// <returns></returns>
        public static bool ReadPasswordFromConsole(out SecureString secStr)
        {
            secStr = new SecureString();

            for (ConsoleKeyInfo c = Console.ReadKey(true); c.Key != ConsoleKey.Enter; c = Console.ReadKey(true))
            {
                if (c.Key == ConsoleKey.Backspace && secStr.Length > 0)
                    secStr.RemoveAt(secStr.Length - 1);

                if (c.Key == ConsoleKey.Escape)
                {
                    // cancel
                    secStr.Dispose();
                    Console.WriteLine();
                    return false;
                }

                if (!Char.IsControl(c.KeyChar))
                    secStr.AppendChar(c.KeyChar);
            }

            secStr.MakeReadOnly();
            Console.WriteLine();
            return true;
        }
Ejemplo n.º 9
0
 public static SecureString ReadSecureString(string prompt)
 {
     const string t = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
     SecureString securePwd = new SecureString();
     ConsoleKeyInfo key;
     Console.Write(prompt);
     Console.Write(':');
     do
     {
         key = Console.ReadKey(true);
         if (t.IndexOf(key.KeyChar) != -1)
         {
             securePwd.AppendChar(key.KeyChar);
             Console.Write('*');
         }
         else if (key.Key == ConsoleKey.Backspace && securePwd.Length > 0)
         {
             securePwd.RemoveAt(securePwd.Length - 1);
             Console.Write(key.KeyChar);
             Console.Write(' ');
             Console.Write(key.KeyChar);
         }
     } while (key.Key != ConsoleKey.Enter);
     Console.WriteLine();
     securePwd.MakeReadOnly();
     return securePwd;
 }
Ejemplo n.º 10
0
        // secure string for passwords or secret string data
        public static void SecureStringUsingExample()
        {
            using (SecureString securePassword = new SecureString())
            {
                // getting
                while (true)
                {
                    ConsoleKeyInfo cki = Console.ReadKey(true);


                    if (cki.Key == ConsoleKey.Enter)
                    {
                        Console.WriteLine();
                        break;
                    }

                    if (cki.Key == ConsoleKey.Backspace)
                    {
                        if (securePassword.Length > 0)
                        {
                            securePassword.RemoveAt(securePassword.Length - 1);
                            Console.Write("-");
                        }
                        continue;
                    }

                    securePassword.AppendChar(cki.KeyChar);
                    Console.Write("*");
                }


                // showing
                unsafe
                {
                    char* buffer = null;

                    try
                    {
                        // decrypting
                        buffer = (char*)Marshal.SecureStringToCoTaskMemUnicode(securePassword);

                        for (var i = 0; buffer[i] != 0; i++)
                            Console.Write(buffer[i]);
                    }
                    finally
                    {
                        // buffer clearing
                        if (buffer != null) Marshal.ZeroFreeCoTaskMemUnicode((IntPtr)buffer);
                    }
                }


                securePassword.Dispose(); // not necessary in using construction
            }
        }
Ejemplo n.º 11
0
        private static SecureString GetPasswordFromConsole()
        {
            SecureString password = new SecureString();
            bool readingPassword = true;

            Console.Write("Enter password: "******" ");
                            Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        }
                        break;
                    default:
                        if (userInput.KeyChar != 0)
                        {
                            password.AppendChar(userInput.KeyChar);
                            Console.Write("*");
                        }
                        break;
                }
            }
            Console.WriteLine();

            password.MakeReadOnly();
            return password;
        }
        public static SecureString ReadLineAsSecureString()
        {
            var secureString = new SecureString();

            try
            {
                ConsoleKeyInfo keyInfo;
                while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter)
                {
                    if (keyInfo.Key == ConsoleKey.Backspace)
                    {
                        if (secureString.Length < 1)
                        {
                            continue;
                        }
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        Console.Write(' ');
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        secureString.RemoveAt(secureString.Length - 1);
                    }
                    else
                    {
                        secureString.AppendChar(keyInfo.KeyChar);
                        Console.Write('*');
                    }
                }
                Console.WriteLine(String.Empty);
            }
            catch (InvalidOperationException)
            {
                // This can happen when you redirect nuget.exe input, either from the shell with "<" or 
                // from code with ProcessStartInfo. 
                // In this case, just read data from Console.ReadLine()
                foreach (var c in Console.ReadLine())
                {
                    secureString.AppendChar(c);
                }
            }

            secureString.MakeReadOnly();
            return secureString;
        }
Ejemplo n.º 13
0
 private bool ReadKey(SecureString buffer)
 {
     ConsoleKeyInfo i = Console.ReadKey(true);
     if (i.Key == ConsoleKey.Enter)
     {
         return true;
     }
     else if (i.Key == ConsoleKey.Backspace)
     {
         if (buffer.Length > 0)
         {
             buffer.RemoveAt(buffer.Length - 1);
             Console.Write("\b \b");
         }
     }
     else
     {
         buffer.AppendChar(i.KeyChar);
         Console.Write("*");
     }
     return false;
 }
Ejemplo n.º 14
0
		public void DefaultConstructor ()
		{
			try {
				SecureString ss = new SecureString ();
				Assert.IsFalse (ss.IsReadOnly (), "IsReadOnly");
				Assert.AreEqual (0, ss.Length, "0");
				ss.AppendChar ('a');
				Assert.AreEqual (1, ss.Length, "1");
				ss.Clear ();
				Assert.AreEqual (0, ss.Length, "0b");
				ss.InsertAt (0, 'b');
				Assert.AreEqual (1, ss.Length, "1b");
				ss.SetAt (0, 'c');
				Assert.AreEqual (1, ss.Length, "1c");
				Assert.AreEqual ("System.Security.SecureString", ss.ToString (), "ToString");
				ss.RemoveAt (0);
				Assert.AreEqual (0, ss.Length, "0c");
				ss.Dispose ();
			}
			catch (NotSupportedException) {
				Assert.Ignore (NotSupported);
			}
		}
Ejemplo n.º 15
0
        /// <summary>
        /// Helper to return the password
        /// </summary>
        /// <returns>SecureString representing the password</returns>
        public static SecureString GetPassword()
        {
            SecureString sStrPwd = new SecureString();

            try
            {
                Console.Write("SharePoint Password: "******" ");
                            Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        }
                    }
                    else if (keyInfo.Key != ConsoleKey.Enter)
                    {
                        Console.Write("*");
                        sStrPwd.AppendChar(keyInfo.KeyChar);
                    }

                }
                Console.WriteLine("");
            }
            catch (Exception e)
            {
                sStrPwd = null;
                Console.WriteLine(e.Message);
            }

            return sStrPwd;
        }
Ejemplo n.º 16
0
 public System.Security.SecureString ReadLineAsSecureString()
 {
     SecureString secret = new SecureString();
     ConsoleKeyInfo currentKey;
     while ((currentKey = Console.ReadKey(true)).Key != ConsoleKey.Enter)
     {
         if (currentKey.Key == ConsoleKey.Backspace)
         {
             if (secret.Length > 0)
             {
                 secret.RemoveAt(secret.Length - 1);
                 Console.Write(currentKey.KeyChar);
             }
         }
         else
         {
             secret.AppendChar(currentKey.KeyChar);
             Console.Write("*");
         }
     }
     Console.WriteLine();
     secret.MakeReadOnly();
     return secret;
 }
Ejemplo n.º 17
0
 public static SecureString GetPassword()
 {
     using (SecureString _pwd = new SecureString ())
     {
         while (true)
         {
             ConsoleKeyInfo i = Console.ReadKey (true);
             if (i.Key == ConsoleKey.Enter || i.Key == (ConsoleKey)0)
             {
                 break;
             }
             if (i.Key != ConsoleKey.Backspace)
             {
                 _pwd.AppendChar (i.KeyChar);
                 Console.Write ("*");
             } else if (_pwd.Length > 0)
             {
                 _pwd.RemoveAt (_pwd.Length - 1);
                 Console.Write ("\b \b");
             }
         }
         return _pwd;
     }
 }
Ejemplo n.º 18
0
 char[] getSecureText()
 {
     SecureString pwd = new SecureString ();
     while (true)
     {
         ConsoleKeyInfo i = Console.ReadKey (true);
         if (i.Key == ConsoleKey.Enter)
         {
             break;
         }
         if (i.Key == ConsoleKey.Backspace)
         {
             if (pwd.Length > 0)
             {
                 pwd.RemoveAt (pwd.Length - 1);
                 Console.Write ("\b \b");
             }
         } else
         {
             pwd.AppendChar (i.KeyChar);
             Console.Write ("*");
         }
     }
     Console.WriteLine ();
     return GetSecureArray (pwd);
 }
Ejemplo n.º 19
0
 private static SecureString ReadPassword()
 {
     var ret = new SecureString();
     while (true)
     {
         var info = Console.ReadKey(true);
         if (info.Key == ConsoleKey.Enter)
         {
             Console.WriteLine();
             Console.WriteLine();
             return ret;
         }
         if (info.Key == ConsoleKey.Backspace)
         {
             if (ret.Length > 0)
             {
                 ret.RemoveAt(ret.Length - 1);
             }
         }
         else
         {
             ret.AppendChar(info.KeyChar);
         }
     }
 }
Ejemplo n.º 20
0
		public void RemoveAt_BiggerThanLength ()
		{
			SecureString ss = new SecureString ();
			ss.RemoveAt (1);
		}
Ejemplo n.º 21
0
        private static SecureString GetSecPswd(String prompt)
        {
            SecureString password = new SecureString();

            Console.ForegroundColor = ConsoleColor.Gray;
            Console.Write(prompt);
            Console.ForegroundColor = ConsoleColor.Magenta;

            while (true)
            {
            ConsoleKeyInfo cki = Console.ReadKey(true);
                if (cki.Key == ConsoleKey.Enter)
                {
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine();
                    return password;
                }
                else if (cki.Key == ConsoleKey.Backspace)
                {
                    // remove the last asterisk from the screen...
                    if (password.Length > 0)
                    {
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        Console.Write(" ");
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        password.RemoveAt(password.Length - 1);
                    }
                }
                else if (cki.Key == ConsoleKey.Escape)
                {
                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine();
                    return password;
                }
                else if (Char.IsLetterOrDigit(cki.KeyChar) || Char.IsSymbol(cki.KeyChar))
                {
                    if (password.Length < 20)
                    {
                        password.AppendChar(cki.KeyChar);
                        Console.Write("*");
                    }
                    else
                    {
                        Console.Beep();
                    }
                }
                else
                {
                    Console.Beep();
                }
            }
        }
Ejemplo n.º 22
0
 private static void ReadSecureStringFromConsole(SecureString secureString)
 {
     ConsoleKeyInfo keyInfo;
     while ((keyInfo = System.Console.ReadKey(intercept: true)).Key != ConsoleKey.Enter)
     {
         if (keyInfo.Key == ConsoleKey.Backspace)
         {
             if (secureString.Length < 1)
             {
                 continue;
             }
             System.Console.SetCursorPosition(System.Console.CursorLeft - 1, System.Console.CursorTop);
             System.Console.Write(' ');
             System.Console.SetCursorPosition(System.Console.CursorLeft - 1, System.Console.CursorTop);
             secureString.RemoveAt(secureString.Length - 1);
         }
         else
         {
             secureString.AppendChar(keyInfo.KeyChar);
             System.Console.Write('*');
         }
     }
     System.Console.WriteLine();
 }
Ejemplo n.º 23
0
 private static SecureString ReadBlind()
 {
     SecureString line = new SecureString();
     ConsoleKeyInfo c;
     while(true){
         c = Console.ReadKey(true);
         if(c.Key==ConsoleKey.Enter){
             Console.WriteLine();
             break;
         }
         else if(c.Key==ConsoleKey.Backspace){
             if(line.Length>0){
                 line.RemoveAt(line.Length-1);
             }
         }
         else {
             line.AppendChar(c.KeyChar);
         }
     }
     line.MakeReadOnly();
     return line;
 }
Ejemplo n.º 24
0
        /// <summary>
        /// The get password.
        /// </summary>
        /// <returns>
        /// The <see cref="SecureString"/>.
        /// </returns>
        private static SecureString GetPassword()
        {
            var secureString = new SecureString();
            ConsoleKeyInfo key;

            Console.Write("Password: ");
            do
            {
                key = Console.ReadKey(true);

                if (key.Key == ConsoleKey.Backspace && secureString.Length > 0)
                {
                    secureString.RemoveAt(secureString.Length - 1);
                }
                else if (key.Key != ConsoleKey.Enter)
                {
                    secureString.AppendChar(key.KeyChar);
                }
            }
            while (key.Key != ConsoleKey.Enter);

            Console.WriteLine();

            return secureString;
        }
Ejemplo n.º 25
0
 public static SecureString GetPassword()
 {
   var pwd = new SecureString();
   while (true)
   {
     var i = Console.ReadKey(true);
     switch (i.Key)
     {
       case ConsoleKey.Enter:
         goto DONE;
       case ConsoleKey.Backspace:
         if (pwd.Length <= 0) continue;
         pwd.RemoveAt(pwd.Length - 1);
         Console.Write("\b \b");
         break;
       default:
         pwd.AppendChar(i.KeyChar);
         Console.Write("*");
         break;
     }
   }
 DONE:
   pwd.MakeReadOnly(); // prevent further changes to the encrypted pwd
   return pwd;
 }
Ejemplo n.º 26
0
        private static SecureString passwordPrompt( string prompt )
        {
            Console.Write( prompt );
            SecureString securePassword = new SecureString();
            ConsoleKeyInfo nextKey = Console.ReadKey( true );
            while ( nextKey.Key != ConsoleKey.Enter )
                {
                if ( nextKey.Key == ConsoleKey.Backspace )
                    {
                    if ( securePassword.Length > 0 )
                        {
                        securePassword.RemoveAt( securePassword.Length - 1 );
                        Console.Write( nextKey.KeyChar );
                        Console.Write( ' ' );
                        Console.Write( nextKey.KeyChar );
                        }
                    }
                else
                    {
                    securePassword.AppendChar( nextKey.KeyChar );
                    Console.Write( '*' );
                    }
                nextKey = Console.ReadKey( true );
                }
            Console.WriteLine();

            securePassword.MakeReadOnly();
            return securePassword;
        }
Ejemplo n.º 27
0
        // Replaces the characters of the typed in password with asterisks
        // More info: http://rajeshbailwal.blogspot.com/2012/03/password-in-c-console-application.html
        private static SecureString ReadPassword()
        {
            var password = new SecureString();
            try
            {
                ConsoleKeyInfo info = Console.ReadKey(true);
                while (info.Key != ConsoleKey.Enter)
                {
                    if (info.Key != ConsoleKey.Backspace)
                    {
                        Console.Write("*");
                        password.AppendChar(info.KeyChar);
                    }
                    else if (info.Key == ConsoleKey.Backspace)
                    {
                        if (password != null)
                        {
                            // remove one character from the list of password characters
                            password.RemoveAt(password.Length - 1);
                            // get the location of the cursor
                            int pos = Console.CursorLeft;
                            // move the cursor to the left by one character
                            Console.SetCursorPosition(pos - 1, Console.CursorTop);
                            // replace it with space
                            Console.Write(" ");
                            // move the cursor to the left by one character again
                            Console.SetCursorPosition(pos - 1, Console.CursorTop);
                        }
                    }
                    info = Console.ReadKey(true);
                }
                // add a new line because user pressed enter at the end of their password
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error Reading Password {ex.Message}");
                Log.Error("Error Reading Password: {@ex}", ex);
            }

            return password;
        }
Ejemplo n.º 28
0
        /// <summary>
        /// 
        /// Implementation based on NT CredUI's GetPasswdStr.
        /// Use Win32.ReadConsole to construct a SecureString. The advantage of ReadConsole over ReadKey is
        /// Alt-ddd where d is {0-9} is allowed.
        /// It also manages the cursor as keys are entered and "backspaced". However, it is possible that
        /// while this method is running, the console buffer contents could change. Then, its cursor mgmt
        /// will likely be messed up.
        ///
        /// Secondary implementation for Unix based on Console.ReadKey(), where
        /// the advantage is portability through abstraction. Does not support
        /// arrow key movement, but supports backspace.
        /// 
        /// </summary>
        ///<param name="isSecureString">
        /// 
        /// True to specify reading a SecureString; false reading a string
        /// 
        /// </param>
        /// <param name="printToken">
        /// 
        /// string for output echo
        /// 
        /// </param>
        /// <returns></returns>
        /// <exception cref="HostException">
        /// 
        /// If obtaining a handle to the active screen buffer failed
        ///    OR
        ///    Win32's setting input buffer mode to disregard window and mouse input failed
        ///    OR
        ///    Win32's ReadConsole failed
        ///    OR
        ///    obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleCursorPosition failed
        ///
        /// </exception>
        /// <exception cref="PipelineStoppedException">
        ///
        /// If Ctrl-C is entered by user
        /// 
        /// </exception>

        private object ReadLineSafe(bool isSecureString, char? printToken)
        {
            // Don't lock (instanceLock) in here -- the caller needs to do that...

            PreRead();
            string printTokenString = printToken.HasValue ?
                printToken.ToString() :
                null;
            SecureString secureResult = new SecureString();
            StringBuilder result = new StringBuilder();
#if UNIX
            bool treatControlCAsInput = Console.TreatControlCAsInput;
#else
            ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle();
            ConsoleControl.ConsoleModes originalMode = ConsoleControl.GetMode(handle);
            bool isModeChanged = true; // assume ConsoleMode is changed so that if ReadLineSetMode
            // fails to return the value correctly, the original mode is
            // restored.
#endif

            try
            {
#if UNIX
                Console.TreatControlCAsInput = true;
#else
                // Ensure that we're in the proper line-input mode.

                ConsoleControl.ConsoleModes desiredMode =
                    ConsoleControl.ConsoleModes.Extended |
                    ConsoleControl.ConsoleModes.QuickEdit;

                ConsoleControl.ConsoleModes m = originalMode;
                bool shouldUnsetEchoInput = shouldUnsetMode(ConsoleControl.ConsoleModes.EchoInput, ref m);
                bool shouldUnsetLineInput = shouldUnsetMode(ConsoleControl.ConsoleModes.LineInput, ref m);
                bool shouldUnsetMouseInput = shouldUnsetMode(ConsoleControl.ConsoleModes.MouseInput, ref m);
                bool shouldUnsetProcessInput = shouldUnsetMode(ConsoleControl.ConsoleModes.ProcessedInput, ref m);

                if ((m & desiredMode) != desiredMode ||
                    shouldUnsetMouseInput ||
                    shouldUnsetEchoInput ||
                    shouldUnsetLineInput ||
                    shouldUnsetProcessInput)
                {
                    m |= desiredMode;
                    ConsoleControl.SetMode(handle, m);
                }
                else
                {
                    isModeChanged = false;
                }
                _rawui.ClearKeyCache();
#endif

                Coordinates originalCursorPos = _rawui.CursorPosition;

                do
                {
                    //
                    // read one char at a time so that we don't
                    // end up having a immutable string holding the
                    // secret in memory.
                    //
#if UNIX
                    ConsoleKeyInfo keyInfo = Console.ReadKey(true);
#else
                    uint unused = 0;
                    string key = ConsoleControl.ReadConsole(handle, string.Empty, 1, false, out unused);
#endif

#if UNIX
                    // Handle Ctrl-C ending input
                    if (keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
#else
                    if (string.IsNullOrEmpty(key) || (char)3 == key[0])
#endif
                    {
                        PipelineStoppedException e = new PipelineStoppedException();
                        throw e;
                    }
#if UNIX
                    if (keyInfo.Key == ConsoleKey.Enter)
#else
                    if ((char)13 == key[0])
#endif
                    {
                        //
                        // we are done if user presses ENTER key
                        //
                        break;
                    }
#if UNIX
                    if (keyInfo.Key == ConsoleKey.Backspace)
#else
                    if ((char)8 == key[0])
#endif
                    {
                        //
                        // for backspace, remove last char appended
                        //
                        if (isSecureString && secureResult.Length > 0)
                        {
                            secureResult.RemoveAt(secureResult.Length - 1);
                            WriteBackSpace(originalCursorPos);
                        }
                        else if (result.Length > 0)
                        {
                            result.Remove(result.Length - 1, 1);
                            WriteBackSpace(originalCursorPos);
                        }
                    }
#if UNIX
                    else if (Char.IsControl(keyInfo.KeyChar))
                    {
                        // blacklist control characters
                        continue;
                    }
#endif
                    else
                    {
                        //
                        // append the char to our string
                        //
                        if (isSecureString)
                        {
#if UNIX
                            secureResult.AppendChar(keyInfo.KeyChar);
#else
                            secureResult.AppendChar(key[0]);
#endif
                        }
                        else
                        {
#if UNIX
                            result.Append(keyInfo.KeyChar);
#else
                            result.Append(key);
#endif
                        }
                        if (!string.IsNullOrEmpty(printTokenString))
                        {
                            WritePrintToken(printTokenString, ref originalCursorPos);
                        }
                    }
                }
                while (true);
            }
#if UNIX
            catch (InvalidOperationException)
            {
                // ReadKey() failed so we stop
                throw new PipelineStoppedException();
            }
#endif
            finally
            {
#if UNIX
                Console.TreatControlCAsInput = treatControlCAsInput;
#else
                if (isModeChanged)
                {
                    ConsoleControl.SetMode(handle, originalMode);
                }
#endif
            }
            WriteLineToConsole();
            PostRead(result.ToString());
            if (isSecureString)
            {
                return secureResult;
            }
            else
            {
                return result;
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Read a password from the console into a SecureString
        /// </summary>
        /// <returns>Password stored in a secure string</returns>
        public static SecureString GetPassword()
        {
            SecureString password = new SecureString();
            Console.WriteLine("Enter password: "******" ");
                        Console.Write(nextKey.KeyChar);
                    }
                }
                else
                {
                    password.AppendChar(nextKey.KeyChar);
                    Console.Write("*");
                }

                nextKey = Console.ReadKey(true);
            }

            Console.WriteLine();

            // lock the password down
            password.MakeReadOnly();
            return password;
        }
Ejemplo n.º 30
0
        public override SecureString ReadLineAsSecureString()
        {
            var secureString = new SecureString();
            try
            {
                lock (_instanceLock)
                {
                    KeyInfo keyInfo;
                    while ((keyInfo = RawUI.ReadKey()).VirtualKeyCode != VkCodeReturn)
                    {
                        // {enter}
                        if (keyInfo.VirtualKeyCode == VkCodeBackspace)
                        {
                            if (secureString.Length > 0)
                            {
                                secureString.RemoveAt(secureString.Length - 1);
                                Console.WriteBackspace();
                            }
                        }
                        else
                        {
                            // culture is deferred until securestring is decrypted
                            secureString.AppendChar(keyInfo.Character);
                            Write("*");
                        }
                    }
                    secureString.MakeReadOnly();
                }
                return secureString;
            }
            catch (PipelineStoppedException)
            {
                // ESC was hit, clean up secure string
                secureString.Dispose();

                return null;
            }
            finally
            {
                WriteLine(String.Empty);
            }
        }