Search code examples
c#certificatebouncycastleprivate-keyx509certificate2

Use PrivateKey of a X509Certificate2 stored in Certificate Store and marked as non-exportable using BouncyCastle and C#


I'm trying to build a small certificate authority using bouncycastle.

The certificate is generated by using BouncyCastle and is stored in the Certificate Store of the current user, along with the private key.

However for security reasons the key is marked as non-exportable. I know that it is easy to circumvent this, but it's meant to be an additional barrier.

Now if a new certificate should be signed, I need to access the private key of the certificate. I tried using this code:

X509Certificate2 caCert = GetRootKey(); // Fetches the certificate from the store
AsymmetricCipherKeyPair caPrivKey = DotNetUtilities.GetKeyPair(caCert.PrivateKey);

Unfortunately I get an CryptographicException - because the private key is marked as not exportable, and this is what I intended ;-)

My question is: How can I use the private key of the certificate without accessing it? I'm pretty sure I'm missing some important point as it would not make any sense to have a private key stored without any way to access it...

I'm searching now for hours for this, but don't find anything on stackoverflow or Google.

Can anyone tell me please what I do fundamentally wrong? Is there another approach to sign something?!

Thanks in advance!

Chris


Solution

  • Short answer: Not with BouncyCastle.

    You can't put the key into the BouncyCastle (or OpenSSL or any other) library and use it from there. There is no way to do this without circumventing the "no export" flag and exporting it, which as you point out is possible if you are an administrator and have the requisite Fu.

    What you can do is get a CryptoAPI handle to the key, and ask CryptoAPI to do the signing or encryption operations for you. The DotNet crypto classes encapsulate CyptoAPI.

    So essentially what you need is a tutorial on how to use the DotNet crypto classes. There are many, for example this MSDN Magazine article has an example of digital signatures about three quarters of the way down:

    http://msdn.microsoft.com/en-us/magazine/cc163454.aspx