我有一些文件,我想用自己在 ASP:NET 中的证书进行数字签名。在 3.5 .NET(中等信任)中,我设法做到了这一点,但是当以中等信任切换到 .NET 4.0 时,我遇到了 System.Security 异常:
System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.KeyContainerPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.CodeAccessSecurityEngine.Check(CodeAccessPermission cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Demand()
at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
我的代码是:
X509Certificate2 certificate = null;
try
{
certificate = new X509Certificate2(AppDomain.CurrentDomain.BaseDirectory + licenceFile, licenceFilePass, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
if (certificate == null)
throw new Exception("The certificate is null!!!");
}
catch (Exception ex)
{
exception += "X509Certificate2 fail! Did not get certificate " + AppDomain.CurrentDomain.BaseDirectory + licenceFile;
exception += FormatException(ex);
goto SetError;
}
RSACryptoServiceProvider myRSASigner = null;
try
{
myRSASigner = (RSACryptoServiceProvider)certificate.PrivateKey;
if (myRSASigner == null)
{
throw new Exception("No valid cert was found");
}
doc = SignXmlFile(doc, myRSASigner);
catch (Exception ex)
{
exception += "SignXmlFile failed";
exception += FormatException(ex);
goto SetError;
}
当我尝试提取我自己本地存储的许可证文件的 PrivateKey 时发生错误:
myRSASigner = (RSACryptoServiceProvider)certificate.PrivateKey;
我知道我缺少 KeyContainerPermission,但是对于我自己的证书?不幸的是,我也用另一个证书解密,当然会出现同样的问题....
我无法提高信任级别,因为该网站位于托管服务器上。我也怀疑我能否说服我的提供商在 GAC 中安装我自己的程序集来执行此操作......