“Invalid provider type specified” CryptographicException when accessing the PrivateKey property of a certificate in C#/.Net

We recently encountered this in a production environment: A customer had installed a new certificate, and this exception began showing up in the logs. Luckily, the application was smart enough to at least fall back on using the previous (not yet expired) certificate, so no downtime occurred.

Turns out the customer had been provided with a certificate with the private key in CNG format. This is not compatible with several versions of .Net. The solution was to convert the key to a standard RSA key using the following commands on a machine with OpenSSL installed:

# You need to set these to match your environment
cert="CertificateFileNameHere.pfx" password="TopSecretCertificatePasswordHere"
# These should run as is - they use the variables provided above openssl pkcs12 -in "${cert}.pfx" -nokeys -out "${cert}.cer" -passin "pass:${password}" openssl pkcs12 -in "${cert}.pfx" -nocerts -out "${cert}.pem" -passin "pass:${password}" -passout "pass:${password}" openssl rsa -inform PEM -in "${cert}.pem" -out "${cert}.rsa" -passin "pass:${password}" -passout "pass:${password}" openssl pkcs12 -export -in "${cert}.cer" -inkey "${cert}.rsa" -out "converted.pfx" -passin "pass:${password}" -passout "pass:${password}"

Importing the converted certificate back into Windows’ Certificate Store, the .Net application was capable of loading it just fine.

The solution was mostly found here.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *