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.
///
/// Takes a byte array as input and returns an encrypted byte array, can be used for
/// both file and string encryption
///
///Byte array containing the unencrypted data
///Byte array containing the encrypted data
internalstaticbyte[] 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 = newTripleDESCryptoServiceProvider();
//Set the key and mode
desProvider.Key = encryptKey;
desProvider.Mode = CipherMode.ECB;
//Encrypt and return!
return desProvider.CreateEncryptor().TransformFinalBlock(unencryptedBytes, 0, unencryptedBytes.Length);
}
///
/// Takes an encrypted byte array as input and returns a decypted byte array. This method is used for both
/// string and file operations
///
///Byte array containing the encrypted data
///Byte array containing the decrypted data
internalstaticbyte[] 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 = newTripleDESCryptoServiceProvider();
//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.
Posted by Mitchel on Monday, September 25, 2006
Currently, there are no comments. Be the first to post one!
Click here to post a comment