Crypting files in c#

c# provides an easy to use API for encryption using symmetric key. The System.Security.Cryptography.RijndaelManaged class is an implementation for AES algorithm that supports key lengths of 128, 192, or 256 bits.

An other very useful API is System.Security.Cryptography.CryptoStream that makes possible to crypt/decrypt data on the fly. I’ll give an example of crypting / decrypting the content of a file, but the CryptoStream can be created over any other stream, for example over a stream from an HTTP web response.

Here is some sample code for encrypting a file: 

//note that key length is 16 bytes = 128 bits
static string symetricKey = “1111222233334444”;
static string iniParam = “5555666677778888”;
RijndaelManaged aes = new RijndaelManaged();
aes.KeySize = 128;
aes.Key = ASCIIEncoding.ASCII.GetBytes(symetricKey);
aes.IV = ASCIIEncoding.ASCII.GetBytes(iniParam);
    FileStream outFile = new FileStream(fileEncrypted, FileMode.Create, FileAccess.Write);
    CryptoStream cryptFile = new CryptoStream(outFile, aes.CreateEncryptor(), CryptoStreamMode.Write);
    FileStream inFile = new FileStream(fileClear, FileMode.Open, FileAccess.Read);
    byte[] buffer = new byte[1024];
    int readSize;
    while ((readSize = inFile.Read(buffer, 0, buffer.Length)) > 0)
        cryptFile.Write(buffer, 0, readSize);
catch (Exception ex)
    Console.WriteLine(“There was an error while cryptinng” + ex);

The corresponding code to decrypt the file is:

    FileStream outFile = new FileStream(fileClear, FileMode.Create, FileAccess.Write);
    FileStream inFile = new FileStream(fileEncrypted, FileMode.Open, FileAccess.Read);
    CryptoStream deCryptFile = new CryptoStream(inFile, aes.CreateDecryptor(), CryptoStreamMode.Read);
    byte[] buffer = new byte[1024];
    int readSize;
    while ((readSize = deCryptFile.Read(buffer, 0, buffer.Length)) > 0)
        outFile.Write(buffer, 0, readSize);
    //flush and close the output
    //close input
catch (Exception ex)
    Console.WriteLine(“There was an error while decrypting” + ex);                 
This entry was posted in c#. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s