Encryption and Decryption in asp.net C#

I am explaining here with an example to encrypt and decrypt any string in asp.net.
//namespaces
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
Encryption:
Encryption is a process by which you can convert plain(meaningful) text to cipher(meaningless) text. We use encryption to make data safe.
Example
private string EncryptionKey = "test2022";
 
private string Encrypt(string clearText)
{
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText)
    Aes encryptor = Aes.Create();
    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4e, 0x65, 0x64, 0x76 });
    encryptor.Key = pdb.GetBytes(32);
    encryptor.IV = pdb.GetBytes(16);
 
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write);
    cs.Write(clearBytes, 0, clearBytes.Length);
    cs.Close();
 
    clearText = Convert.ToBase64String(ms.ToArray());
    return clearText;
}
 
//string encryptedText = Encrypt("Vikash");
//Output: Ww97BC1n/AqY3Lf0bNkMWw==
Dycryption:
Dycryption is a process by which you can convert cipher(meaningless) text to plain(meaningful) text.
Example
private string Decrypt(string cipherText)
{
    cipherText = cipherText.Replace(" ", "+");
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    Aes encryptor = Aes.Create();
    Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4e, 0x65, 0x64, 0x76 });
    encryptor.Key = pdb.GetBytes(32);
    encryptor.IV = pdb.GetBytes(16);
 
    MemoryStream ms = new MemoryStream();
    CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write);
    cs.Write(clearBytes, 0, clearBytes.Length);
    cs.Close();
 
    cipherText = Encoding.Unicode.GetString(ms.ToArray());
    return cipherText;
}
 
//string decryptedText = Decrypt("Ww97BC1n/AqY3Lf0bNkMWw==");
//Output: Vikash

 Posted Comments

No comments have been posted to this article.

 Post a comment

Name:
Email:
Comment:
Security Code:
40 + 15
=
We don't publish your email on our website.