Windows Forms: Encryption and Decryption using ROT13 in C#

This tutorial shows you how to encrypt and decrypt using ROT13 algorithm in C#.NET Windows Forms Application.

To play the demo, you can drag the textbox, label and button from the visual studio toolbox into your winform, then you can design a simple UI that allows you to encrypt and decrypt a string using the ROT13 algorithm as shown below.

c# rot3 encrypt

ROT13 (rotate by 13 places) is an encryption rotates 13 positions. It's a simple way to encrypt plain text by replacing unit data (characters, character groups) in text with other character units. The coding units used are called the ciphertext and the modal group mentioned is called the alternate ciphertext.

ROT13 encrypt method is implemented based on the order of the english table. A character will be encoded using the following character 13 positions to replace it. When decoding, we just need to do the same as the encoding process, ie keep on jumping 13 next positions, if at the end of the table, count from the top of the table. So ROT13 (ROT13 (x)) = x with x is any character in the table. Encryption and decryption can also be done using a lookup table that is made based on the above rule as follows:

rot13 algorithm c#

After that, we can easily see that A will be encoded into N and B will become O. With the HELLO text string, we will get the result after coding as URYYB, which cannot be understood by human.

rot13 algorithm

You need to create the ROT13 method to encrypt your text using ROT13 algorithm.

public string ROT13(string input)
{
    StringBuilder result = new StringBuilder();
    Regex regex = new Regex("[A-Za-z]");
    foreach (char c in input)
    {
        if (regex.IsMatch(c.ToString()))
        {
            int code = ((c & 223) - 52) % 26 + (c & 32) + 65;
            result.Append((char)code);
        }
        else
            result.Append(c);
    }
    return result.ToString();
}

Add code to the Encrypt button click event as the following c# code.

private void btnEncrypt_Click(object sender, EventArgs e)
{
    txtEncrypt.Text = ROT13(txtInput.Text);
}

Finally, Add code to handle the Decrypt button click event

private void btnDecrypt_Click(object sender, EventArgs e)
{
    txtDecrypt.Text = ROT13(txtEncrypt.Text);
}

You can also you the ROT13 algorithm to encrypt and decrypt password using c# code.