Symmetric v/s Asymmetric Encryption


Symmetric encryption is performed on streams whereas asymmetric encryption works on a small number of bytes.

Photo by Markus Winkler from Pexels

What is Encryption?

Encryption means the conversion of data to symbols so that its contents cannot be understood if intercepted.

There are mainly two types of encryption techniques:

  1. Symmetric Encryption

  2. Asymmetric Encryption

What is Symmetric Encryption?

Symmetric encryption is executed on streams and therefore, it’s useful to encrypt vast volumes of data.

Let us consider an example of writing encrypted text into a .txt file and understand symmetric encryption step by step.

Create a file stream

Create a new file stream with OpenOrCreate file mode.

FileStream myStream = new FileStream("test.txt", FileMode.OpenOrCreate);

AES instance

Build a unique instance of the default Aes implementation class and encrypt the stream.

Aes aes = Aes.Create();
byte[] key = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };
byte[] iv = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 };

Create a Crypto Stream

Build a CryptoStream, pass it the FileStream, and encrypt it with the Aes class and pass onto StreamWriter.

CryptoStream cryptStream = new CryptoStream(
aes.CreateEncryptor(key, iv),

Create a StreamWriter for quickly write to the file stream.

StreamWriter sWriter = new StreamWriter(cryptStream);

Write to the stream & close connections.

sWriter.WriteLine("Hello World!");

Complete Code

What is Asymmetric Encryption?

Asymmetric encryption is done on a small number of bytes and is therefore beneficial only for small amounts of data.

Initialize Public Key

Create a byte arrays to the public key information.

byte[] modulus = {214,46,220,83,160,73,40,39,201,155,19,202,3,11,191,178,56,
byte[] exponent = { 1, 0, 1 };

Create an RSA class instance

Build a new instance of the RSA class.

RSA rsa = RSA.Create();

Create RSA parameters & import key

Build a new instance of the RSAParameters structure as shown below, Set rsaKeyInfo to the public key values and Import key parameters into RSA.

RSAParameters rsaKeyInfo = new RSAParameters();
rsaKeyInfo.Modulus = modulus;
rsaKeyInfo.Exponent = exponent;

AES class & Encryption

Build a new instance of the default Aes implementation class and Encrypt the symmetric key and IV.

Aes aes = Aes.Create();
encryptedKey = rsa.Encrypt(aes.Key, RSAEncryptionPadding.Pkcs1);
encryptedIV = rsa.Encrypt(aes.IV, RSAEncryptionPadding.Pkcs1);

Complete Code

Thank you for reading. I hope you like the article..!!

#AsymmetricEncryption #Csharp #Encryption #Dotnet #SymmetricEncryption

Recent Posts

See All

Design Pattern – Adapter

#Aspnetcore #AdapterDesignPattern #Csharp #DesignPatterns #Dotnet According to Gang of Four, the Adapter Pattern converts the interfaces of a class into interfaces that the client requires. In other w