DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report

Encryption and Decryption Using Symmetric Key In C#

Want to learn more about encryption and decryption using symmetric keys?

Vivek Kumar user avatar by
Vivek Kumar
·
May. 14, 19 · Tutorial
Like (2)
Save
Tweet
Share
31.87K Views

Join the DZone community and get the full member experience.

Join For Free

A 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.

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.

C#

Choose Console App (.NET Core) Visual C# and enter the project name, like so: “EncryptionDecryptionUsingSymmetricKey.”

encryption and decryption using symmetric key in c#

Now, we will get a Program class, as shown in 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 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.

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 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.

csharp

Published at DZone with permission of Vivek Kumar, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Journey to Event Driven, Part 1: Why Event-First Programming Changes Everything
  • Create a CLI Chatbot With the ChatGPT API and Node.js
  • Create Spider Chart With ReactJS
  • Microservices Testing

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: