I recently created an ASP.NET application which used Forms Authentication. In the interests of security I configured the machinekey properties of the web.config file. An explanation of the machinekey including its purpose and how to generate the keys is explained in this past Microsoft article. The article explains to create cryptographically random keys you use the System.Security.Cryptography.RNGCryptoServiceProvider class.
You use different length keys for different types of encryption.
- For SHA1, set the validationKey to 64 bytes (128 hexadecimal characters).
- For AES, set the decryptionKey to 32 bytes (64 hexadecimal characters).
- For 3DES, set the decryptionKey to 24 bytes (48 hexadecimal characters).
Example code for generating keys is shown below;
Example in C#
using System; using System.Text; using System.Security; using System.Security.Cryptography; class App { static void Main(string[] argv) { int len = 128; if (argv.Length > 0) len = int.Parse(argv[0]); byte[] buff = new byte[len/2]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(buff); StringBuilder sb = new StringBuilder(len); for (int i=0; i<buff.Length; i++) sb.Append(string.Format("{0:X2}", buff[i])); Console.WriteLine(sb); } }
Example in VB.NET
Imports System Imports System.Text Imports System.Security Imports System.Security.Cryptography Module App Sub Main(ByVal argv() As String) Dim len As Integer = 128 If argv.Length > 0 Then len = Integer.Parse(argv(0)) End If Dim buff(len / 2) As Byte Dim rng As New RNGCryptoServiceProvider() rng.GetBytes(buff) Dim sb As New StringBuilder(len) Dim i As Integer For i = 0 To buff.Length - 1 sb.Append(String.Format("{0:X2}", buff(i))) Next i Console.WriteLine(sb) Console.ReadLine() End Sub 'Main End Module
I have taken this code and created a more user friendly, though still pretty basic windows application.
A copy of the code can be downloaded from MachineKeyGenerator repository on Github.
You must be logged in to post a comment.