Click here to Skip to main content
15,892,269 members
Articles / Desktop Programming / Windows Forms

File Encryption and Decryption in C#

Rate me:
Please Sign up or sign in to vote.
4.19/5 (41 votes)
14 May 2008CPOL1 min read 368.6K   89   46
Demonstrates how to encrypt and decrypt any file type using C#.

Introduction

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

Background

Recently, I needed to find a simple 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 use of 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 originally 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 file rights to create the encrypted file.

C#
///<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)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionPossible to know Key From Encrypt and Decrypt String ?? Pin
ketan d patel16-Feb-09 19:11
ketan d patel16-Feb-09 19:11 
Generaldecryption problem Pin
4sasha17-Nov-08 6:46
4sasha17-Nov-08 6:46 
Generalexecution time Pin
MarwaAlSagheer19-Oct-08 22:24
MarwaAlSagheer19-Oct-08 22:24 
GeneralRe: execution time Pin
Ivan Svogor29-Oct-08 3:40
Ivan Svogor29-Oct-08 3:40 
GeneralRe: execution time Pin
Wael_Galal_El_Deen18-Nov-14 16:57
Wael_Galal_El_Deen18-Nov-14 16:57 
GeneralKey and StackTrace Pin
thund3rstruck19-May-08 4:37
thund3rstruck19-May-08 4:37 
GeneralKey in code Pin
Hellcat8215-May-08 13:36
Hellcat8215-May-08 13:36 
GeneralRe: Key in code Pin
mav.northwind15-May-08 18:57
mav.northwind15-May-08 18:57 
Although you are right in considering the key in code a security flaw, I think it would be better to suggest an alternative Shucks | :-\ . Any ideas?

Regards,
mav

--
Black holes are the places where God divided by 0...

GeneralRe: Key in code Pin
Hellcat8215-May-08 21:40
Hellcat8215-May-08 21:40 
AnswerRe: Key in code Pin
Steve Lydford15-May-08 23:14
Steve Lydford15-May-08 23:14 
GeneralRe: Key in code Pin
Hellcat8216-May-08 0:00
Hellcat8216-May-08 0:00 
GeneralRe: Key in code Pin
Shargon_8530-Jun-13 22:15
Shargon_8530-Jun-13 22:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.