Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use X509Certificate2 with Windows certificate store, HSM, and Azure Key Vault

I have many methods like the below which uses X509Certificate2.PrivateKey

    public SomeValue DoSomething(X509Certificate2 cert)
    {
        // do something that needs the cert.PrivateKey
    }

They are working well so far with certificates that are stored in the Windows certificate store whose private keys are accessible. Problem now is that I need to support certificates stored in HSM devices and Azure Key Vault HSM where the private keys can't be loaded into memory (and thus the PrivateKey property is null).

I'm looking for a way to avoid changing signatures of my public methods. If the PrivateKey property is virtual, I would be easily make sub classes and return appropriate AsymmetricAlgorithm implementation for each store type (to be clear, for example in Azure Key Vault HSM, the AsymmetricAlgorithm will be an implementation that calls Azure Key Vault to do signing). Btw, the setter of the PrivateKey property doesn't allow me to set my custom AsymmetricAlgorithm.

Another problem is that the PrivateKey property is out of favor now and the GetRSAPrivateKey extension method is recommended.

Is there any trick that I can use to let an X509Certificate2.PrivateKey or the GetRSAPrivateKey extension method returns an AsymmetricAlgorithm of a type that I want?

like image 471
Thuan Avatar asked Jan 27 '26 12:01

Thuan


1 Answers

When using KV, RSA Private Keys don't leave KV, when you get a 'key' back from KV, you really get a key ID, not the key. You will need to export the cert as a PFX file.

like image 187
MichaelHoward-MSFT Avatar answered Jan 29 '26 04:01

MichaelHoward-MSFT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!