Make the user enter a password to use a program in C#

[password]

The example Display a simple password dialog before a program starts in C# displays a simple password form. It compares the value entered by the user with a string inside the program to decide whether the user entered the right password.

Unfortunately, this strategy requires the program to hold the password inside its code. Even a mediocre hacker could easily read the code to find the password.

This program uses a different approach. Instead of storing the password inside the code, the program stores a token and its encryption using the password. When the user enters the password, the program uses it to encrypt the token and compares the result with the saved encryption. If the two match, then the program knows that the user entered the correct password.

With this approach, the program doesn’t include the password, so a hacker cannot find it by examining the code.

The following code shows how the program validates the user’s password.

// Get the password from the user.
private void Form1_Load(object sender, EventArgs e)
{
    const string token = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    const string encrypted = "0dbc23df7b4358281cbc83...";

    // Get the password from the user.
    PasswordForm frm = new PasswordForm();
    if (frm.ShowDialog() == DialogResult.Cancel) Close();

    // See if the password is correct.
    string password = frm.txtPassword.Text;
    if (token.Encrypt(password).ToHex() != encrypted) Close();
}

This code defines the token and the encrypted token. It then displays a password form so the user can enter the password. (The example uses the password SecretPassword.)

The program then uses the extension methods described in the example Use the .NET cryptography library to make extension methods that encrypt and decrypt strings in C# to encrypt the token string using the user’s password. If the result doesn’t match the encrypted value stored in the program, the code closes the main form.

The last question is, “How do you calculate the encrypted value to store inside the code?” One method is to use the example program from the post Use the .NET cryptography library to make extension methods that encrypt and decrypt strings in C#. That example includes spaces inside the encrypted string. Simply remove those spaces to make a result that this program can use.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in cryptography, dialogs, programs and tagged , , , , , , , , , , . Bookmark the permalink.

One Response to Make the user enter a password to use a program in C#

  1. Pingback: Why Twitter recently wanted you to change your password - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.