5,286,006 members and growing! (20,706 online)
Email Password   helpLost your password?
Desktop Development » Files and Folders » Encryption     Intermediate License: The Code Project Open License (CPOL)

File Encryption and Decryption in C#

By Steve Lydford

Demonstrates how to encrypt and decrypt any file type using C#
C# (C# 1.0, C# 2.0, C# 3.0, C#), Windows, .NET, WinForms, Dev

Posted: 14 May 2008
Updated: 14 May 2008
Views: 3,006
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
5 votes for this Article.
Popularity: 1.27 Rating: 1.82 out of 5
0 votes, 0.0%
1
4 votes, 100.0%
2
0 votes, 0.0%
3
0 votes, 0.0%
4
0 votes, 0.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

This article demonstrates how to use C# to encrypt and decrypt files of any type.

Background

Recently I needed to find a simple to way to encrypt and decrypt a file of any type (I actually needed to encrypt image and text files) and any size. I found hundreds of examples on the web, many of which just plain didn't work, or threw errors on certain file types.

Eventually I put together the following two methods using the Rijndael encryption algorithm, they simply require that you pass them the full path to the original and target files. They both require the System.Security, System.Security.Cryptography, System.Runtime.InteropServices and System.Text.RegularExpressions namespaces.

Unfortunately, as I looked at so many examples on the web and actually did all this a while ago, I do not remember which bits of code were orginally written by who. So if you recognise some of it, many thanks, leave a comment below so that your work doesn't go unrecognised.

Using the code

There are two methods: encryptFile and decryptFile. They both require that you pass in the filenames and paths of the source and destination files as strings. It is important that the user has the necessary files rights to create the encrypted file.

        ///<summary>
        /// Steve Lydford - 12/05/2008.
        ///
        /// Encrypts a file using Rijndael algorithm.
        ///</summary>
        ///<param name="inputFile"></param>
        ///<param name="outputFile"></param>
        private void EncryptFile(string inputFile, string outputFile)
        {
 
            try
            {
                string password = @"myKey123"; // Your Key Here
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);
 
                string cryptFile = outputFile;
                FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);
 
                RijndaelManaged RMCrypto = new RijndaelManaged();
 
                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateEncryptor(key, key),
                    CryptoStreamMode.Write);
 
                FileStream fsIn = new FileStream(inputFile, FileMode.Open);
 
                int data;
                while ((data = fsIn.ReadByte()) != -1)
                    cs.WriteByte((byte)data);
 
                
                fsIn.Close();
                cs.Close();
                fsCrypt.Close();
            }
            catch
            {
                MessageBox.Show("Encryption failed!", "Error");
            }
        }
        ///<summary>
        /// Steve Lydford - 12/05/2008.
        ///
        /// Decrypts a file using Rijndael algorithm.
        ///</summary>
        ///<param name="inputFile"></param>
        ///<param name="outputFile"></param>
        private void DecryptFile(string inputFile, string outputFile)
        {
 
            {
                string password = @"myKey123"; // Your Key Here
 
                UnicodeEncoding UE = new UnicodeEncoding();
                byte[] key = UE.GetBytes(password);
 
                FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
 
                RijndaelManaged RMCrypto = new RijndaelManaged();
 
                CryptoStream cs = new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);
 
                FileStream fsOut = new FileStream(outputFile, FileMode.Create);
 
                int data;
                while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((byte)data);
 
                fsOut.Close();
                cs.Close();
                fsCrypt.Close();
 
            }
        }


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Steve Lydford



Occupation: Software Developer (Senior)
Location: United Kingdom United Kingdom

Other popular Files and Folders articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 6 of 6 (Total in Forum: 6) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralKey and StackTracememberthund3rstruck5:37 19 May '08  
GeneralKey in codememberHellcat8214:36 15 May '08  
GeneralRe: Key in codemembermav.northwind19:57 15 May '08  
GeneralRe: Key in codememberHellcat8222:40 15 May '08  
AnswerRe: Key in codememberSteve Lydford0:14 16 May '08  
GeneralRe: Key in codememberHellcat821:00 16 May '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 14 May 2008
Editor:
Copyright 2008 by Steve Lydford
Everything else Copyright © CodeProject, 1999-2008
Web11 | Advertise on the Code Project