Encryption And Decryption in c# with key

In this article we will see how to Encrypt and Decrypt a string with a Secret Key in C#

we are going to use Symmetric encryption to encrypt and decrypt a string, Symmetric encryption is a type of encryption where only one key (a secret key) is used to both encrypt and decrypt information. The entities communicating via symmetric encryption must exchange the key so that it can be used in the decryption process.

see below image which shows how ecryption and decryption work with a key

ecrypt-decrypt-in-c#
ecrypt-decrypt-in-c#

as you see “Welcome@123” is a plain text that is encrypted using a secret key (A#$Derclfkdws) and decrypted with the same key returned output “Welcome@123”.

let’s move to the code part, I have created a simple console application that contains the “static void Main()” function and added two methods encrypt and decrypt in the same class (Program) where “Main()” exists so I can access both methods directly.

below namespaces will be require for encrypt/decrypt

Encryption/Decryption Example


using System.IO;
using System.Security.Cryptography;
using System.Text;
public static string Encrypt(string clearText) 
{
  string EncryptionKey = "A#$Derclfkdws"; // SecurityKey
  byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
  using(Aes encryptor = Aes.Create()) {
    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
      0x49,0x76,0x61,0x6e,0x20,0x4d,0x65,0x64,0x76,0x65,0x64,0x65,0x76
    });
    encryptor.Key = pdb.GetBytes(32);
    encryptor.IV = pdb.GetBytes(16);
    using(MemoryStream ms = new MemoryStream()) {
      using(CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) {
        cs.Write(clearBytes, 0, clearBytes.Length);
        cs.Close();
      }
      clearText = Convert.ToBase64String(ms.ToArray());
    }
  }
  return clearText;
}
public static string Decrypt(string cipherText) 
{
  try 
  {
    string EncryptionKey = "A#$Derclfkdws"; // SecurityKey
    cipherText = cipherText.Replace(" ", "+");
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using(Aes encryptor = Aes.Create()) {
      Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] {
        0x49,0x76,0x61,0x6e,0x20,0x4d,0x65,0x64,
        0x76,0x65,0x64,0x65,0x76
      });
      encryptor.Key = pdb.GetBytes(32);
      encryptor.IV = pdb.GetBytes(16);
      using(MemoryStream ms = new MemoryStream()) {
        using(CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) {
          cs.Write(cipherBytes, 0, cipherBytes.Length);
          cs.Close();
        }
        cipherText = Encoding.Unicode.GetString(ms.ToArray());
      }
    }
    return cipherText;
  } catch (Exception ex) {
    return "";
  }
}
static void Main(string[] args) 
{
  bool a = true;
  while (a) {
    Console.Write("Enter text :");
    var text = Console.ReadLine();
    var encryption = Encrypt(text);
    Console.WriteLine("your encrypted string is :" + encryption);
    Console.Write("enter encrypted text to decrypt: ");
    var userInput = Console.ReadLine();
    var plaintext = Decrypt(userInput);
    Console.WriteLine("Your decrypted string is :" + plaintext);
    Console.ReadLine();
  }
}

Output :

Enter Text : Welcome@123
Your encrypted string is : hVsmvQomEDYLnPZQWm2okAsUFXaC/F4Oc8TZPscSiMA=
Enter encrypted text to decrypt : hVsmvQomEDYLnPZQWm2okAsUFXaC/F4Oc8TZPscSiMA=
Your decrypted string is : Welcome@123

Share this article

Leave a Comment

Your email address will not be published. Required fields are marked *