Friday, October 01, 2010

Generate machineKey for your web.config in .NET

Hi All,

We were implemeneting Single Sign-On for our enterprise ASP.NET applications, I have been asked: How can we generate our own machine keys in our web.config ? Here is the console application you need to run and to get a random key based on the length you need and then add it to your web.config.

C# Code:

static void Main(string[] keyLength)

int len = 128;
if (keyLength.Length > 0)
len = int.Parse(keyLength[0]);
byte[] buff = new byte[len / 2];
RNGCryptoServiceProvider rng = new
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < buff.Length; i++)
sb.Append(string.Format("{0:X2}", buff[i]));


If you didn't pass anything to this method will generate 128 character key (64 byte), If you want to get 32 byte key, you need to pass 64 as key length input.

If you are trying different cryptography algorithms provided by System.Cryptography namespace in .NET Framework so here is the reference you need to read for what is the required length for each algorithm ? either if you are using: DES,3DES,AES,SHA1...etc.

Hope this helps.

Regards,Mostafa Arafa

No comments: