Private Key from PFX File

0 votes
asked Apr 11 by rafael.lasertech (140 points)
edited Apr 11 by rafael.lasertech

Hi,

I'm having an issue while extracting RSA Private Key from a PFX File (3rd line in my code). Currently, I'm running Windows CE 7.0 with .NET Compact Framework 3.5 and a registered version of File Transfer Pack 2016 R2.2. Last line from code is a function I have developed and it works fine. However, I want to keep the PFX file in Certificate Store, so thats the reason I need GetRSAParameters to be working on Rebex Certificate class.

byte[] pfxb = Utilities.ReadAllBytes(@"\SD Card\oi1.pfx");

Certificate pfxCert = Certificate.LoadPfx(pfxb, "rafael", KeySetOptions.PersistKeySet);

RSAParameters privateKey = pfxCert.GetRSAParameters(true, false); // error

//RSAParameters privateKey1 = PFXUtil.GetPrivateKeyFromPFXFile(pfxb, "rafael"); // my functions works fine

Error:

    {Rebex.Security.Certificates.CertificateException: Unable to acquire private key handle for this certificate (80090016).
   at Rebex.Security.Certificates.Certificate.UN(Boolean JK, IntPtr& KK, Int32& YK, Int32& WK)
   at Rebex.Security.Certificates.Certificate.XN(RSAParameters& JK, DSAParameters& KK, Boolean YK)
   at Rebex.Security.Certificates.Certificate.NN(RSAParameters& JK, DSAParameters& KK, Boolean YK)
   at Rebex.Security.Certificates.Certificate.HN(RSAParameters& JK, DSAParameters& KK, Boolean YK)
   at Rebex.Security.Certificates.Certificate.GetRSAParameters(Boolean exportPrivateKeys, Boolean silent)
   at CertificateX509Test.Form1.btnGetCertificates_Click(Object sender, EventArgs e)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.ButtonBase.WnProc(WM wm, Int32 wParam, Int32 lParam)
   at System.Windows.Forms.Control._InternalWnProc(WM wm, Int32 wParam, Int32 lParam)
   at Microsoft.AGL.Forms.EVL.EnterMainLoop(IntPtr hwnMain)
   at System.Windows.Forms.Application.Run(Form fm)
   at CertificateX509Test.Program.Main()
}

Any ideas why I cannot extract private key?

Thanks.

1 Answer

0 votes
answered Apr 12 by Lukas Pokorny (82,430 points)

Hello,

Private keys stored in Windows key storage are either exportable or non-exportable. Both exportable and non-exportable keys can be used through Rebex Certificate class - SignHash/SignMessage/VerifyHash/VerifyMessage methods work. This is how private keys associated with certificates are supposed to be used.

However, you are doing something else - the GetRSAParameters method exports the private RSA parameters from the key storage, which does not work for non-exportable keys.

To make the key exportable, specify KeySetOptions.Exportable option when loading the PFX file:

Certificate pfxCert = Certificate.LoadPfx(pfxb, "rafael", KeySetOptions.PersistKeySet | KeySetOptions.Exportable);
...