C# Tutorial Encrypt and Decrypt a String

preview_player
Показать описание
Hello Guys,
In this tutorial i tell you about c# encrypt and decrypt data.
i given code below:

Code for Encryption:
***************************************
public static string Encrypt(string clearText)
{
string EncryptionKey = "khalid123";
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;
}

Code for Decryption:
*************************************
public static string Decrypt(string cipherText)
{
string EncryptionKey = "khalid123";
cipherText = cipherText.Replace(" ", "+");
try
{
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());
}
}
}
catch (Exception ex)
{

}

return cipherText;
}


I am Khalid Ahmed and welcome to my channel “KhalidTech”. I created this channel for with the aim to help you to learn website development, mobile development, programming, online earnings, English language, blogging, online marketing,SEO etc. In this channel I share technical videos, English languages videos in your own language “Urdu” to make technical learning easy for you. This channel is very helpful for all my friends, students who is interested to learn technical things in Urdu. Every day I upload new technical videos on my channel.
“Come to learn go to earn”.
Please subscribe my channel to receive notification of my latest videos.
Website
Click to see all our videos
Subscribe to my channel
KhalidTech App
Рекомендации по теме