Skip to main content

Generate machine keys with F#

If you want to release software often, as scrum advises, you need to take special care about those releases. I had recently a problem where releasing changes to an ASP.NET website would cause it to generate new machine key and invalidating ViewState for all visitors that were using some sort of form on the website. The solution to that is of course specifying the machine key in web.config to make sure that it doesn't change when the application pool refreshes.

let gen len =
    let provider = new System.Security.Cryptography.RNGCryptoServiceProvider()
    let out : byte array = Array.zeroCreate (len / 2)
    out |> (fun b -> System.String.Format("{0:X2}", b)) |> System.String.Concat

This is how I use F# to generate the keys.

type MachineKey = { sha1 : string; aes : string; _3des : string }
let machineKey = { sha1 = (gen 128); aes = (gen 64); _3des = (gen 48) } 

printfn "<machineKey validationKey=&quot;%s&quot; decryptionKey=&quot;%s&quot; validation=&quot;SHA1&quot; decryption=&quot;AES&quot; />" machineKey.sha1 machineKey.aes

And the result is...

 decryption="AES" />

Dump this in your web.config and you're good to go. Just don't forget to encrypt the configuration file before deployment to avoid the keys getting in the wrong hands.

comments powered by Disqus