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)
    provider.GetBytes(out)
    out |> Seq.map (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...

<machineKey
 validationKey="E2063661CB8652441A7B687309A5F688C95CFC71513334CBE4CE8AE7F73404C468B784EA7A1BFDECD514572D4330383879A4AE418119B65C9755A30D0208FC8A"
 decryptionKey="1047AF920BE7770803DF9ECBDC1FDB73F3AF0C8D9F71C1C8E0D7B8260AFE607D"
 validation="SHA1"
 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