Pkcs11Interop / Pkcs11Interop.X509Store

Easy to use PKCS#11 based X.509 certificate store
Apache License 2.0
32 stars 18 forks source link

Unable to get private key from Luna HSM via X509Store #24

Closed rcohnuil closed 2 years ago

rcohnuil commented 2 years ago

Hi,

I need to use a RA certificate stored in a Luna HSM to add 2nd signature and the RA cert to CSRs generated from a client app.

After running OpenSSL commands to process the RA cert in .pfx format, I got the private key in PKCS8 format, then imported both the RA cert and private key into the HSM.

Using the X509CertificateParser, X509Certificate, AsymmetricKeyParameter and RsaKeyParameter from BouncyCastle, I derived the public key.

I did look at https://github.com/Pkcs11Interop/Pkcs11Interop.X509Store/issues/1 and double checked that CKA_LABEL and CKA_ID have the same values for all 3 objects (private key, public key and certificate). In Pkcs11Admin, I did see all 3 objects after I logged into my HSM via menu Token > Login > User login.

Next , I tried the following code with a Luna HSM...

var store = new Pkcs11X509Store(LunaHsmManager.LibraryPath, LunaHsmManager.PinProvider); Pkcs11X509Certificate cert = store.Slots[0].Token.Certificates[0];

I was able to retrieve the cert and public key. The cert.Info.KeyType value is RSA, but cert.HasPrivateKeyObject still shows FALSE.

What am I missing?

Thanks

jariq commented 2 years ago
cert.GetRSAPrivateKey();
rcohnuil commented 2 years ago

I did check cert.GetRSAPrivateKey() but it returned null

jariq commented 2 years ago

No idea then 🤷🏻‍♂️ But Pkcs11Interop.X509Store uses SourceLink so you should be able to step through its code and debug the problem yourself. For more info see: https://devblogs.microsoft.com/dotnet/improving-debug-time-productivity-with-source-link/

jariq commented 2 years ago

One more thing came to my mind. Did you login into HSM via IPinProvider? Because private key objects are visible only to authenticated users.

rcohnuil commented 2 years ago

Yes I did. As I'm using an existing token, I skipped InitializeTokens() and added a new method to call session.Login(...) via an opened session from a slot with the token present.

I found the problem: I didn't use the right token's label. After I corrected that, cert.GetRSAPrivateKey() no longer returns null.

jariq commented 2 years ago

OK, thanks for letting me know.