ÜberUtils - Part 2 : Cryptography (continued)

ÜberUtils Series posts so far :

I am now going to finish off the cryptography part of my ÜberUtils project. If you don't know about it, check it out. In the first article I released the hashing class. This post I am going to run through the Encryption class. The Encryption class is pretty straight forward and basically wraps the System.Security.Cryptography symmetric encryption classes. Here are the types of encryption available (this is exposed as an enum):

public enum EncryptionTypes
{
DES,
RC2,
Rijndael,
TripleDES
}

A simple example demostrates the ease of use :

Encryption target = new Encryption();
string inputText = "Thi$ is @ str!&n to tEst encrypti0n!";
string output = target.Encrypt(inputText);

You can also call a static method to make it even easier :

string strCiperText = Encryption.EncryptText("hello world!");

You can also as easily change the encryption algorithm, the password key or the salt. I am not going to write an article explaining how encryption works and what the different components are. If you are interested, check out this nice article I found on the subject.

You guessed it, it is as simple to decrypt too :

string strOriginal = Encryption.DecryptText(strEncryptedText);

Here is the class diagram :

 

Like the hashing class, the encryption class also uses some extension methods. Please note : extension methods should only be used when extending functionality of an existing class in a reusable fashion. Don't create an extension method just because you can, create one when you see yourself using the method over and over again in many places. This is my reasoning behind creating these extension methods. I feel they will be reused again in the future and it makes my life as a developer easier. Here they are :

        public static string ToBase64String(this byte[] data)
{
return Convert.ToBase64String(data);
}

public static string ToUTF8String(this byte[] data)
{
return new UTF8Encoding().GetString(data);
}

public static byte[] ToByteArrayUTF8(this string str)
{
return new UTF8Encoding().GetBytes(str);
}

public static byte[] ToByteArrayBase64(this string str)
{
return Convert.FromBase64String(str);
}

 So thats the encryption class. Included in the source, we again add unit tests for encryption. Download the source here. Enjoy.

No Comments