Er. alokpandey's Blog

how to generate validationKey and decryption Key for web.config

Posted in ASP.NET (C# & VB), C#, VB, WCF by Alok Kumar Pandey on January 12, 2011

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 web.config file or Machine.config.

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 web.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];

            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"

Note Because the code is using a random number generator, the output is different each time.

Note for Machine.config

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.


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.

12 Responses

Subscribe to comments with RSS.

  1. orthodontist said, on September 13, 2012 at 9:33 am

    You actually make it seem so easy with your presentation but I find this matter
    to be really something that I think I would
    never understand. It seems too complicated and very broad
    for me. I am looking forward for your next post, I will try to get the hang of it!

  2. Alok Kumar Pandey said, on September 13, 2012 at 10:04 am

    Just use sime way, Under normal circumstances, you could use the regular Random class as randomizer, but why not use the more advanced Cryptographic Service Provider, which apparently offers better security?

    The following code creates a byte array of the desired length, fills it in with super-random numbers and then translates the entire array to its hexadecimal string representation byte by byte. You can then take the output of this procedure and paste it into your Web.config.

    System.Security.Cryptography.RNGCryptoServiceProvider cp =
    new System.Security.Cryptography.RNGCryptoServiceProvider();
    // decryptionKey: 48 characters or 24 bytes,
    // validationKey: 128 characters or 64 bytes
    int len = 48;
    byte[] buff = new byte[len / 2]; // each byte translates into two HEX characters

    System.Text.StringBuilder sb = new System.Text.StringBuilder(len);
    foreach (byte b in buff)
    sb.Append(string.Format(“{0:X2}”, b)); // format as HEX character pair
    Response.Write(sb.ToString()); // or Console.WriteLine(sb.ToString());

  3. humidifiers for home said, on September 27, 2012 at 3:15 am

    I do consider all the ideas you’ve introduced to your post. They are very convincing and can definitely work. Still, the posts are too quick for starters. May just you please lengthen them a little from next time? Thank you for the post.

  4. long range rifle scopes said, on September 29, 2012 at 6:14 am

    Amazing things here. I’m very satisfied to peer your article. Thank you a lot and I’m looking ahead to contact you.
    Will you kindly drop me a mail?

  5. using newspaper clippings said, on September 30, 2012 at 2:13 am

    Marvelous, what a weblog it is! This blog presents valuable data to us,
    keep it up.

  6. Pure Leverage said, on April 21, 2013 at 3:06 am

    Because the admin of this site is working, no uncertainty very rapidly it will be renowned,
    due to its feature contents.

  7. nitro radio controlled trucks said, on May 19, 2013 at 1:13 am

    As an added benefit, internet radio offers music at a better quality than
    traditional radio. Unlike broadcast radio which is an audio-only medium, Internet radio stations
    are free to offer interactive programming and can include
    images, animation, and even video. Closed at heels, all the interruptions of RJs too can be kept aside, thanks to odysseystreaming.

  8. Ingeborg said, on May 29, 2013 at 3:22 am

    Hi! Do you use Twitter? I’d like to follow you if that would be okay. I’m undoubtedly enjoying your blog and look
    forward to new posts.

  9. said, on June 20, 2013 at 4:55 am

    After exploring a handful of the blog articles on your web site, I seriously appreciate your way of blogging.
    I book marked it to my bookmark webpage list and will be
    checking back in the near future. Take a look at my web site
    too and let me know your opinion.

  10. Emergency Freeze Dried Food said, on June 28, 2013 at 7:28 am

    Thankfulness to my father who stated to me concerning this weblog, this web site is actually awesome.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: