Search code examples
c#securityglobal-variablesprocess.startsecurestring

C# - Process.Start - using global variable as password - "cannot convert from 'string' to 'System.Security.SecureString'


I designed a login form and wanted the username and password entered to be stored as variables I could call in other forms (overall program is a collection of .exe files and powershell scripts that I want to run as the username and password initially entered in my login form).

At the start of the program I created "global variables" using this code:

class usernameGlobalVariable
    {
        public static string var = "";
    }
    class passwordGlobalVariable
    {
        public static string var = "";
    }

In the login form I stored the username and password entered into these global variables this way:

private void usernameTextBox_TextChanged(object sender, EventArgs e)
    {
        usernameGlobalVariable.var = usernameTextBox.Text;
    }


    private void passwordTextBox_TextChanged(object sender, EventArgs e)
    {
        passwordGlobalVariable.var = passwordTextBox.Text;
    }

When I want to start a process I call it using this code (to run it as the username and password stored by the login form):

string fileName = "c:\\hdatools\\Ping2.exe";
string arguments = "";
string domain = "vantage";
private void Button2_Click(object sender, EventArgs e)
    {

    Process.Start(
    fileName,
    arguments,
    usernameGlobalVariable.var,
    passwordGlobalVariable.var,
    domain);

    }

The main error I get is on the line passwordGlobalVariable.var, The error says

Argument 4: cannot convert from 'string' to 'System.Security.SecureString'

I've tried different ways to try to convert `passwordGlobalVariable.var' to a secure string, or to give another string variable its contents and then render that variable as a secure string. I've finally run out of ideas. Thanks in advance for the help.


Solution

  • Argument 4: cannot convert from 'string' to 'System.Security.SecureString'

    because var is a string and not a SecureString, look:

    class passwordGlobalVariable
    {
       public static string var = "";
    }
    

    So change it to:

    class passwordGlobalVariable
    {
       public static SecureString var;
    }
    

    And later on, change your passwordTextBox_TextChanged event-handler to convert your password string into a SecureString:

    private void passwordTextBox_TextChanged(object sender, EventArgs e)
    {
       SecureString passWord = new SecureString();
       foreach (char c in passwordTextBox.Text.ToCharArray())
       {
         passWord.AppendChar(c);
       }
    
        passwordGlobalVariable.var = passWord;
    }
    

    A small side-note: Refrain from using the var word because one can be confused with the C#'s var contextual keyword.