Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

How to create keys by using Visual C# .NET for use in Forms authentication


View products that this article applies to.

Summary

This article describes how to create keys to use for encryption, decryption, and validation of Forms authentication cookie data. You can use the keys that you create in this article for the validationKey and decryptionKey attributes of the <machineKey> section in the <system.web> element in the Machine.config file.


Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Windows 2000 or Microsoft Windows XP
  • Microsoft .NET Framework
  • Microsoft Internet Information Services (IIS)

Create the project

Create a Visual C# .NET console application:
  1. Start Visual Studio .NET.
  2. On File menu, point to New, and then click Project.
  3. Under Project Types, click Visual C# Projects.
  4. Under Templates, click Console application.
  5. Name the project HashConfigCs.
  6. Click OK.

Write the code to generate the keys

The following code reads two arguments that are passed from the command line:
  • The first argument is the number of bytes that is used to create the decryptionKey attribute.
  • The second argument is the number of bytes that is used to create the validationKey attribute.
The code uses a random number generator to create a random number of bytes based on the command-line arguments. After the random bytes are created, the bytes are formatted into a hexadecimal string that is suitable for use in the .config files.

Note The hexadecimal string that is created is twice the size of the value that is passed on the command line. For example, if you specify 24 bytes for a key, the resulting string is 48 bytes in length after the conversion. The valid values for decryptionKey is 8 or 24. This creates a 16 byte key for Data Encryption Standard (DES) or a 48 byte key for Triple DES, respectively. Valid values for validationKey are 20 to 64. This creates keys from 40 to 128 bytes in length. The output from the code is an entire <machineKey> element that you can copy and paste into a Machine.config file.

Add the following code to a .cs file:
using System;
using System.Text;
using System.Security.Cryptography;

namespace Crypto
{
    public class KeyCreator
    {
        public static void Main(String[] args)
        {			
            String[] commandLineArgs = System.Environment.GetCommandLineArgs();
            string decryptionKey = CreateKey(System.Convert.ToInt32(commandLineArgs[1]));
            string validationKey = CreateKey(System.Convert.ToInt32(commandLineArgs[2]));

            Console.WriteLine("<machineKey validationKey=\"{0}\" decryptionKey=\"{1}\" validation=\"SHA1\"/>", validationKey, decryptionKey);
        }	

        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();
        }
    }
}
				

Generate the hashes

Now you can compile the application.

Run the application from a command prompt by passing in two integer values that are the size of the decryption and the validation keys. For example, if you named the console application HashConfigCs.exe, type the following syntax from the command line in the Bin\debug directory of the application:
hashconfigcs.exe 24 64
You can expect the application to return output that is similar to the following output:
<machineKey validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D7AD972A119482D15A4127461DB1DC347C1A63AE5F1CCFAACFF1B72A7F0A281B"
            decryptionKey="261F793EB53B761503AC445E0CA28DA44AA9B3CF06263B77"
            validation="SHA1"/>
					
Note Because the code is using a random number generator, the output is different each time.


Update the configuration file

  1. Locate the Machine.config file.
  2. Locate the <system.web> section in the configuration file.
  3. Replace the <machineKey> section with the output from the console application. If the <machineKey> section does not exist, create it.
  4. Save the configuration file.
  5. Restart IIS on all servers in the Web farm for the Machine.config changes to take effect.

Troubleshooting

Make sure that the <machineKey> section has identical, explicit keys (that is, do not use the AutoGenerate option for attributes in the <machineKey> section) across the Web farm in the following scenarios:
  • When you use Forms authentication.
  • When you run session state in StateServer mode.
  • When you want ViewState to be available across a Web farm because the enableViewStateMAC attribute is set to True by default.

More information

The machineKey section should be the same across the web farm in the following cases:
  • When using Forms Authentication.
  • When you run session state in StateServer mode.
  • When you want viewstate to be available across a web farm since enableViewStateMac is turned on by default.

↑ Back to the top


References

For additional information, click the following article numbers to view the articles in the Microsoft Knowledge Base:
301240 How to implement forms-based authentication in your ASP.NET application by using C# .NET
311495 How to implement role-based security with forms-based authentication in your ASP.NET application by using Visual C# .NET
306590 INFO: ASP.NET security overview
307626 INFO: ASP.NET configuration overview

↑ Back to the top


Keywords: KB312906, kbstate, kbsecurity, kbhowtomaster, kbconfig

↑ Back to the top

Article Info
Article ID : 312906
Revision : 13
Created on : 7/11/2005
Published on : 7/11/2005
Exists online : False
Views : 819