Machine Key Creator

Every time I need to create a machine name to be use for Session State Service or other services in ASP.NET I need to find out how to do it, you can find many applications and code out there, however let me make it easy and post the class you need to create a Machine name.

public class KeyCreator
    {
        public string GetXmlKey(string desKey, string valiKey)
        {          
            string decryptionKey = CreateKey(System.Convert.ToInt32(desKey));
            string validationKey = CreateKey(System.Convert.ToInt32(valiKey));

            return "<machineKey validationKey=\""+ validationKey +"\" decryptionKey=\"" + descryptionKey + "\" validation=\"SHA1\"/>";
        }

        static String CreateKey(int numBytes)
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[numBytes];

            rng.GetBytes(buff);
            return BytesToHexString(buff);
        }

        static String BytesToHexString(byte[] bytes)
        {
            StringBuilder hexString = new StringBuilder(64);

            for (int counter = 0; counter < bytes.Length; counter++)
            {
                hexString.Append(String.Format("{0:X2}", bytes[counter]));
            }
            return hexString.ToString();
        }
    }

Hope this helps.

Cheers

Al

Published Monday, January 28, 2008 11:23 PM by albertpascual
Filed under: , , ,

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)