Encrypting Data with the System.Security.Cryptography Classes


The final topic for this chapter is a very brief excursion into the world of encryption. Within the .NET Framework are a series of classes that provide support for all kinds of encryption. However, the main set of classes is in the System.Security.Cryptography namespace. Here you will find classes that support all kinds of ciphers, codes, and transformsincluding DES, TripleDES, SHA, MD5, RSA, Base64, and more.

While many programmers tend to shy away from this topic due to its complexity and specialist requirements, it is worth seeing an example of how you can use one of the classes here. The example page allows you to perform a TripleDES encryption transformation to the data when you generate it and the matching decryption transformation to an existing file. This means that, as you will see later, you can encrypt and then decrypt a file to prove that the transformations work.

Using TripleDES Encryption

Listing 15.32 shows the code in the transformToFrom3DES method of the Ch15DataProcess.cs file that performs both encryption and decryption using the tripleDESCryptoServiceProvider class. The techniques shown here are generic for most of the transformation types in the System.Security.Cryptography namespace, though each differs slightly depending on the criteria, keys, and other specifics of each transformation.

To demonstrate decryption of a file, and restore the original file, the code must use the same key and initialization vector (IV) values for both the encryption and decryption processes. It therefore saves these values in the ASP.NET session between requests. If you close the browser and then reopen it, your session is lost and the decryption process will use new valuesresulting in a failure to decrypt the file.

You can see in Listing 15.32 that the code first creates a new tripleDESCryptoServiceProvider instance, which contains autogenerated random key and IV values. Then it looks in the session for an existing key value, and if found, retrieves this and the corresponding IV and applies them to the tripleDESCryptoServiceProvider.

The CryptoAPITransform class performs the actual transformation, and so the code next creates an instance of this from the tripleDESCryptoServiceProvider, using the key and IV values it exposes. Most of the different types of transformation for the various cryptography providers use the CryptoAPITransform class in this way.

An individual transformation is limited to Int32.MaxValue bytes (around 2GB), and the CryptoAPITransform class exposes two methods that you use to perform larger transformations. The transformBlock method allows you to transform blocks of data and store each set of results in the appropriate position of a Byte array. The last transformation uses the TRansformFinalBlock method to transform any remaining data and add it to the end of the result array. However, in the example, the code assumes that the data is less than Int32.MaxValue and just uses the transformFinalBlock method.

Listing 15.32. Performing TripleDES Transformations

// create TripleDESCryptoServiceProvider instance TripleDESCryptoServiceProvider provider                 = new TripleDESCryptoServiceProvider(); // get existing key and IV from session if available HttpContext context = HttpContext.Current; String keyString = (String)context.Session["3DESKey"]; if (keyString != null && keyString.Length > 0) {   provider.Key = Encoding.Unicode.GetBytes(keyString);   provider.IV = Encoding.Unicode.GetBytes(                          (String)context.Session["3DESIV"]); } else {   // save the key and IV in session   context.Session["3DESKey"]          = Encoding.Unicode.GetString(provider.Key);   context.Session["3DESIV"]          = Encoding.Unicode.GetString(provider.IV); } // create encryption transformer using key and initialization // vector from TripleDESCryptoServiceProvider CryptoAPITransform transform = null; // check the encrypt parameter to this method to // see if it should encrypt or decrypt the data if (encrypt) {   transform = provider.CreateEncryptor(provider.Key, provider.IV)               as CryptoAPITransform; } else {   transform = provider.CreateDecryptor(provider.Key, provider.IV)               as CryptoAPITransform; } // transform the source array of bytes to a new array // assumes that the source is less than Int32.MaxValue // if larger, must use TransformBlock method first Byte[] transformedBytes = transform.TransformFinalBlock(                           sourceBytes, 0, sourceBytes.Length);

Figure 15.21 shows how you can see a TripleDES encryption using the example page. Select the Graphic image option as the source, turn on the encryption option, and select Disk file as the output. Then click Start to create the encrypted disk file.

Figure 15.21. Selecting the options to encrypt the source data into a disk file


After creating the file, go back to the initial page and select Use an existing file and enable decryption as shown in Figure 15.22. Then click Start to perform the decryption.

Figure 15.22. Selecting the options to decrypt the file just created


Once complete, you can open the resulting file, which has been encrypted and then decrypted (see Figure 15.23). If you wish, open the original file (graphic.gif), the encrypted file (graphic-3des.gif), and the decrypted file (graphic-3des-un3des.gif) in the binary editor in Visual Studio (see Figure 15.8 earlier in this chapter) to view the binary content and confirm that encryption took place.

Figure 15.23. Viewing the decrypted image file


Note that the TripleDES process may not work properly on small files, such as the text files generated by the other input options in the example page.




ASP. NET 2.0 Illustrated
ASP.NET 2.0 Illustrated
ISBN: 0321418344
EAN: 2147483647
Year: 2006
Pages: 147

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net