Geekpedia Programming Tutorials






Encrypting and Decrypting Files with C#

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.

On Wednesday, September 26th 2007 at 09:13 PM
By Andrei Pociu (View Profile)
*****   (Rated 4.6 with 12 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project (Visual Studio 2005)

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.

File Encrypter

Encrypter Dialogs

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:

Test Encrypted


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:

File Decrypter

Decrypter Dialogs

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.
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Saiful Islam on Monday, October 1st 2007 at 10:11 AM

helpful article.

by Sachin Kalse on Friday, November 23rd 2007 at 07:13 AM

Dear Andrei Pociu,
We are also working on encryption-decryption that works well on .doc, .xls, .ppt files well, unfortuantely when it comes to .docx , .xlsx kind of Office 2007 files, the decryption fails.
I tried with you sample code also, but failled, as you have clearly said in the begining that this is for text files.
If I am not disturbing you schedule, please guide.
regards
Sachin

by Shadyyx on Wednesday, December 5th 2007 at 04:45 AM

.docx, .xlsx, .ppsx etc files from MSO 2007 are no longer TEXT files - they are saved and held as BINARY files (like dll, exe, bat, etc)...

by Ruba on Wednesday, December 12th 2007 at 02:03 AM

Dear Andrei
I am working on the above application.It works for encryption.But while decrypting I am getting the following exception

Unhandled exception in type
\'System.Security.Cryptography.CryptographicException\' occurred in mscorlib.dll
Additional information \'Bad Data\'

I am using visual studio 2003.Is there any problem with the version compatiblity?.

Thanks and Regards
Ruba.S

by Richard on Tuesday, March 4th 2008 at 02:25 PM

Get the System.Security.Cryptography.CryptographicExecption sometmes in visual studio 2008 as well. If I put file externsions on all the files it seems to work. If I do not put file extensions on some of the files it seems to through the above error some times. Have not been able to work out just what combination causes it.

It is a good example anyway.

Rick S

by sundar on Wednesday, March 12th 2008 at 09:24 AM

hi ,
The above coding works well. But how can i modify the coding so that user can create a key file which could be used for encryption purpose. The same key file should be used for decryption purpose also.

thanks dude


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons