0

In .Net 5/6, I got a RsaCng key in memory, got a certificate back from CA, how can I specify to use the "Microsoft Key Storage Provider" when importing to the Windows certificate store? I currently have the below code and it resulted in the CSP provider "Microsoft Enhanced RSA and AES Cryptographic Provider" once I import it into the certificate store. Setting the ProviderName to "Microsoft Key Storage Provider" gave an error of "The keyset is not defined".

                    var cspParams = new CspParameters
                    {
                        KeyContainerName = Guid.NewGuid().ToString(),
                        KeyNumber = (int)KeyNumber.Exchange,
                        Flags = CspProviderFlags.UseMachineKeyStore
                                | CspProviderFlags.UseNonExportableKey
                                | CspProviderFlags.NoPrompt,
                    };

                    var csp = new RSACryptoServiceProvider(cspParams);
                    csp.ImportParameters(myRsaCngKey.ExportParameters(true));
                    var certWithPrivateKey = cert.CopyWithPrivateKey(csp);
lee23
  • 409
  • 1
  • 3
  • 10
  • When you export the certificate with private key in PFX, Windows API writes provider name as bag attribute in PKCS#12 object. Windows certificate importer reads this attribute and attempts to use same provider. That is, if your PFX was exported from KSP, it will be automatically imported to same provider and no custom code is required. – Crypt32 Sep 21 '22 at 10:46
  • `Microsoft Key Storage Provider` is CNG, not CAPI, you have to switch from RSACryptoServiceProvider to RSACng (which you should really just do, anyways). – bartonjs Sep 21 '22 at 16:02

0 Answers0