How To Encrypt And Decrypt In C# Using Simple AES Keys

In this article, I'm going to tell you how to encrypt and decrypt a string in Visual Studio.

Whenever the word encryption comes to our mind, we will move to the topic AES (Advanced Encryption Standard). But today I came up with an ideology of using Public Key Cryptography. One can perform encryption and decryption by the source code provided below but to better understand the concept, please read the theory.

Cryptology

Cryptology is the science of using mathematics to encrypt and decrypt data.

Generally, it is classified into two categories.

Cryptanalysis

It refers to the study of ciphertext in cryptosystems.

Cryptography

In terms of Cryptography, the phrase ‘crypto’ means secret, and ‘graph’ means writing, So cryptography means ‘secret writing’.

It is a method of modifying original data in a particular form so that only those for whom it is intended can read and process it.

Cryptography is most often associated with scrambling plain text into ciphertext and then back again.

Cryptography is the science of keeping information secure. It involves encryption and decryption of messages.

Basic Image of Encryption.

Encryption

There are two types of CryptographyThey are,

Secret Key Cryptography

The encryption key and decryption key are the same.

 Cryptography

Let ‘K’ be the key.

The message TEJA can be represented as WHMD.

Here., the key value K=3, and one can easily identify the key.

Public key Cryptography

The different keys for encryption and decryption.

Public key

Process flow example of two-way communication based on my understanding

Let's assume Santhosh and Teja are two persons who agree to have a public key = 5.

Santhosh picks message = 3, while Teja picks message = 2. Santhosh computes encryption = 3 x 5 (15), and Teja computes encryption = 2 x 5 (10) .

Santhosh and Teja exchange encrypted messages.

Santhosh computes k = 3*10 = 30, while Teja computer k = 2*15 = 30. They now use k = 30.

Thus the messages can be easily encrypted and decrypted.

Ok, now coming to the C# coding part, the Source code of encryption and decryption for one-way communication is given below,

Encryption in C#

Here I have taken a string with the value "Water" to encrypt

I had taken "Santhosh" as the public key and "engineer" as a secret key and here I had got the encrypted value as "VtbM/yjSA2Q="

public string Encrypt()
{
    try
    {
        string textToEncrypt = "Water";
        string ToReturn = "";
        string publickey = "santhosh";
        string secretkey = "engineer";
        byte[] secretkeyByte = {};
        secretkeyByte = System.Text.Encoding.UTF8.GetBytes(secretkey);
        byte[] publickeybyte = {};
        publickeybyte = System.Text.Encoding.UTF8.GetBytes(publickey);
        MemoryStream ms = null;
        CryptoStream cs = null;
        byte[] inputbyteArray = System.Text.Encoding.UTF8.GetBytes(textToEncrypt);
        using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
        {
            ms = new MemoryStream();
            cs = new CryptoStream(ms, des.CreateEncryptor(publickeybyte, secretkeyByte), CryptoStreamMode.Write);
            cs.Write(inputbyteArray, 0, inputbyteArray.Length);
            cs.FlushFinalBlock();
            ToReturn = Convert.ToBase64String(ms.ToArray());
        }
        return ToReturn;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message, ex.InnerException);
    }
}

Decryption in C#

After encrypting the value "Water", I got the encrypted value "VtbM/yjSA2Q=" which now will be decrypted back to "Water"

public string Decrypt()
{
    try
    {
        string textToDecrypt = "VtbM/yjSA2Q=";
        string ToReturn = "";
        string publickey = "santhosh";
        string privatekey = "engineer";
        byte[] privatekeyByte = System.Text.Encoding.UTF8.GetBytes(privatekey);
        byte[] publickeybyte = System.Text.Encoding.UTF8.GetBytes(publickey);
        MemoryStream ms = null;
        CryptoStream cs = null;
        byte[] inputbyteArray = new byte[textToDecrypt.Replace(" ", "+").Length];
        inputbyteArray = Convert.FromBase64String(textToDecrypt.Replace(" ", "+"));
        using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
        {
            ms = new MemoryStream();
            cs = new CryptoStream(ms, des.CreateDecryptor(publickeybyte, privatekeyByte), CryptoStreamMode.Write);
            cs.Write(inputbyteArray, 0, inputbyteArray.Length);
            cs.FlushFinalBlock();
            Encoding encoding = Encoding.UTF8;
            ToReturn = encoding.GetString(ms.ToArray());
        }
        return ToReturn;
    }
    catch (Exception ae)
    {
        throw new Exception(ae.Message, ae.InnerException);
    }
}

By using these two methods we can encrypt and decrypt the string in C#. One should note that the key size of the public key and private key should be equal and should not exceed less than 8 characters as I had encoded using UTF8.

Thanks for reading the article.

All the best for your future endeavors!


Similar Articles