TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Encryption and Decryption in .net
Raghavendra U
Aug 21, 2010
16.7
k
0
0
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
Encryption and Decryption in .net
Encryption:
using System.Security.Cryptography;
//add reference
private string EncryptString(string strText, string strEncrKey)
{
byte[] byKey = { };
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
DESCryptoServiceProvider Des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
MemoryStream Ms = new MemoryStream();
CryptoStream Cs = new CryptoStream(Ms, Des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
Cs.Write(inputByteArray, 0, inputByteArray.Length);
Cs.FlushFinalBlock();
return Convert.ToBase64String(Ms.ToArray());
}
catch (Exception ex)
{
return "Error Occured while Encrypting the '" + strText + "'";
}
}
private string EncryptText(string EncText)
{
return EncryptString(EncText, "&%#@?,:*");
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
TextBox2.Text = EncryptText(TextBox1.Text);
}
catch (Exception)
{ }
}
Decryption:
private string DecryptString(string strText, string sDecrKey)
{
byte[] byKey = { };
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
byte[] inputByteArray = new byte[strText.Length + 1];
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
DESCryptoServiceProvider Des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(strText);
MemoryStream Ms = new MemoryStream();
CryptoStream Cs = new CryptoStream(Ms, Des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
Cs.Write(inputByteArray, 0, inputByteArray.Length);
Cs.FlushFinalBlock();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(Ms.ToArray());
}
catch (Exception ex)
{
return "Error Occured while Decrypting the '" + strText + "'";
}
}
public string DecryptText(string DecText)
{
return DecryptString(DecText, "&%#@?,:*");
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
TextBox3.Text = DecryptText(TextBox2.Text);
}
catch (Exception)
{ }
}
Encryption and Decryption in .net