ENTERPRISE

Microsoft Enterprise Library : Relieving Cryptography Complexity - Diving in with an Example (part 1) - Encrypting and Decrypting Data Using A Symmetric Provider

1/29/2015 3:27:05 AM

You can run this directly from the bin\debug folder, or open the solution named Cryptography in Microsoft® Visual Studio® to see all of the code as you run the examples.

Note

Before you attempt to run the example, you must create new encryption keys for the block to use to encrypt the data when using a symmetric encryption provider. This is because the key is tied to either the user or the machine, and so the key included in the sample files will not work on your machine. In the configuration console, select the AesManaged symmetric provider, and click the "…" button in the Key property to start the Key wizard. Use this wizard to generate a new key, save the key file, and automatically update the content of App.config. Then repeat this procedure for the RijndaelManager symmetric provider. Rijndael is an implementation of the AES algorithm. However, we will demonstrate both as we show you how to encrypt and decrypt both value types and objects.

Encrypting and Decrypting Data Using A Symmetric Provider

To encrypt and decrypt information, you use a symmetric encryption provider. As you saw earlier, the Cryptography block includes several symmetric encryption providers. The examples we provide use two of these: the AES managed symmetric algorithm provider and the Rijndael managed symmetric algorithm provider. The examples demonstrate how to use these providers to encrypt both a text string and an object (in our example this is a simple class named Product), and how to decrypt the encrypted item.

The Cryptography Manager exposes two methods for working with symmetric encryption providers:

  • The EncryptSymmetric method takes as parameters the name of a symmetric provider configured in the Cryptography block for the application, and the item to encrypt. There are two overloads of this method. One accepts a string and returns a base-64 encoded string containing the encrypted text. The second overload accepts the data to encrypt as a byte array, and returns a byte array containing the encrypted data.

  • The DecryptSymmetric method takes as parameters the name of a symmetric provider configured in the Cryptography block for the application, and the item to decrypt. There are two overloads of this method. One accepts a base-64 encoded string containing the encrypted text and returns the decrypted text. The second overload accepts a byte array containing the encrypted data and returns a byte array containing the decrypted item.

Encrypting and Decrypting a Text String

The first example, Encrypt and Decrypt a Text String using a Symmetric Algorithm, uses the AES managed symmetric algorithm provider to encrypt and decrypt a text string.

The code shown below creates a text string and then calls the EncryptSymmetric method of the Cryptography Manager, passing to it the name of the AES managed symmetric algorithm provider defined in the configuration of the application, and the text string to encrypt. To decrypt the resulting string, the code then calls the Decrypt Symmetric method of the Cryptography Manager, passing to it (as before) the name of the AES managed symmetric algorithm provider defined in the configuration of the application, and the encrypted base-64 encoded string. We've removed some of the lines of code that simply write values to the console screen to make it easier to see the code that actually does the work.

// Define the text string instance to encrypt.string sampleText = "This is some text to encrypt.";// Use the AES Symmetric Algorithm Provider.// The overload of the EncryptSymmetric method that takes a// string returns the result as a Base-64 encoded string.string encrypted = defaultCrypto.EncryptSymmetric("AesManaged", sampleText);// Now decrypt the result string.string decrypted = defaultCrypto.DecryptSymmetric("AesManaged", encrypted);// Destroy any in-memory variables that hold sensitive information.encrypted = null;decrypted = null;

Notice that the last lines of the code destroy the in-memory values that hold the sensitive information used in the code. This is good practice as it prevents any leakage of this information should an error occur elsewhere in the application, and prevents any attacker from being able to dump the memory contents and view the information. If you store data in a string, set it to null, allowing the garbage collector to remove it from memory during its next run cycle. If you use an array, call the static Array.Clear method (passing in the array you used) to remove the contents after use.

Note

You may also consider storing values in memory using the SecureString class, which is part of the Microsoft .NET Framework. However, in the current release of Enterprise Library, the methods of the Security block do not accept or return SecureString instances, and so you must translate them into strings when interacting with the block methods. 

When you run this example, you'll see the output shown below. You can see the value of the original string, the base-64 encoded encrypted data, and the result after decrypting this value.

Text to encrypt is 'This is some text to encrypt.'Encrypted and Base-64 Encoded result is '+o3zulnEOeggpIqUeiHRD2ID4E85TSPxCjS/D6kII4CUCjedFvlNOXjrqjna7ZWWbJp5yfyh/VrHw7oQPzUtUaxlXNdyiqSvDGcU814NNq4='Decrypted string is 'This is some text to encrypt.'

Encrypting and Decrypting an Object Instance

The second example, Encrypt and Decrypt Data using a Symmetric Algorithm, uses the Rijndael managed symmetric algorithm provider to encrypt and decrypt an instance of the Product class defined within the example project.

