Simple Symmetric Encryption in .NET

It is often very useful to have round-trip encryption-decryption capabilities to support secure data exchange. Here is how to implement symmetric encryption with a few lines of code.

The symmetric encryption algorithm demonstrated here is a simple wrapper on the TripleDESCryptoServiceProvider available as part of the .NET libraries. The ‘encrypt’ and ‘decrypt’ functions are using the common ‘transform’ method to perform their operation. It is critical that the ‘vector’ is matching for the encrtyption and decryption steps to work correctly; here it is defined as a static byte[] for simplicity. Notice that the transform function is simply appplying the CryptoStream it receives on a CryptoStream in the most basic manner.

C# symmetric encryption extension library shared across front-end and middle-tier.

public static string Encrypt(this string text, string key)
{
return Transform(text, _cryptoService.CreateEncryptor(key.GetBytes(), vector));
}

public static string Decrypt(this string text, string key)
{
return Transform(text, _cryptoService.CreateDecryptor(key.GetBytes(), vector));
}

private static SymmetricAlgorithm _cryptoService = new TripleDESCryptoServiceProvider();
// static vector to ensure match between Encrypt and Decrypt
private static byte[] vector = ("MyPrivateKey12345").ToString().GetBytes();
// Symmetric transform used for both Encrypt and Decrypt
private static string Transform(string text, ICryptoTransform cryptoTransform)
{
using (MemoryStream stream = new MemoryStream())
{
using (CryptoStream cryptoStream =
new CryptoStream(stream, cryptoTransform, CryptoStreamMode.Write))
{
cryptoStream.Write(Encoding.Default.GetBytes(text), 0, text.Length);
cryptoStream.FlushFinalBlock();
}
return Encoding.Default.GetString(stream.ToArray());
}
}

Leave a comment

Who's the Coach?

Ben Ruiz Oatts is the insightful mastermind behind this coaching platform. Focused on personal and professional development, Ben offers fantastic coaching programs that bring experience and expertise to life.

Get weekly insights

We know that life's challenges are unique and complex for everyone. Coaching is here to help you find yourself and realize your full potential.

We know that life's challenges are unique and complex for everyone. Coaching is here to help you find yourself and realize your full potential.