Skip to main content

Encryption And Decryption Using Symmetric Key In C#

Symmetric key is a string which is used to encrypt the data and with the same string, we can decrypt the data, which means a single string is required for encryption and decryption.

Encryption And Decryption

We are going to see the sample code in the console application, so let’s start.

Open the Visual Studio and click on File -> New -> Project, as shown in below image.

C#

 

Choose Console App (.NET Core) Visual C# and enter the project name, such as – “EncryptionDecryptionUsingSymmetricKey”.

encryption and decryption using symmetric key in c#

 

Now, we will get a Program class as per the below image.

encryption and decryption in c#

 

Right-click on Project and click Class -> Add.

Give the class name “AesOperation” as in the below image.

 

Now, write the following code into this file.

using System;  
using System.IO;  
using System.Security.Cryptography;  
using System.Text;  
  
namespace EncryptionDecryptionUsingSymmetricKey  
{  
    public class AesOperation  
    {  
        public static string EncryptString(string key, string plainText)  
        {  
            byte[] iv = new byte[16];  
            byte[] array;  
  
            using (Aes aes = Aes.Create())  
            {  
                aes.Key = Encoding.UTF8.GetBytes(key);  
                aes.IV = iv;  
  
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);  
  
                using (MemoryStream memoryStream = new MemoryStream())  
                {  
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))  
                    {  
                        using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))  
                        {  
                            streamWriter.Write(plainText);  
                        }  
  
                        array = memoryStream.ToArray();  
                    }  
                }  
            }  
  
            return Convert.ToBase64String(array);  
        }  
  
        public static string DecryptString(string key, string cipherText)  
        {  
            byte[] iv = new byte[16];  
            byte[] buffer = Convert.FromBase64String(cipherText);  
  
            using (Aes aes = Aes.Create())  
            {  
                aes.Key = Encoding.UTF8.GetBytes(key);  
                aes.IV = iv;  
                ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);  
  
                using (MemoryStream memoryStream = new MemoryStream(buffer))  
                {  
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, decryptor, CryptoStreamMode.Read))  
                    {  
                        using (StreamReader streamReader = new StreamReader((Stream)cryptoStream))  
                        {  
                            return streamReader.ReadToEnd();  
                        }  
                    }  
                }  
            }  
        }  
    }  
}

In the above code, we used a predefined Aes class which is in System.Security.Cryptography namespace that uses the same key for encryption and decryption. AES algorithm supports 128, 198, and 256 bit encryption.

We can also see in the above code that we used initialization vector (IV) which is of 16 bytes in size, the block size of the algorithm. IV is optional.

Now, we are going to write the following code in the Main method that is inside the Program.cs file.

using System;  
  
namespace EncryptionDecryptionUsingSymmetricKey  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            var key = "b14ca5898a4e4133bbce2ea2315a1916";  
  
            //Console.WriteLine("Please enter a secret key for the symmetric algorithm.");  
            //var key = Console.ReadLine();  
  
            Console.WriteLine("Please enter a string for encryption");  
            var str = Console.ReadLine();  
            var encryptedString = AesOperation.EncryptString(key, str);  
            Console.WriteLine($"encrypted string = {encryptedString}");  
  
            var decryptedString = AesOperation.DecryptString(key, encryptedString);  
            Console.WriteLine($"decrypted string = {decryptedString}");  
  
            Console.ReadKey();  
        }  
    }  
}

In the given code, we are using a hardcoded value as a key but in real time, we can get a key at runtime and also, we can use the optional initialization vector (IV) as per the complexity we need.

Now, it is time to run the above code and see the output.

symmetric key output in C#

 

Conclusion

In this article, we learned how to use a symmetric key for encryption and decryption in C#. As per our requirement, we can also use different types of methods present inside the Aes Class.

Get the source code of the sample application from GitHub.

If you have any suggestions or questions, please mention them in the comments section.

 

Leave a Reply