public static string CreateMachineKey(int length)
{
// Create a byte array.
byte[] random = new byte[length/2];
// Create a cryptographically strong random number generator.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
// Fill the byte array with random bytes.
rng.GetBytes(random);
// Create a StringBuilder to hold the result once it is
// converted to hexadecimal format.
CHAPTER 5 ■ ASP.NET APPLICATIONS 161
System.Text.StringBuilder machineKey = new
System.Text.StringBuilder(length);
// Loop through the random byte array and append each value
// to the StringBuilder.
for (int i = 0; i < random.Length; i++)
{
machineKey.Append(String.Format("{0:X2}", random[i]));
}
return machineKey.ToString();
}
You can use this function in a web form to create the keys you need. For example, the following
snippet of code creates a 48-character decryption key and a 128-character validation key, and it displays
the values in two separate text boxes:
txtDecryptionKey.Text = CreateMachineKey(48);
txtValidationKey.Text = CreateMachineKey(128);
You can then copy the information and paste it into the machine.config file for each computer
in the web farm. This is a much more convenient and secure approach than creating keys by hand.