How to encrypt a password in C#

By FoxLearn 7/16/2024 8:56:37 AM   14.01K
Encrypt a password with MD5 in C# by entering text into a TextBox, then encrypting and displaying the result in a TextBox control.

You can use the MD5 class from the System.Security.Cryptography namespace to encrypt a password using the MD5 hashing algorithm in C# Windows Forms Application.

What is the MD5 Algorithm?

The MD5 (Message Digest Algorithm 5) is a popular cryptographic hash function designed by Ronald Rivest in 1991. It generates a 128-bit hash value from an input message of any length, creating a fixed-size output typically represented as a 32-character hexadecimal number. Originally used for cryptographic tasks like password storage and data integrity verification, MD5 has since been found vulnerable to attacks, making it unsuitable for secure purposes.

How to encrypt a password using MD5 encryption in C#

Here's a basic example of how you can do this:

Open your Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "EncryptPassword" and then click OK

Drag and drop TextBox, Label, Button from the Visual Studio toolbox onto your form designer, then you can layout your form as shown below

encrypt password in c#

Creating a Encrypt method allows you to encrypt string to md5 hash.

static string Encrypt(string value)
{
    //Using MD5 to encrypt a string
    using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
    {
        UTF8Encoding utf8 = new UTF8Encoding();
        //Hash data
        byte[] data = md5.ComputeHash(utf8.GetBytes(value));
        return Convert.ToBase64String(data);
    }
}

Here's how you can use this Encrypt method in your Windows Forms application

Add a click event handler to the Encrypt button allows you to encrypt text from the TextBox to md5 hash, then display result to the TextBox control.

private void btnEncrypt_Click(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(txtPassword.Text))
    {
        MessageBox.Show("Please enter your password.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }
    txtResult.Text = Encrypt(txtPassword.Text);
}

VIDEO TUTORIAL

Related