Building a String Encryption/Decryption Class in C#

HomeC#

Building a String Encryption/Decryption Class in C#

Create a case insensitive “Contains(string)”
How to escape braces in a format string in C#
Difference between String (Uppercase s) and string (lowercase s)

How to create a C# class for encrypting and decrypting strings provided by the user. We’ll use a simple symmetric encryption method (XOR) for demonstration purposes. Important Note: XOR encryption is easily broken and is not suitable for production systems. Real-world applications should use robust encryption algorithms like AES. This example serves as an educational starting point.

using System;
using System.Text;

public class StringCipher
{
    private string _key;

    public StringCipher(string key)
    {
        _key = key;
    }

    public string Encrypt(string text)
    {
        return xorCipher(text);
    }

    public string Decrypt(string text)
    {
        return xorCipher(text);
    }

    private string xorCipher(string text)
    {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < text.Length; i++)
        {
            result.Append((char)(text[i] ^ _key[i % _key.Length]));
        }
        return result.ToString();
    }
}

Explanation:

  1. StringCipher Class: This class encapsulates the encryption and decryption logic.
  2. _key Field: Stores the encryption key. Critical: The security of this method relies entirely on the secrecy of the key.
  3. Constructor: Takes the encryption key as an argument and initializes the _key field.
  4. Encrypt Method: Takes the plaintext string as input and calls the xorCipher method to perform the encryption.
  5. Decrypt Method: Takes the ciphertext string as input and calls the xorCipher method. Because XOR is symmetric, the same method is used for both encryption and decryption.
  6. xorCipher Method: This is where the actual encryption/decryption happens. It iterates through each character of the input string and performs an XOR operation with the corresponding character of the key (wrapping around if the key is shorter than the text). The result is appended to a StringBuilder for efficiency.
public static void Main(string[] args)
{
    string key = "mysecretkey"; // In a real application, this should be handled securely!
    StringCipher cipher = new StringCipher(key);

    string plaintext = "This is a secret message.";
    string ciphertext = cipher.Encrypt(plaintext);

    Console.WriteLine("Plaintext: " + plaintext);
    Console.WriteLine("Ciphertext: " + ciphertext);

    string decryptedText = cipher.Decrypt(ciphertext);
    Console.WriteLine("Decrypted Text: " + decryptedText);

    Console.ReadKey();
}

Output:

COMMENTS

DISQUS: 0