Back to all posts

Encrypting Files

Posted on Sep 25, 2006

Posted in category:
Development
.NET

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 hardcoded 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 compiled 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.