Symmetric Cryptography


This is the simplest kind of Cryptography that involves only one secret key to encrypt and decrypt information. It is also known as “Secret Key Cryptography”.

Both Sender and receiver should know the key to be able to communicate securely.

For Example: if Mahesh & Shalini wants to communicate using symmetric-key cryptography then both would have to devise key and use it for every communication.

So Now, Mahesh encrypts his message using shared key, sends encrypted message to Shalini, then Shalini uses the same key again decrypt message to read.

To demonstration symmetric-key cryptography, I will use AES (Advanced Encryption Standard) & .Net Framework in-build library “System.Security.Cryptograph

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace SymmetricCryptography
{
class AdvancedEncryptionStandard
{
static void Main()
{
Console.WriteLine("Enter key to encrypt the text:");
var key = Console.ReadLine();
if (string.IsNullOrEmpty(key))
return;
Console.WriteLine("Enter message to encrypt");
var message = Console.ReadLine();
if (string.IsNullOrEmpty(message))
return;
var sha256 = SHA256.Create();
var keyBytes = sha256.ComputeHash(Encoding.ASCII.GetBytes(key));
var encryptedMessage = EncryptString(message, keyBytes);
Console.WriteLine($"Encrypted Message : {encryptedMessage}");
Console.WriteLine($"Decrypted Message : {DecryptString(encryptedMessage, keyBytes)}");
Console.ReadLine();
}
static string EncryptString(string plainText, byte[] key)
{
var encryptor = Aes.Create();
encryptor.Key = key;
encryptor.IV = new byte[16]; //initialization vector
using (var memoryStream = new MemoryStream())
{
var aesEncryptor = encryptor.CreateEncryptor();
using (var cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write))
{
var plainBytes = Encoding.ASCII.GetBytes(plainText);
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
var cipherBytes = memoryStream.ToArray();
var cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
return cipherText;
}
}
}
static string DecryptString(string cipherText, byte[] key)
{
var decryptor = Aes.Create();
decryptor.Key = key;
decryptor.IV = new byte[16]; //initialization vector
using (var memoryStream = new MemoryStream())
{
var aesDecryptor = decryptor.CreateDecryptor();
using (var cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write))
{
var cipherBytes = Convert.FromBase64String(cipherText);
cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
cryptoStream.FlushFinalBlock();
var plainBytes = memoryStream.ToArray();
return Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
}
}
}
}
}
Output:



Comments

Popular posts from this blog

SHA-256(Source Code in C# using .Net in-built Cryptography library) - Part II

Basic of Cryptography (Type of Cryptography)- Part II