在中等信任.NET 4.0中使用非对称密钥进行数字签名/解密

时间:2013-03-07 17:11:44

标签: asp.net asp.net-4.0 digital-signature medium-trust

我有一些文件,我想用自己的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中安装我自己的程序集来执行此操作...

0 个答案:

没有答案