I created a pair of private and public keys using OpenSSL, and then I generated a .p12 file to import it into my certstore for Windows. The key pairs and .p12 were created in Windows XP, and I am trying to use it in Windows 7. I am trying to access the key from a web service (.svc) in IIS. If I try to read the private key from a standalone application, I can do it without any problems, but when I try to read it from my web application, I always get the following exception:
'cert.PrivateKey' threw an exception of type 'System.Security.Cryptography.CryptographicException'
And this is the whole stack:
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
And this is my part of the code that reads the key:
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; } }
I believe that this is due to some kind of resolution problem, but I do not know what it is ... Please, if anyone has any suggestions, we will be very grateful.
THINGS TO CONSIDER:
- The private key IS is exported.
- User IIS_IUSRS has certificate permissions.
source share