Encryption is
the process that converting normal message Plain-text into Cipher-text. It is a
process of converting normal data into an unreadable form. It helps you to
avoid any unauthorized access to data.
Decryption is
the process that converting Cipher-text into its original form Plain-text. It is
a method of converting the unreadable/coded data into its original form.
This example will help you to encrypt and decrypt a plan text as string in dotnet core c#,
This example will help you to encrypt and decrypt a plan text as string in dotnet core c#,
using
System.IO;
using
System.Text;
using
System.Security.Cryptography;
using
System;
public static class EncryptionHelper
{
public static string
Encrypt(string clearText)
{
string
EncryptionKey = "Anilkey123";
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)
{
string
EncryptionKey = " Anilkey123";
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;
}
}
Used of this method looks like,
string
encryptedUserName = EncryptionHelper.Encrypt(userName_text);
string
decryptedUserName = EncryptionHelper.Decrypt(encryptUserName);