Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Security.Cryptography.CryptographicException: Keyset does not exist thrown within Visual studio

Good day

I am having serious issues trying to assign a private key due to this error.

System.Security.Cryptography.CryptographicException: Keyset does not exist

var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);

var col = store.Certificates.Find(X509FindType.FindBySerialNumber, "00873476DC47C5BB614EA96F2A9CE744A6", false);
var cert = col[0];
var xmlUnSignedSaml = new XmlDocument();
xmlUnSignedSaml.LoadXml(assertion);
xmlUnSignedSaml.PreserveWhitespace = true;
SignedXml signedXml = new SignedXml(xmlUnSignedSaml);

signedXml.SigningKey = cert.PrivateKey; //<<<--- Exception thrown.

I have verified the following:

  1. The certificate HAS a private key.
  2. Read Permissions on the certificate is granted to IUSR, NETWORK SERVICE, LOCAL SERVICE and the local user context on the MMC Console. The certificate is in the localMachine - Personal folder
  3. Same Read permissions are given to the machinekeys folder at “C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys”.

I have checked the answers at the following pages, but absolutely none of them worked for me:

  • Stack Overflow User @blowdart's answer
  • MSDN Answer
  • Other sites, but that had to do with setting up IIS and getting certificates to work there

I am running the application from within Visual Studio, and at the code segment above, it throws the exception trying to set the SignedXml's SigningKey

What else can I do to get this up and running? (Afterthought, I have also tried the "Everyone" permission on the cert and folder - even that threw the same exception)

like image 688
Eon Avatar asked Oct 01 '22 06:10

Eon


1 Answers

I have solved my issue using the following steps:

  1. Downloaded the WCF_Samples from Microsoft to gain access to the FindPrivateKey - 15.5mb in size solution.
  2. Extracted the zip file
  3. Navigated to WCF_Samples\WCF\Setup\FindPrivateKey\CS\FindPrivateKey.sln and Built it.ctrl+shift+B.
  4. Added the following line of code in the Main(string args[]) Method Because I am lazy and don't want to do it through the console: args = new string[] { "My", "LocalMachine", "-t", THUMBPRINT_OBTAINED_IN_MMC, "-a" };
  5. Ran the application. I found the path to the key and navigated to it. It turns out that the permissions on the key itself was NOT SET

I changed the permissions on the key itself, and my application started working.

like image 195
Eon Avatar answered Oct 06 '22 18:10

Eon