Download source code - 2.8 Kb
The question you are most probably asking: why another Crypto class? Well, I found many articles, examples and documentation on encryption and decryption, but they were not exactly what I was looking for.
For example, there was lots of the same code in different areas: most of them used only 1 type of encryption and most were encypting to and from byte arrays and I wanted to work in strings only.
So, I put all the knowledge I had gained into creating very simple-to-use classes to encypt, decrypt and hash strings. I also tried to create classes that had no code duplication at all, so if things change, then only 1 correction/update is needed. I also found problems in converting byte arrays to strings and back again. I went through all the possibilites, and eventually came up with the best way to do it - that works every time with all characters etc.
Summary of code (what does the code do?)
The file Crypto.cs contains 2 classes. The first one is the class
Crypto and is used for symmetric encryption/decryption. It contains an enum so that you can use the different symmetric algorithms available:
public enum CryptoTypes
encTypeDES = 0,
The other is called
Hashing and is used for oneway hashing. It also contains an enum for the different types of hashing available :
public enum HashingTypes
SHA, SHA256, SHA384, SHA512, MD5
The code references the NUnit library, which is used to do perform simple unit testing. You can download the NUnit libray from http://www.nunit.org/.
How to use the code
Its easy! Add the file crypto.cs to you project, add a reference:
using Utils; and fire away! The code is self explanatory and is well documented. The NUnit test also contains good examples:
string input = "Thi$ is @ str!&n to tEst encrypti0n!";
Crypto c = new Crypto(Utils.Crypto.CryptoTypes.encTypeTripleDES);
string s1 = c.Encrypt(input);
string s2 = c.Decrypt(s1);
Assert.IsTrue(s2 == input);
s1 = Hashing.Hash(input);
s2 = Hashing.Hash(input,Utils.Hashing.HashingTypes.MD5);
Assert.IsTrue(s1 == s2);
s1 = Hashing.Hash(input,Utils.Hashing.HashingTypes.SHA512);
As you can see from the above code, the
Hashing class contains only static methods, so no need to instantiate. You can also create your own utils class that has static methods for symmetric encryption/decryption.
Hope this helps.