Click here to Skip to main content
Click here to Skip to main content
Go to top

File Encryption and Decryption in C#

, 14 May 2008
Rate this:
Please Sign up or sign in to vote.
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.

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

Share

About the Author

Steve Lydford
Software Developer (Senior)
United Kingdom United Kingdom
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionNice Pinmemberezelden.sahi10-Apr-14 0:39 
QuestionProvide me the complete application so I can run that PinmemberMember 106801324-Apr-14 0:01 
GeneralWOW!!!!! MY VOTE OF 5.. Pinmemberparkavikarthi21-Sep-13 1:22 
GeneralMy vote of 4 PinprofessionalAmir Mohammad Nasrollahi29-Jul-13 22:19 
GeneralMy vote of 5 PinmemberJPFriederich19-Jun-13 0:49 
GeneralMy vote of 3 PinmemberB.Farivar27-Apr-13 19:40 
QuestionEncrypion/Decryption PinmemberPeter Van Zyl11-Feb-13 2:40 
GeneralThanks PinmemberImteyaz Ahmed3-Sep-12 8:14 
GeneralRe: Thanks PinmemberSteve Lydford4-Sep-12 5:01 
QuestionInput and Output files Pinmemberpeek4y1-Jul-12 20:58 
GeneralMy vote of 4 Pinmemberkaliprasad12317-Jun-12 21:05 
GeneralEncryption PinmemberFreshino14-May-12 21:56 
QuestionError when Encrypting PinmemberMember 795084531-Oct-11 4:09 
Generalexception [modified] Pinmembersamson radu11-May-11 3:54 
Questionkey length Pinmemberale.zad23-Apr-11 3:11 
GeneralRe: key length [modified] Pinmemberjoaquin.cubero18-Nov-11 12:09 
Generalerror in encryption code Pinmemberamrita_patole9-Mar-11 8:05 
GeneralMy vote of 5 Pinmembervahapdemir3-Aug-10 22:29 
GeneralWon't compile for me Pinmemberblipton18-Mar-10 14:55 
AnswerRe: Won't compile for me PinmemberSteve Lydford18-Mar-10 23:14 
GeneralRe: Won't compile for me Pinmemberblipton19-Mar-10 8:37 
GeneralMy vote of 1 PinmemberNilesh Kumar 20088-Jun-09 0:17 
AnswerRe: My vote of 1 PinmemberSteve Lydford10-Aug-09 22:57 
QuestionPossible to know Key From Encrypt and Decrypt String ?? Pinmemberketan d patel16-Feb-09 19:11 
Generaldecryption problem Pinmember4sasha17-Nov-08 6:46 
Generalexecution time PinmemberMember 390465319-Oct-08 22:24 
GeneralRe: execution time PinmemberIvan Svogor29-Oct-08 3:40 
GeneralKey and StackTrace Pinmemberthund3rstruck19-May-08 4:37 
GeneralKey in code PinmemberHellcat8215-May-08 13:36 
GeneralRe: Key in code Pinmembermav.northwind15-May-08 18:57 
GeneralRe: Key in code PinmemberHellcat8215-May-08 21:40 
AnswerRe: Key in code PinmemberSteve Lydford15-May-08 23:14 
GeneralRe: Key in code PinmemberHellcat8216-May-08 0:00 
GeneralRe: Key in code PinmemberShargon_8530-Jun-13 22:15 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140926.1 | Last Updated 15 May 2008
Article Copyright 2008 by Steve Lydford
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid