September 25, 2006

Encrypting Files

The need for encrypting files only seems to be increasing as I continue working in the .NET development field.  Regardless of the reason needed to encrypt the below two methods are very helpful and allow you to encrypt and decrypt a file (Loaded as an array of bytes).  The code will be explained below.

internal static byte[] Encrypt(byte[] unencryptedBytes)
{
    //Get the encryption key, basing it off of type of to prevent it from being directly
    //compiled into the project output!
    byte[] encryptKey = HashEncryptionKey(typeof(ByteArrayEncryption).ToString());
    //Declare the provider
    TripleDESCryptoServiceProvider desProvider = new TripleDESCryptoServiceProvider();
    //Set the key and mode
    desProvider.Key = encryptKey;
    desProvider.Mode = CipherMode.ECB;
    //Encrypt and return!
        return desProvider.CreateEncryptor().TransformFinalBlock(unencryptedBytes, 0, unencryptedBytes.Length);
}
internal static byte[] Decrypt(byte[] encryptedBytes)
{
    //Get the encryption key, basing it off of type of to prevent it from being directly
    //compiled into the project output!
    byte[] encryptKey = HashEncryptionKey(typeof(ByteArrayEncryption).ToString());
    //Declare the provider
    TripleDESCryptoServiceProvider desProvider = new TripleDESCryptoServiceProvider();
    //Set the key and mode
    desProvider.Key = encryptKey;
    desProvider.Mode = CipherMode.ECB;
    return desProvider.CreateDecryptor().TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
} 

The first thing to point out is this line byte[] encryptKey = HashEncryptionKey(typeof(ByteArrayEncryption).ToString()); in both of the Encrypt and Decrypt methods. Traditionally the value you specify to be used as the encryption key will be something secret, and something that is NOT hard coded in as a constant string value. If it is entered as a constant string value it will be stored exactly as that when your application is compilied and someone can easily use the ildasm.exe application to view this value, potentially aiding them with accessing your encrypted data.

The remainder of the sample is fairly simple. Using this method you can easily encrypt files in a very prompt manner. You can then take the created byte array and return it to a file on the users PC or easily insert it into a blob column in a database engine.

tags: .NET 1.1, .NET 2.0
comments powered by Disqus

Content provided in this blog is provided "AS-IS" and the information should be used at your own discretion.  The thoughts and opinions expressed are the personal thoughts of Mitchel Sellers and do not reflect the opinions of his employer.

Content Copyright

Content in this blog is copyright protected.  Re-publishing on other websites is allowed as long as proper credit and backlink to the article is provided.  Any other re-publishing or distribution of this content is prohibited without written permission from Mitchel Sellers.