Work with Security-Sensitive Strings in Memory - CSharp Security

CSharp examples for Security:Cryptography

Description

Work with Security-Sensitive Strings in Memory

Demo Code


using System;/*from w ww. ja v  a2  s.c om*/
using System.Security;
using System.Diagnostics;

class MainClass
    {
        public static SecureString ReadString()
        {
            SecureString str = new SecureString();

            ConsoleKeyInfo nextChar = Console.ReadKey(true);

            while (nextChar.Key != ConsoleKey.Enter)
            {
                if (nextChar.Key == ConsoleKey.Backspace)
                {
                    if (str.Length > 0)
                    {
                        // Backspace pressed, remove the last character.
                        str.RemoveAt(str.Length - 1);

                        Console.Write(nextChar.KeyChar);
                        Console.Write(" ");
                        Console.Write(nextChar.KeyChar);
                    }
                    else
                    {
                        Console.WriteLine("else");
                    }
                }
                else
                {
                    str.AppendChar(nextChar.KeyChar);
                    Console.Write("*");
                }

                nextChar = Console.ReadKey(true);
            }

            // String entry finished. Make it read-only.
            str.MakeReadOnly();
            return str;
        }

        public static void Main()
        {
            string user = "";

            Console.Write("Enter the user name: ");
            user = Console.ReadLine();

            Console.Write("Enter the user's password: ");
            using (SecureString pword = ReadString())
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();

                startInfo.FileName = "notepad.exe";
                startInfo.UserName = user;
                startInfo.Password = pword;
                startInfo.UseShellExecute = false;

                using (Process process = new Process())
                {
                    // Assign the ProcessStartInfo to the Process object.
                    process.StartInfo = startInfo;

                    try
                    {
                        // Start the new process.
                        process.Start();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("\n\nCould not start Notepad process.");
                        Console.WriteLine(ex);
                    }
                }
            }
        }
    }

Result


Related Tutorials