Implement Symmetric And Asymmetric Cryptography Algorithms With C#

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. 
  1. using System;  
  2. using System.Security.Cryptography;  
  3. using System.IO;  
  4.   
  5. namespace SymmetricTutorial  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             // Create a new instance of the AES algorithm   
  12.             SymmetricAlgorithm aes = new AesManaged();  
  13.   
  14.             byte[] key = aes.Key; // Key propery contains the key of the aes algorithm you can create your own   
  15.   
  16.             Console.WriteLine("Enter your message here to encrypt:");  
  17.             string message = Console.ReadLine();   
  18.   
  19.             // Call the encryptText method to encrypt the a string and save the result to a file   
  20.             EncryptText(aes, message, "encryptedData.dat");  
  21.   
  22.             // Call the decryptData method to get the encrypted text from the file and print it   
  23.             Console.WriteLine("Decrypted message: {0}", DecryptData(aes, "encryptedData.dat"));   
  24.   
  25.   
  26.               
  27.         }  
  28.   
  29.         // Method to encrypte a string data and save it in a specific file using an AES algorithm  
  30.         static void EncryptText(SymmetricAlgorithm aesAlgorithm,string text,string fileName)  
  31.         {  
  32.             // Create an encryptor from the AES algorithm instance and pass the aes algorithm key and inialiaztion vector to generate a new random sequence each time for the same text  
  33.             ICryptoTransform encryptor = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV);  
  34.   
  35.             // Create a memory stream to save the encrypted data in it  
  36.             using (MemoryStream ms = new MemoryStream())  
  37.             {  
  38.                 using (CryptoStream cs = new CryptoStream(ms,encryptor,CryptoStreamMode.Write))  
  39.                 {  
  40.                     using (StreamWriter writer = new StreamWriter(cs))  
  41.                     {  
  42.                         // Write the text in the stream writer   
  43.                         writer.Write(text);  
  44.                     }  
  45.                 }  
  46.   
  47.                 // Get the result as a byte array from the memory stream   
  48.                 byte[] encryptedDataBuffer = ms.ToArray();  
  49.   
  50.                 // Write the data to a file   
  51.                 File.WriteAllBytes(fileName, encryptedDataBuffer);  
  52.             }  
  53.         }  
  54.   
  55.         // Method to decrypt a data from a specific file and return the result as a string   
  56.         static string DecryptData(SymmetricAlgorithm aesAlgorithm, string fileName)  
  57.         {  
  58.             // Create a decryptor from the aes algorithm   
  59.             ICryptoTransform decryptor = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV);  
  60.   
  61.             // Read the encrypted bytes from the file   
  62.             byte[] encryptedDataBuffer = File.ReadAllBytes(fileName);   
  63.   
  64.             // Create a memorystream to write the decrypted data in it   
  65.             using (MemoryStream ms = new MemoryStream(encryptedDataBuffer))  
  66.             {  
  67.                 using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))  
  68.                 {  
  69.                     using (StreamReader reader = new StreamReader(cs))  
  70.                     {  
  71.                         // Reutrn all the data from the streamreader   
  72.                         return reader.ReadToEnd();   
  73.                     }  
  74.                 }  
  75.             }  
  76.         }  
  77.     }  
  78. }  
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,
  1. using System;  
  2. using System.IO;  
  3. using System.Security.Cryptography;  
  4. using System.Text;   
  5.   
  6. namespace AsymmetricTutorial  
  7. {  
  8.     class Program  
  9.     {  
  10.   
  11.         static void Main(string[] args)  
  12.         {  
  13.             // Create an instance of the RSA algorithm class  
  14.             RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();  
  15.             // Get the public keyy   
  16.             string publicKey = rsa.ToXmlString(false); // false to get the public key   
  17.             string privateKey = rsa.ToXmlString(true); // true to get the private key   
  18.   
  19.             // Call the encryptText method   
  20.             EncryptText(publicKey, "Hello from C# Corner""encryptedData.dat");  
  21.   
  22.             // Call the decryptData method and print the result on the screen   
  23.             Console.WriteLine("Decrypted message: {0}", DecryptData(privateKey, "encryptedData.dat"));   
  24.   
  25.         }  
  26.   
  27.         // Create a method to encrypt a text and save it to a specific file using a RSA algorithm public key   
  28.         static void EncryptText(string publicKey ,string text,string fileName)  
  29.         {  
  30.             // Convert the text to an array of bytes   
  31.             UnicodeEncoding byteConverter = new UnicodeEncoding();  
  32.             byte[] dataToEncrypt = byteConverter.GetBytes(text);  
  33.   
  34.             // Create a byte array to store the encrypted data in it   
  35.             byte[] encryptedData;   
  36.             using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())  
  37.             {  
  38.                 // Set the rsa pulic key   
  39.                 rsa.FromXmlString(publicKey);  
  40.   
  41.                 // Encrypt the data and store it in the encyptedData Array   
  42.                 encryptedData = rsa.Encrypt(dataToEncrypt, false);   
  43.             }  
  44.             // Save the encypted data array into a file   
  45.             File.WriteAllBytes(fileName, encryptedData);  
  46.   
  47.             Console.WriteLine("Data has been encrypted");   
  48.         }  
  49.   
  50.         // Method to decrypt the data withing a specific file using a RSA algorithm private key   
  51.         static string DecryptData(string privateKey,string fileName)  
  52.         {  
  53.             // read the encrypted bytes from the file   
  54.             byte[] dataToDecrypt = File.ReadAllBytes(fileName);  
  55.   
  56.             // Create an array to store the decrypted data in it   
  57.             byte[] decryptedData;  
  58.             using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())  
  59.             {  
  60.                 // Set the private key of the algorithm   
  61.                 rsa.FromXmlString(privateKey);  
  62.                 decryptedData = rsa.Decrypt(dataToDecrypt, false);   
  63.             }  
  64.   
  65.             // Get the string value from the decryptedData byte array   
  66.             UnicodeEncoding byteConverter = new UnicodeEncoding();  
  67.             return byteConverter.GetString(decryptedData);   
  68.         }  
  69.     }  
  70. }  
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.


Similar Articles