How to Encrypt and Decrypt plain string using ROT13 in C#

By FoxLearn 7/20/2024 2:29:21 AM   8.11K
Encrypting and decrypting using ROT13 in C# is straightforward due to its simplicity. ROT13 is a simple substitution cipher that replaces each letter with the letter 13 positions after it in the alphabet.

How to implement ROT13 encryption and decryption in a C#

Create a new Windows Forms Application project, then can drag and drop the TextBox, Label and Button controls 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.

// Method to perform ROT13 encryption
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

// // Method to perform ROT13 decryption (same as encryption)
private void btnDecrypt_Click(object sender, EventArgs e)
{
    txtDecrypt.Text = ROT13(txtEncrypt.Text);
}

Build and run your application. then enter text into the txtInput box, click Encrypt to see the ROT13-encrypted text in txtEncrypt, and click Decrypt to see the decrypted text.

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