Encryption and Decryption Using Symmetric Key In C#
Want to learn more about encryption and decryption using symmetric keys?
Join the DZone community and get the full member experience.
Join For FreeA symmetric key is a string used to encrypt data, and with the same string, we can decrypt the data, which means a single string is required for both encryption and decryption.
We are going to look at the sample code in the console application, so let’s get started.
Open the Visual Studio and click on File —> New —> Project, as shown in the image below.
Choose Console App (.NET Core) Visual C# and enter the project name, like so: “EncryptionDecryptionUsingSymmetricKey.”
Now, we will get a Program
class, as shown in the below image.
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 the 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. 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.
Conclusion
In this article, we learned how to use a symmetric key for encryption and decryption in C#. As per our requirements, we can also use different types of methods present inside the Aes
class.
You can check out the source code of the sample application from GitHub.
If you have any suggestions or questions, please mention them in the comments section below.
Published at DZone with permission of Vivek Kumar, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments