Tuesday, December 4, 2007

WebResource.axd error: Padding is invalid and cannot be removed.

If you are experiencing the error detailed here, but you are running a web garden, not a web farm, the query string parameters of your WebResource.axd requests are not being properly decrypted. The root cause is that a different decryption key is being created for each of the processes in your web garden.

To fix this problem, you have to explicitly set a machineKey element in your web.config:


See this article on web deployment considerations for more information.

You may also have seen this error manifest as wierd Javascript errors when you increased the number of worker processes.

You will need to restart IIS for this to take effect, it seems.

Here's a Powershell script to generate a key. Place this in a .ps1 file. Keep in mind, the validation is done with a hash, and so can use SHA1 with a 128-bit key, but decryption is done with a reversible encryption algorithm so the key should probably be 64-bit with AES (Rijndael).

$len = 128

if($args[0] > 0)
$len = $args[0]

[byte[]] $buff = new byte[] ($len/2)

$rng = new System.Security.Cryptography.RNGCryptoServiceProvider


$sb = new System.Text.StringBuilder $len

for ($i = 0; $i -lt $buff.Length; $i += 1)
$junk = $sb.Append([System.String]::Format("{0:X2}", $buff[$i]));