Friday, July 2, 2010

Simple Encryption and Decryption

public class EnDC
{

/*
The .net 2.0 framework contains classes for encryption which can be found in the
System.Security.Cryptography namespace. These classes overcomes the complexity of
the encryption as under most scenarios, a developer simply wants a function a clear
text string as a parameter and returns an encrypted string.
The C# code for this function is below
*/

public string EncryptString(string ClearText)
{

byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);

System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();

MemoryStream ms = new MemoryStream();
byte[] rgbIV = Encoding.ASCII.GetBytes("kolpfmckfryjgmkk");
byte[] key = Encoding.ASCII.GetBytes("kokollmnlvita345dfgniskhanmumccc");
CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV),
CryptoStreamMode.Write);

cs.Write(clearTextBytes, 0, clearTextBytes.Length);

cs.Close();

return Convert.ToBase64String(ms.ToArray());
}

/*Following is the code of Decrypting the given string. */

public string DecryptString(string EncryptedText)
{
byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);

MemoryStream ms = new MemoryStream();

System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();


byte[] rgbIV = Encoding.ASCII.GetBytes("kolpfmckfryjgmkk");
byte[] key = Encoding.ASCII.GetBytes("kokollmnlvita345dfgniskhanmumccc");

CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV),
CryptoStreamMode.Write);

cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);

cs.Close();

return Encoding.UTF8.GetString(ms.ToArray());

}

/*Please be sure to replace the encryption keys I provided above with your
own unique values of the same length.
Also, note that the encryption type used above is symmetric t.
If you need an asymmetric or hash
algorithm use the appropriate class within the Cryptography namespace*/
}

No comments:

Post a Comment