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