Thuan
Thuan

Reputation: 1628

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?

Upvotes: 4

Views: 529

Answers (1)

MichaelHoward-MSFT
MichaelHoward-MSFT

Reputation: 319

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.

Upvotes: 1

Related Questions