In this C# programming tutorial we're going to learn how to encrypt and decrypt text files using the cryptographic services of .NET Framework 2.0.
Encryption and decryption are no longer difficult topics, since with the help of .NET Framework any intermediate programmer can encrypt and decrypt a string using a series of algorithms. In this tutorial we’re not going to just encrypt and decrypt strings, but entire text files, since there’s only slightly more code needed for that.
I created two Visual Studio projects for this tutorial, however you could just as well place this code into a single one. Each of these two applications will deal with three files: the file to encrypt, the encryption key file and the encrypted file. The encryption key file will contain a key without which one cannot decrypt the file, as we will do using the DecryptFile application.
Encrypting Files Start Visual Studio 2005 and in a new project put up a form similar to the one below; in there we have txtFilePath, btnSelFile, btnEncFile and three dialogs: openFile, saveKeyFile, saveEncFile.
Two using statements are needed at the top of Form1.cs:
using System.IO;
using System.Security.Cryptography;
First action comes from the Select File button (btnSelFile). Nothing exciting happens in its Click event, we just show the OpenFileDialog and store the file’s path into the txtFilePath TextBox:
private void btnSelFile_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
txtFilePath.Text = openFile.FileName;
}
}
But here comes the actual encryption process, in the Click event of btnEncFile:
private void btnEncFile_Click(object sender, EventArgs e)
{
// After the user chose where he wants the key file saved
if (saveKeyFile.ShowDialog() == DialogResult.OK)
{
// And after the user chose where he wants the encrypted file saved
if (saveEncFile.ShowDialog() == DialogResult.OK)
{
FileStream fsFileOut = File.Create(saveEncFile.FileName);
// The chryptographic service provider we're going to use
TripleDESCryptoServiceProvider cryptAlgorithm = new TripleDESCryptoServiceProvider();
// This object links data streams to cryptographic values
CryptoStream csEncrypt = new CryptoStream(fsFileOut, cryptAlgorithm.CreateEncryptor(), CryptoStreamMode.Write);
// This stream writer will write the new file
StreamWriter swEncStream = new StreamWriter(csEncrypt);
// This stream reader will read the file to encrypt
StreamReader srFile = new StreamReader(txtFilePath.Text);
// Loop through the file to encrypt, line by line
string currLine = srFile.ReadLine();
while (currLine != null)
{
// Write to the encryption stream
swEncStream.Write(currLine);
currLine = srFile.ReadLine();
}
// Wrap things up
srFile.Close();
swEncStream.Flush();
swEncStream.Close();
// Create the key file
FileStream fsFileKey = File.Create(saveKeyFile.FileName);
BinaryWriter bwFile = new BinaryWriter(fsFileKey);
bwFile.Write(cryptAlgorithm.Key);
bwFile.Write(cryptAlgorithm.IV);
bwFile.Flush();
bwFile.Close();
}
}
}
You can probably figure out what’s happening in here with the help of the comments. The user is prompted to select where he wants to save the key file and the encrypted file, followed by the creation of the encrypted file and the initialization of the encryption algorithm. Using a loop we go line by line through the file we want to encrypt, and using the encryption service we just set up, we encrypt each line and put it into the new file. The magic of encryption is done on the swEncStream.Write(currLine); where the unencrypted line is passed to the cryptographic stream.
Compile, run and encrypt your file. The content of the encrypted file will look similar to this:
Decrypting Files Now that you got your little encrypted file, it’s not of much use unless you get to decrypt it. So create another Visual Studio 2005 application with a form looking much like the one for the encrypter:
txtFilePath, btnSelPath, btnDecFile, openFile, openKeyFile, saveDecFile are the elements of this form. You’ll notice that instead of one OpenFileDialogs and two SaveFileDialogs, we have the opposite. That’s because in this application we’re going to open the encrypted file, then the key file and finally save the decrypted file.
Obviously we’ll need these again:
using System.IO;
using System.Security.Cryptography;
In the Click event of the btnSelFile button we have the same story as in the previous application; this time we're opening the encrypted file:
private void btnSelFile_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
txtFilePath.Text = openFile.FileName;
}
}
Finally, the file is being decrypted in the btnDecFile Click event. There’s slighly less action hapening here than in the encryption process.
private void btnDecFile_Click(object sender, EventArgs e)
{
// After the encrypted file has been selected for opening
if (openKeyFile.ShowDialog() == DialogResult.OK)
{
// After the location where the decrypted file should be saved has been decided
if (saveDecFile.ShowDialog() == DialogResult.OK)
{
// The encrypted file
FileStream fsFileIn = File.OpenRead(txtFilePath.Text);
// The key
FileStream fsKeyFile = File.OpenRead(openKeyFile.FileName);
// The decrypted file
FileStream fsFileOut = File.Create(saveDecFile.FileName);
// Prepare the encryption algorithm and read the key from the key file
TripleDESCryptoServiceProvider cryptAlgorithm = new TripleDESCryptoServiceProvider();
BinaryReader brFile = new BinaryReader(fsKeyFile);
cryptAlgorithm.Key = brFile.ReadBytes(24);
cryptAlgorithm.IV = brFile.ReadBytes(8);
// The cryptographic stream takes in the encrypted file
CryptoStream csEncrypt = new CryptoStream(fsFileIn, cryptAlgorithm.CreateDecryptor(), CryptoStreamMode.Read);
// Write the new unecrypted file
StreamReader srCleanStream = new StreamReader(csEncrypt);
StreamWriter swCleanStream = new StreamWriter(fsFileOut);
swCleanStream.Write(srCleanStream.ReadToEnd());
swCleanStream.Close();
fsFileOut.Close();
srCleanStream.Close();
}
}
}
As you can see here, the decryption process is similar to the encryption once; however here the cryptographic key is being retrieved from the key file, and the CryptoStream takes in CryptoStreamMode. Read instead of CryptoStreamMode. Write. It all adds up, doesn’t it? Compile, run and you’ll now be able to decrypt the file you encrypted earlier, for as long as you specify the correct key for that file.
That’s it for this tutorial; we’ve encrypted and decrypted files (and thus strings.) If you have questions or suggestions, do post a comment.