Keeping your users' data in a secure environment is very important step while building an application, especially when you are dealing with sensitive information, such as - Emails, Passwords, and E-Payment information (Bank Accounts, Payment cards, .etc.), and also when your application sends and receives the data over a network.In these situations, you have to be sure that no one can tamper with the data or steal it; and make your users feel comfortable while they are using your application because they know that their data is secure.
In this article, I’ll try to explain the differences between symmetric and asymmetric algorithms and how you can implement these algorithms in your app using C# programming language.
So, what are symmetric and asymmetric algorithms?
Before I start with symmetric and asymmetric algorithms, I’ll explain Cryptography in general.
Cryptography is about encrypting and decrypting data. With encryption, you convert a plain text (that’s human readable) into a random array of bytes. Decryption is the opposite process, you convert the random array of bytes into a plain text.
Encrypting any piece of plain text needs a key to do the operation and also, the decrypting process needs a key to convert encrypted data into a plain text. A key is the controller of the encryption process that is used by an algorithm. Actually, here is the main difference between symmetric and asymmetric strategies. A symmetric algorithm uses one key to encrypt and decrypt your data, however, the asymmetric algorithms use two different keys which are mathematically related to each other. One of these keys is public and can be used by everyone. The other key is private and it should be used only by you and never shared with anyone.
Another difference between symmetric and asymmetric algorithms is the performance and size. Symmetric encryption is faster and used to encrypt a large data sets. Asymmetric is well suited for encrypting a small messages. But using these two strategies lead you to implement a robust security system in your application.
Implementing symmetric cryptography in your C# application
One of the most popular symmetric algorithms is AES (Advanced Encryption Security). You can find all the cryptography classes in System.Security.Cryptography namespace. In this tutorial, I will use AES algorithm to encrypt a piece of plain text and save it into a file and also read this file and decrypt its content to a plain text.
Note
In this tutorial, I will use Console Application to concentrate only on the encryption code without event handlers and something like this.
Let’s start,
Open Visual Studio (I use Visual Studio 2017) and click on "New project".
Choose console application and name the project as you want.
Inside the program.cs file, write the following code. The code is self-explanatory.
- using System;
- using System.Security.Cryptography;
- using System.IO;
-
- namespace SymmetricTutorial
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- SymmetricAlgorithm aes = new AesManaged();
-
- byte[] key = aes.Key;
-
- Console.WriteLine("Enter your message here to encrypt:");
- string message = Console.ReadLine();
-
-
- EncryptText(aes, message, "encryptedData.dat");
-
-
- Console.WriteLine("Decrypted message: {0}", DecryptData(aes, "encryptedData.dat"));
-
-
-
- }
-
-
- static void EncryptText(SymmetricAlgorithm aesAlgorithm,string text,string fileName)
- {
-
- ICryptoTransform encryptor = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV);
-
-
- using (MemoryStream ms = new MemoryStream())
- {
- using (CryptoStream cs = new CryptoStream(ms,encryptor,CryptoStreamMode.Write))
- {
- using (StreamWriter writer = new StreamWriter(cs))
- {
-
- writer.Write(text);
- }
- }
-
-
- byte[] encryptedDataBuffer = ms.ToArray();
-
-
- File.WriteAllBytes(fileName, encryptedDataBuffer);
- }
- }
-
-
- static string DecryptData(SymmetricAlgorithm aesAlgorithm, string fileName)
- {
-
- ICryptoTransform decryptor = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV);
-
-
- byte[] encryptedDataBuffer = File.ReadAllBytes(fileName);
-
-
- using (MemoryStream ms = new MemoryStream(encryptedDataBuffer))
- {
- using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
- {
- using (StreamReader reader = new StreamReader(cs))
- {
-
- return reader.ReadToEnd();
- }
- }
- }
- }
- }
- }
Note: In this example I encrypted a text and saved it to a file. Then, I read this file, decrypted its content, and showed the result on the console window.
Implementing Asymmetric cryptography in your C# application
The common asymmetric algorithm is called RSA. So in this example, I'll use it to do the same action that I did in the previous one. Again, create a Console Application project (1 and 2 steps in the previous example).
Inside the program.cs file, write the following code,
- using System;
- using System.IO;
- using System.Security.Cryptography;
- using System.Text;
-
- namespace AsymmetricTutorial
- {
- class Program
- {
-
- static void Main(string[] args)
- {
-
- RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
-
- string publicKey = rsa.ToXmlString(false);
- string privateKey = rsa.ToXmlString(true);
-
-
- EncryptText(publicKey, "Hello from C# Corner", "encryptedData.dat");
-
-
- Console.WriteLine("Decrypted message: {0}", DecryptData(privateKey, "encryptedData.dat"));
-
- }
-
-
- static void EncryptText(string publicKey ,string text,string fileName)
- {
-
- UnicodeEncoding byteConverter = new UnicodeEncoding();
- byte[] dataToEncrypt = byteConverter.GetBytes(text);
-
-
- byte[] encryptedData;
- using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
- {
-
- rsa.FromXmlString(publicKey);
-
-
- encryptedData = rsa.Encrypt(dataToEncrypt, false);
- }
-
- File.WriteAllBytes(fileName, encryptedData);
-
- Console.WriteLine("Data has been encrypted");
- }
-
-
- static string DecryptData(string privateKey,string fileName)
- {
-
- byte[] dataToDecrypt = File.ReadAllBytes(fileName);
-
-
- byte[] decryptedData;
- using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
- {
-
- rsa.FromXmlString(privateKey);
- decryptedData = rsa.Decrypt(dataToDecrypt, false);
- }
-
-
- UnicodeEncoding byteConverter = new UnicodeEncoding();
- return byteConverter.GetString(decryptedData);
- }
- }
- }
In this example, I used two keys - one to encrypt the data and one to decrypt.
Conclusion
Using Symmetric and Asymmetric algorithms and implementing them correctly in your application increases the security system in the app as well as enhances the usability of your app because it becomes safer for users to share their personal data. This is not the only use of cryptography algorithms; actually, they are used in different situations also, such as - Digital signature, Digital certificates, etc.