Wednesday, March 05, 2008

Intoduction toExtension Method

One of the nice features in 3.5 is Extension Methods. Basically a side effect of LINQ, Extension methods offer the ability to create utility methods that are statically available to all classes. I'm not going to go into detail here, but there is plenty of information available on the net.

One utility class that most developers will have in there virtual rucksack is for Encrypting and Decrypting. In most cases encryption/decryption is done at variable level, for example encrypting/decrypting passwords or logins.

Creating an Extension Method to do this is a simple thing to do.

There are a couple of criteria that an EM must adhere to. Out of the Visual Studio help file : "Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive."

To achieve our goal we will create two EM's. One for encrypting some plain text and one for decrypting an already encrypted value back to plain text.

First we must create a new class. Make sure the class is marked static.

Our encryption EM will take a string parameter and return an array of byte as below:

public static byte[] ToEncryptedValue(this String unEncryptedValue)
{
   return ProtectedData.Protect(Encoding.Default.GetBytes
      (unEncryptedValue), null, DataProtectionScope.LocalMachine);
}

All the hard work of encryption is handled by the ProtectedData class. The DataProtection class is a .NEt wrapper for the Data Protection API (DPAPI). The beauty of using the DPAPI class is it illeviates the neccessity of generating and storing an encryption key, which can be an issue when dealing with security. The protect method takes a string, and a protection scope and returns an encrypted array of bytes.

Conversely, our decryption EM will take an array of bytes and return a string as below:

public static string ToUnEncryptedValue(this byte[] encryptedValue)
{
   return Encoding.Default.GetString(ProtectedData.Unprotect
      (encryptedValue, null, DataProtectionScope.LocalMachine));
}

again we use the ProtectedData class. The only caveat here is the data protection scope must be the same as the encryption scope.

Also, the encryption is tied to a machine. You can't take a password encrypt it on one machine and then try and decrypt it on another machine.

Extension Methods are called like any other class method, except they are called by variables themselves. For example to encrypt a variable called password:

byte[] encrypted = password.ToEncryptedValue();

and coversely to decrypt:

string plainText = encryptedArray.ToUnEncryptedValue();

Easy!

Hopefully from this the potential of extension methods are evident.

No comments: