Monday, October 19, 2009

Encrypt Querystring

using System;
using System.Collections.Specialized;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace infoExpediters
{
public class SecureQueryString : NameValueCollection

{

public SecureQueryString() : base() { }
//public DateTime dtt;
public SecureQueryString(string encryptedString)
{
deserialize(decrypt(encryptedString));

// Compare the Expiration Time with the current Time to ensure
// that the queryString has not expired.

dtt=ExpireTime;

if (DateTime.Compare(ExpireTime, DateTime.Now) < 0) { throw new ExpiredQueryStringException(); } } ///
/// Returns the encrypted query string.
///

public string EncryptedString
{
get
{
return HttpUtility.UrlEncode(encrypt(serialize()));
}
}
private DateTime _expireTime DateTime.MaxValue;//Convert.ToDateTime("8 PM");
// ///
// /// The timestamp in which the EncryptedString should expire
///

public DateTime ExpireTime
{
get
{
return _expireTime;
}
set
{
_expireTime = value;
}
}
//Commented by Rahul end
///
/// Returns the EncryptedString property.
///

public override string ToString()
{
return EncryptedString;
}

///
/// Encrypts a serialized query string
///

public string encrypt(string serializedQueryString)
{
byte[] buffer = Encoding.ASCII.GetBytes(serializedQueryString);
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));
des.IV = IV;
return Convert.ToBase64String(
des.CreateEncryptor().TransformFinalBlock(
buffer,
0,
buffer.Length
)
);
}

///
/// Decrypts a serialized query string
///

public string decrypt(string encryptedQueryString)
{
try
{
byte[] buffer = Convert.FromBase64String(encryptedQueryString);
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
des.Key = MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(cryptoKey));
des.IV = IV;
return Encoding.ASCII.GetString(
des.CreateDecryptor().TransformFinalBlock(
buffer,
0,
buffer.Length
)
);
}
catch (CryptographicException)
{
throw new InvalidQueryStringException();
}
catch (FormatException)
{
throw new InvalidQueryStringException();
}
}

///
/// Deserializes a decrypted query string and stores it
/// as name/value pairs.
///

private void deserialize(string decryptedQueryString)
{
string[] nameValuePairs = decryptedQueryString.Split('&');
for (int i = 0; i < nameValuePairs.Length; i++) { string[] nameValue = nameValuePairs[i].Split('='); if (nameValue.Length == 2) { base.Add(nameValue[0], nameValue[1]); } } // Ensure that timeStampKey exists and update the expiration time. Commented by Rahul if (base[timeStampKey] != null) _expireTime = DateTime.Parse(base[timeStampKey]); } ///
/// Serializes the underlying NameValueCollection as a QueryString
///

public string serialize()
{
StringBuilder sb = new StringBuilder();
foreach (string key in base.AllKeys)
{
sb.Append(key);
sb.Append('=');
sb.Append(base[key]);
sb.Append('&');
}

// Append timestamp


sb.Append(timeStampKey);
sb.Append('=');
sb.Append("12/31/9999 11:59:59 PM");//.ToString().Substring(0,_expireTime.Length-2)("08/09/2004 11:10:10 //PM")_expireTime;



return sb.ToString();
}
private const string timeStampKey = "__TimeStamp__";

// The key used for generating the encrypted string
private const string cryptoKey = "ChangeThis!";

// The Initialization Vector for the DES encryption routine
private readonly byte[] IV = new byte[8] { 240, 3, 45, 29, 0, 76, 173, 59 };


}
}

Thursday, October 8, 2009

C# Readonly List

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ListReadOnly
{
class Program
{
static void Main(string[] args)
{
Patterns p = new Patterns();
IList lstAlphabets = p.GetAlphabetList();
p.AddAlphabetToList("D");
foreach (string s in lstAlphabets)
{
Console.WriteLine(s);
}
try
{
foreach (string s in lstAlphabets)
{
//This line of code should throw error.
lstAlphabets.Add("P");
Console.WriteLine(s);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
class Patterns
{
List m_lNames = new List { "A", "B", "C" };
public IList GetAlphabetList()
{
return m_lNames.AsReadOnly();
}
public void AddAlphabetToList(string s)
{
m_lNames.Add(s);
}
}
}

Output: