问题描述
||
我使用OpenSSL创建了私钥和公钥对,然后生成了.p12文件,将其导入到Windows certstore中。密钥对和.p12文件是在Windows XP中创建的,我正在尝试在Windows 7中使用它。
我正在尝试从IIS中的Web服务(.svc)内部访问密钥。
如果尝试从独立应用程序读取私钥,则可以毫无问题地进行操作,但是当我尝试从Web应用程序读取私钥时,总是会遇到以下异常:
\'cert.PrivateKey\' threw an exception of type \'System.Security.Cryptography.CryptographicException\'
这是整个堆栈跟踪:
en System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters,Boolean randomKeyContainer)
en System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType,CspParameters parameters,Boolean randomKeyContainer,Int32 dwKeySize,SafeProvHandle& safeProvHandle,SafeKeyHandle& safeKeyHandle)
en System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
en System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize,Boolean useDefaultKeySize)
en System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
en ValidKeyDll.ValidKey.getLlaveDeAlmacen(String almacen,Boolean esllavePrivada) en C:\\Users\\desarrollo\\Documents\\ValidKeyDll\\ValidKeyDll\\ValidKey.cs:línea 58
en ValidKeyDll.ValidKey.firmaCadena(String almacen,String cadenaFirmar) en C:\\Users\\desarrollo\\Documents\\ValidKeyDll\\ValidKeyDll\\ValidKey.cs:línea 117
这是我读取密钥的代码的一部分:
X509Store store = new X509Store(StoreName.My,StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
RSACryptoServiceProvider csp = null;
foreach (X509Certificate2 cert in store.Certificates)
{
if (cert.Subject.Contains(almacen))
{
if (cert.NotAfter.Compareto(System.DateTime.Now) <= 0)
throw new CertificadoVencidoException();
if (isPrivateKey)
csp = (RSACryptoServiceProvider)cert.PrivateKey;
else
csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
break;
}
}
我想它与某种许可问题有关,但我无法查明它是什么...如果有人有任何建议,将不胜感激。
注意事项:
私钥是可导出的。
用户IIS_IUSRS对证书具有权限。
解决方法
我终于解决了这个问题,但是直到现在都无法发布答案(因为我是一个初学者):
问题是我以错误的方式导入了.p12。我双击它并按照步骤进行。这样做是将证书放入“当前用户-个人”证书存储中,所以我认为仅将证书从该存储区移动到“本地计算机”存储中就足够了……但是,噢,令人惊讶!不是。
经过大量修改后,我发现IIS具有从自身内部导入证书的功能,并且将证书直接放入本地计算机证书存储中。
如果有人遇到问题或只是想看看如何做到这一点,请执行以下步骤:
打开IIS。
转到服务器证书(对不起,如果您找不到确切的单词,我的Windows是西班牙语)
选择导入
选择您的文件。如果您的文件是像我的.p12文件,则选择查看*。*
输入密码
接受...然后瞧瞧
, 是的,这是权限问题。我前一段时间对此感到挣扎。当前,我使用winhttpcertcfg添加适当的权限。
您还应该检查此链接:http://benoit808.wordpress.com/2008/10/31/cryptographicexception-the-handle-is-invalid/。
也有关于它的文章http://www.stevefenton.co.uk/Content/Blog/Date/201101/Blog/X509-Certificates-On-Windows-Server-2003/。您可能还需要为IIS_WPG和IUSR帐户添加权限(本文未提及)。