“Invalid provider type specified” CryptographicException when trying to load private key of certificate

前端 未结 18 2900
盖世英雄少女心
盖世英雄少女心 2020-11-29 22:04

I\'m trying to read the private key of a certificate which has been shared with me by a third-party service provider, so I can use it to encrypt some XML before sending it t

18条回答
  •  北海茫月
    2020-11-29 22:57

    The link to Alejandro's blog is key.

    I believe this is because the certificate is stored on your machine with the CNG ("Crypto Next-Generation") API. The old .NET API is not compatible with it, so it doesn't work.

    You can use the Security.Cryptography wrapper for this API (available on Codeplex). This adds extension methods to X509Certificate/X509Certificate2, so your code will look something like:

    using Security.Cryptography.X509Certificates; // Get extension methods
    
    X509Certificate cert; // Populate from somewhere else...
    if (cert.HasCngKey())
    {
        var privateKey = cert.GetCngPrivateKey();
    }
    else
    {
        var privateKey = cert.PrivateKey;
    }
    

    Unfortunately the object model for CNG private keys is quite a bit different. I'm not sure if you can export them to XML like in your original code sample...in my case I just needed to sign some data with the private key.

提交回复
热议问题