Friday 23 June 2017

Asymmetric Encryption

Asymmetric Encryption is an alternative to symmetric encryption, the main reason to use Asymmetric encryption is to avoid using a secret key. Asymmetric Encryption instead uses two mathematically related keys which compliment one another. One key is used to encrypt and the other is used to decrypt, they key for encryption is called the public key which is what you would share and the key used to decrypt is called the private key which you would keep to yourself.

so if you your friend wanted to send you something securely you could send him the public key, he could use it to encrypt the data and send it to you. You then would use the private key to decrypt the message.

The main disadvantage of Asymmetric encryption is that because it is more complex it's also slower, but on the other hand you eliminate the secret key, greatly minimizing the odds of your encryption key becoming compromised.

using System;
using System.Security.Cryptography;
using System.Text;

namespace pc.AsymmetricEncryption01
    class Program
        static byte[] Encrypt(string Data, out string publicKey, out string privateKey) {
            using (var RSA = new RSACryptoServiceProvider())
                try {
                    publicKey = RSA.ToXmlString(false);
                    privateKey = RSA.ToXmlString(true);

                    var byteData = Encoding.Default.GetBytes(Data);
                    return RSA.Encrypt(byteData, false);
                finally {

        static byte[] Decrypt(byte[] EncryptedData, string privateKey)
            using (var RSA = new RSACryptoServiceProvider())
                try {
                    return RSA.Decrypt(EncryptedData, false);
                finally {
        static void Main(string[] args)
            var data = "Hello world, this is my secret data i want encrypted";
            string publicKey;
            string privateKey;

            var encryptedData = Encrypt(data, out publicKey, out privateKey);

            Console.WriteLine($"Public Key\n{publicKey}");

            var decyptedData = Decrypt(encryptedData, privateKey);


To Sum up

  •  Asymmetric Encryption is otherwise known as Public Key Encryption 
  • One key is used for encryption and the other for decryption 
  • Commonly used for signatures. 
  • Cryptography namespace includes 4 asymmetric algorithms: 
    • DSA 
    • ECDiffieHellman 
    • ECDsa 
    • RSA - the most popular