ASP.NET 2.0+ MachineKey Generator

CSharp · Console

/Program.cs

using System;
using System.Text;
using System.Security.Cryptography;

public class Program
{
	public static void Main()
	{
		var gen = new ASPNETMachineKeyGenerator();

		var validationKey = gen.GenValidationKey();
		var decryptionKey = gen.GenDecryptionKey();

		StringBuilder aspnet20machinekey = new StringBuilder();

		aspnet20machinekey.Append("<machineKey \n");
		aspnet20machinekey.Append("validationKey=\"" + validationKey + "\"\n");
		aspnet20machinekey.Append("decryptionKey=\"" + decryptionKey + "\"\n");
		aspnet20machinekey.Append("validation=\"SHA1\" decryption=\"AES\"\n");
		aspnet20machinekey.Append("/>\n");

		Console.WriteLine(aspnet20machinekey.ToString());
	}
}

// Define other methods and classes here

public class ASPNETMachineKeyGenerator
{
	public string GenValidationKey()
	{
		return getRandomKey(64);
	}

	public string GenDecryptionKey()
	{
		return getRandomKey(32);
	}

	string getRandomKey(int bytelength)
	{
		byte[] buff = new byte[bytelength];
		
		RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
		rng.GetBytes(buff);
		
		StringBuilder sb = new StringBuilder(bytelength * 2);
		
		for (int i = 0; i < buff.Length; i++)
			sb.Append(string.Format("{0:X2}", buff[i]));
		
		return sb.ToString();
	}
}
;