Click here to Skip to main content
Licence CPOL
First Posted 14 May 2008
Views 54,642
Bookmarked 48 times

File Encryption and Decryption in C#

By | 14 May 2008 | Article
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)

About the Author

Steve Lydford

Software Developer (Senior)

United Kingdom United Kingdom

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralEncryption PinmemberFreshino21:56 14 May '12  
QuestionError when Encrypting PinmemberMember 79508454:09 31 Oct '11  
Generalexception [modified] Pinmembersamson radu3:54 11 May '11  
Questionkey length Pinmemberale.zad3:11 23 Apr '11  
GeneralRe: key length [modified] Pinmemberjoaquin.cubero12:09 18 Nov '11  
Generalerror in encryption code Pinmemberamrita_patole8:05 9 Mar '11  
GeneralMy vote of 5 Pinmembervahapdemir22:29 3 Aug '10  
GeneralWon't compile for me Pinmemberblipton14:55 18 Mar '10  
AnswerRe: Won't compile for me PinmemberSteve Lydford23:14 18 Mar '10  
GeneralRe: Won't compile for me Pinmemberblipton8:37 19 Mar '10  
GeneralMy vote of 1 PinmemberNilesh Kumar 20080:17 8 Jun '09  
AnswerRe: My vote of 1 PinmemberSteve Lydford22:57 10 Aug '09  
QuestionPossible to know Key From Encrypt and Decrypt String ?? Pinmemberketan d patel19:11 16 Feb '09  
Generaldecryption problem Pinmember4sasha6:46 17 Nov '08  
Generalexecution time PinmemberMember 390465322:24 19 Oct '08  
GeneralRe: execution time PinmemberIvan Svogor3:40 29 Oct '08  
GeneralKey and StackTrace Pinmemberthund3rstruck4:37 19 May '08  
I would make the key a public static member that must be set by the caller, this way if your encryption library gets compromised all the solutions implementing the library are not un-necessarily exposed.
 
Also, refer to the .NET Bible (ISBN-10 0735621721 Practical Guidelines and Best Practices for C#.NET Developers) Section 33.16 Protect Libraries from Unauthorized Use. You need to make sure that the only assemblies that can access your encryption library are ones that you explicitly define (otherwise any idiot could crack your code just by loading your library into Visual Studio). So you need to digitally sign all assemblies that are going to need to use this library and then walk the stack to validate that the caller assembly has been granted explicit access to execute the encrypt and decrypt methods via the digital signatures you establish for the solution.
GeneralKey in code PinmemberHellcat8213:36 15 May '08  
GeneralRe: Key in code Pinmembermav.northwind18:57 15 May '08  
GeneralRe: Key in code PinmemberHellcat8221:40 15 May '08  
AnswerRe: Key in code PinmemberSteve Lydford23:14 15 May '08  
GeneralRe: Key in code PinmemberHellcat820:00 16 May '08  

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.

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