Skip to main content
Email Password   helpLost your password?

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();

    }
}
You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralMy vote of 1 Pin
Nilesh Kumar 2008
1:17 8 Jun '09  
AnswerRe: My vote of 1 Pin
Steve Lydford
23:57 10 Aug '09  
GeneralPossible to know Key From Encrypt and Decrypt String ?? Pin
ketan d patel
20:11 16 Feb '09  
Generaldecryption problem Pin
4sasha
7:46 17 Nov '08  
Generalexecution time Pin
Member 3904653
23:24 19 Oct '08  
GeneralRe: execution time Pin
Ivan Svogor
4:40 29 Oct '08  
GeneralKey and StackTrace Pin
thund3rstruck
5:37 19 May '08  
GeneralKey in code Pin
Hellcat82
14:36 15 May '08  
GeneralRe: Key in code Pin
mav.northwind
19:57 15 May '08  
GeneralRe: Key in code Pin
Hellcat82
22:40 15 May '08  
AnswerRe: Key in code Pin
Steve Lydford
0:14 16 May '08  
GeneralRe: Key in code Pin
Hellcat82
1:00 16 May '08  


Last Updated 14 May 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2009