项目背景: asp.net mvc升级到5.2.0.0,web.config的System.Web設置了machineKey
错误:在cshtml的@Html.AntiForgeryToken()抛出System.Security.Cryptography.CryptographicException异常
解决:重置web.config的静态机器码
参考:http://msdn.microsoft.com/en-us/library/ms998288.aspx
1:使用 RNGCryptoServiceProvider 类创建一个随机秘钥
2:选择一个适当的秘钥大小,如下:
1) SHA1, set the validationKey to 64 bytes (128 hexadecimal characters).
2)AES, set the decryptionKey to 32 bytes (64 hexadecimal characters).
3)3DES, set the decryptionKey to 24 bytes (48 hexadecimal characters).
3:创建一个console application生成key,如下代码:
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);
}
}