advanced web statistics

Encrypt and Decrypt Passwords using Cryptostream

2/20/2006 12:04:21 PM

I posted these functions to my old blog but they are now inaccessible due to the blog crapping out.  Slowly but surely I will resurrect all of my relevant and interesting code snippets and tutorials.

I used these functions in the creation of my blog engine as well as other content management software (i.e. administrative back-end client websites) to avoid saving plain-text passwords and access codes  in a database or configuration file.  Even if you pass information in the querystring this would be ideal because the visitor wouldn't be able to extrapolate information such as client id, employee number, etc...

using System.Security.Cryptography;

Encryption

protected void EncryptIt(string Password)
{
   byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(Password);
   byte[] rgbKey = System.Text.ASCIIEncoding.ASCII.GetBytes("56565656");
   byte[] rgbIV = System.Text.ASCIIEncoding.ASCII.GetBytes("78787878");

   //1024-bit encryption
   MemoryStream memoryStream = new MemoryStream(1024);
   DESCryptoServiceProvider desCryptoServiceProvider = 

   new DESCryptoServiceProvider();

   CryptoStream cryptoStream = new CryptoStream(memoryStream,
   desCryptoServiceProvider.CreateEncryptor(rgbKey, rgbIV),

   CryptoStreamMode.Write);

   cryptoStream.Write(data, 0, data.Length);
   cryptoStream.FlushFinalBlock();

   byte[] result = new byte[(int)memoryStream.Position];
   memoryStream.Position = 0;
   memoryStream.Read(result, 0, result.Length);

   cryptoStream.Close();

   string toDecrypt = System.Convert.ToBase64String(result);

   DecryptIt(toDecrypt);
}

Decryption

protected void DecryptIt(string toDecrypt)
{
   byte[] data = System.Convert.FromBase64String(toDecrypt);
   byte[] rgbKey = System.Text.ASCIIEncoding.ASCII.GetBytes("56565656");
   byte[] rgbIV = System.Text.ASCIIEncoding.ASCII.GetBytes("78787878");

   MemoryStream memoryStream = new MemoryStream(data.Length);

   DESCryptoServiceProvider desCryptoServiceProvider =

   new DESCryptoServiceProvider();

   CryptoStream cryptoStream = new CryptoStream(memoryStream,
   desCryptoServiceProvider.CreateDecryptor(rgbKey, rgbIV),

   CryptoStreamMode.Read);

   memoryStream.Write(data, 0, data.Length);
   memoryStream.Position = 0;

   string decrypted = new StreamReader(cryptoStream).ReadToEnd();

   cryptoStream.Close();
}

.NET, C#, Code, Security

kick it on DotNetKicks.com

Leave a Comment

   

  Enter the text to proceed!