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:
StringCipher
Class: This class encapsulates the encryption and decryption logic._key
Field: Stores the encryption key. Critical: The security of this method relies entirely on the secrecy of the key.- Constructor: Takes the encryption key as an argument and initializes the
_key
field. Encrypt
Method: Takes the plaintext string as input and calls thexorCipher
method to perform the encryption.Decrypt
Method: Takes the ciphertext string as input and calls thexorCipher
method. Because XOR is symmetric, the same method is used for both encryption and decryption.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 aStringBuilder
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