C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » Encryption »

Encrypt/Decrypt text files using Rijndael or TripleDES


Posted Date: 11 Jun 2009    Resource Type: Code Snippets    Category: Encryption
Author: Deepika HaridasMember Level: Diamond    
Rating: 1 out of 5Points: 10 (Rs 2)



This sample code shows you how to use Rijndael or TripleDES to encrypt and decrypt text files that you can browse for and load into a TextBox.

using System.Security.Cryptography;
private SampleCrypto crpSample;
private bool FormHasLoaded = false;
private string strCurrentKeyFile;
private string strSourcePath;
private string strRijndaelSaltIVFile;
private string strTripleDESSaltIVFile;

This routine handles the "Load" button click event.


private void btnLoad_Click(object sender, System.EventArgs e)
{
//Open fle dialog control used
odlgSourceFile.InitialDirectory = @"C:\";

// The file could be of any type. The Filter is restricted to Text Format
// files only for demonstration purposes.

odlgSourceFile.Filter = "Text Format (*.txt)|*.txt";
odlgSourceFile.FilterIndex = 1;

// The OpenFileDialog control only has an Open button, not an OK button.
// However, there is no DialogResult.Open enum so use DialogResult.OK.

if (odlgSourceFile.ShowDialog() == DialogResult.OK) {
try
{
txtCrypto.Text = ReadFileAsstring(odlgSourceFile.FileName);
strSourcePath = odlgSourceFile.FileName;
}
catch( ArgumentException exp)
{
MessageBox.Show(exp.Message, this.Text,MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}


This routine handles the "Encrypt" and "Decrypt" button click events.

private void EncryptDecrypt_Click(object sender, System.EventArgs e)
{
Button btn = (Button) sender;
try
{
crpSample.SourceFileName = strSourcePath;
if (btn.Name == "btnEncrypt")
{
crpSample.EncryptFile();
}
else
{
crpSample.DecryptFile();
}

txtCrypto.Text = ReadFileAsstring(strSourcePath);
}
catch(CryptographicException expCrypto)
{
MessageBox.Show("The file could not be decrypted. Make sure you entered " +
"the correct password. " + Environment.NewLine + "This error can also be caused by changing " +
"crypto type between encryption and decryption.",
this.Text,MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch( Exception exp)
{
MessageBox.Show(exp.Message, this.Text,MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}


This routine encrypts a file.

public void EncryptFile()
{
// Create a FileStream object to read in the source file.
FileStream fsInput = new FileStream(strSourceFile, FileMode.Open, FileAccess.Read);
// Create a byte array from the FileStream object by reading in the source file.

byte[] abytInput = new byte[Convert.ToInt32(fsInput.Length)];
fsInput.Read(abytInput, 0, Convert.ToInt32(fsInput.Length));
fsInput.Close();

// Create a FileStream object to write to a temp file.

FileStream fsCipherText = new FileStream("temp.dat", FileMode.Create, FileAccess.Write);
fsCipherText.SetLength(0);

// Create a Crypto Stream that transforms the file stream using the chosen
// encryption and writes it to the output FileStream object.

CryptoStream csEncrypted = new CryptoStream(fsCipherText, crpSym.CreateEncryptor(),
CryptoStreamMode.Write);
csEncrypted.Write(abytInput, 0, abytInput.Length);
csEncrypted.FlushFinalBlock();
// Clean up. There is no need to call fsCipherText.Close() because closing the
// crypto stream automatically encloses the stream that was passed into it.
csEncrypted.Close();
}


This routine decrypts a file.

public void DecryptFile()
{
// Create a FileStream object to read back the encrypted file.
FileStream fsCipherText = new FileStream(strSourceFile, FileMode.Open, FileAccess.Read);
// Create a FileStream object to write to the temp file.
FileStream fsPlainText = new FileStream("temp.dat", FileMode.Create, FileAccess.Write);
// Read in the encrypted file and decrypt.
CryptoStream csDecrypted = new CryptoStream(fsCipherText, crpSym.CreateDecryptor(),
CryptoStreamMode.Read);
// Create a StreamWriter to write to the temp file.
StreamWriter swWriter = new StreamWriter(fsPlainText);
// Read the decrypted stream into a StreamReader.
StreamReader srReader = new StreamReader(csDecrypted);
try
{
// Write out the decrypted stream.
swWriter.Write(srReader.ReadToEnd());
}
catch( CryptographicException expCrypto)
{
throw new CryptographicException();
}
finally
{
// Close and clean up.
swWriter.Close();
csDecrypted.Close();
}
}



Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
TripleDES  .  Text  .  Rijndael  .  Opendialog  .  Filestream  .  Files  .  Encrypt  .  Decrypt  .  Cryptography  .  Cipher  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: C# and VB.Net Encryption
Previous Resource: Encrypting and Decripting values using Security Key
Return to Discussion Resource Index
Post New Resource
Category: Encryption


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use