The code shown below first creates a new instance of the Product class. We need to pass this to the EncryptSymmetric method of the Cryptography Manager, along with the name of the Rijndael managed symmetric algorithm provider defined in the configuration of the application, as an array of bytes. The easiest way to perform the conversion to a byte array is to take advantage of the SerializationUtility class in the Caching block. This class exposes two methods: ToBytes and ToObject. We use the ToBytes method to convert the Product instance into a byte array before passing it the EncryptSymmetric method.

Then the code decrypts the resulting byte array using the DecryptSymmetric method of the Cryptography Manager, passing to it (as before) the name of the Rijndael managed symmetric algorithm provider defined in the configuration of the application, and the encrypted byte array. The ToObject method of the SerializationUtility class then converts this back into an instance of the Product class. Again, we've removed some of the lines of code that simply write values to the console screen to make it easier to see the code that actually does the work.

// Create the object instance to encrypt.Product sampleObject = new Product(42, "Fun Thing",                                   "Something to keep the grandchildren quiet.");// Use the Rijndael Symmetric Algorithm Provider.// Must serialize the object to a byte array first. One easy way is to use// the methods of the SerializationUtility class from the Caching block.byte[] serializedObject = SerializationUtility.ToBytes(sampleObject);// The overload of the EncryptSymmetric method that takes a// byte array returns the result as a byte array.byte[] encrypted = defaultCrypto.EncryptSymmetric("RijndaelManaged",                                                  serializedObject);// Now decrypt the result byte array and de-serialize the// result to get the original object.byte[] decrypted = defaultCrypto.DecryptSymmetric("RijndaelManaged", encrypted);Product decryptedObject = (Product) SerializationUtility.ToObject(decrypted);// Destroy any in-memory variables that hold sensitive information.Array.Clear(encrypted, 0, encrypted.Length);Array.Clear(decrypted, 0, decrypted.Length);Array.Clear(serializedObject, 0, serializedObject.Length);decryptedObject = null;

If you run this example, you'll see the output shown below. You can see the value of the properties of the Product class we created, the encrypted data (we base-64 encoded it for display), and the result after decrypting this data.

Object to encrypt is 'CryptographyExample.Product' - Product.ID = 42 - Product.Name = Fun Thing - Product.Description = Something to keep the grandchildren quiet.Encrypted result is 'System.Byte[]'Contents (when Base-64 encoded for display) are:OEnp9yOP6LInmsfFDaGfVR7RJbwU4/TQskYtIPsqXKcx4UhxMctzBPWXuUX8Q+RgKqYdGAZVVbSCR2VxyTmSDdYQNdiSohA5Fo6bWOqhOR5V0uxdcfNUgKhUhuIAhl5RZ8W5WD8M2CdMiqG1gPgQjJC2afwf1mJnF/4ZB/oD9QcCyQf5d5F1Ww==Decrypted object is 'CryptographyExample.Product' - Product.ID = 42 - Product.Name = Fun Thing - Product.Description = Something to keep the grandchildren quiet.
Other  
  •  Microsoft Enterprise Library : Relieving Cryptography Complexity - How Do I Use the Cryptography Block?
  •  Microsoft Enterprise Library : Relieving Cryptography Complexity - What Does the Cryptography Block Do?
  •  Review : Aztech FG7008GR(AC) 2400Mbps Gigabit Router
  •  Using Exchange Server 2010 Antispam Tools (part 6) - Sender Reputation
  •  Using Exchange Server 2010 Antispam Tools (part 5) - Sender Filtering, Sender ID
  •  Using Exchange Server 2010 Antispam Tools (part 4) - IP Block and Allow Lists, Recipient Filtering , Tarpitting
  •  Using Exchange Server 2010 Antispam Tools (part 3) - IP Block and IP Allow Providers
  •  Using Exchange Server 2010 Antispam Tools (part 2) - Content Filtering
  •  Using Exchange Server 2010 Antispam Tools (part 1) - Enabling Antispam Agents for Hub Transport Servers , Enabling Automatic Updates for the Antispam Signatures
  •  Exchange Server 2007 Management and Maintenance Practices : Postmaintenance Procedures, Reducing Management and Maintenance Efforts
  •  
    Top 10
    Free Mobile And Desktop Apps For Accessing Restricted Websites
    MASERATI QUATTROPORTE; DIESEL : Lure of Italian limos
    TOYOTA CAMRY 2; 2.5 : Camry now more comely
    KIA SORENTO 2.2CRDi : Fuel-sipping slugger
    How To Setup, Password Protect & Encrypt Wireless Internet Connection
    Emulate And Run iPad Apps On Windows, Mac OS X & Linux With iPadian
    Backup & Restore Game Progress From Any Game With SaveGameProgress
    Generate A Facebook Timeline Cover Using A Free App
    New App for Women ‘Remix’ Offers Fashion Advice & Style Tips
    SG50 Ferrari F12berlinetta : Prancing Horse for Lion City's 50th
    Popular Tags
    Video Tutorail Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Exchange Server Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe Photoshop CorelDRAW X5 CorelDraw 10 windows Phone 7 windows Phone 8 Iphone