我使用 OpenSSL 创建了一个私钥和公钥对,然后生成了一个 .p12 文件以将其导入我的 Windows certstore。密钥对和 .p12 文件是在 Windows XP 中创建的,我正在尝试在 Windows 7 中使用它。我正在尝试从 IIS 中的 Web 服务 (.svc) 中访问密钥。如果我尝试从独立应用程序中读取私钥,我可以毫无问题地做到这一点,但是当我尝试从我的网络应用程序中读取它时,我总是会遇到以下异常:
'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, CspParameters parameters, 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 对证书具有权限。