CAPICOM Certificate keys to RSACryptoServiceProvider

From: Mark Abrams (
Date: 07/15/04

Date: Thu, 15 Jul 2004 03:54:02 -0700


I am using the RSACryptoServiceProvider to perform the asymmetric encryption, but I am having big problems extracting the public and private keys from a X509 certificate to use with the RSACryptoServiceProvider. The certificate is installed in the LocalMachine/MY Store and includes both the public and private keys. The certificate has been obtained from a root certification authority on Windows 2003 Server and is valid.

I am using CAPICOM 2 to create the CAPICOM.Certificate object. I'm using the following VB.Net code to load the public and private keys into the RSACSP object:

CSPParams = New CspParameters
CSPParams.KeyContainerName = CAPICOMCertificate.PrivateKey.ContainerName
CSPParams.KeyNumber = CAPICOMCertificate.PrivateKey.KeySpec
RSACSP = New RSACryptoServiceProvider(CSPParams)

Although this enables me to encrypt and decrpyt on the same machine, if I try to encrypt on Machine A and decrpyt on Machine B (where both machines have the same certificate installed), I get a Bad Data error when trying to decrypt the data using the Decrypt method of RSACryptoServiceProvider. I don't think that the above code is extracting the public key properly, it does not seem to match that specified in the certificate.

I've also tried using the objects within the Microsoft.Web.Services2.Security namespace. This allows me to create a X509Certificate object, but this does not seem to allow me to export the private key from the certificate into the RSACryptoServiceProvider. An error is reported stating that "Export of private parameters is not supported".

My question is how can I get the public and private keys out of a CAPICOM or WSE2.0 certificate object into a RSACryptoServiceProvider object ?? Is it possible to do this without using P/Invoke ?? Any sample code would be great.

Many thanks,