rsacryptoserviceprovider using x509 certificates c#

bkhanal picture bkhanal · Oct 26, 2009 · Viewed 20.5k times · Source

i am using a certificate generated by makecert which has both private and public key. The java side uses this public key to encrypt the data and .net decrypts it back.

I am trying to decrypt Java's encrypted 64 bit encoded string and getting bad data.

To see if all is good on.Net end, I frist tried to encrypt with the public key and then decrypt with private using the same certificate. My code looks like this.

X509Certificate2 cert = GetCert(key, StoreName.My, StoreLocation.LocalMachine);
RSACryptoServiceProvider provider =  (RSACryptoServiceProvider)cert.PrivateKey;

RSACryptoServiceProvider publicprovider = (RSACryptoServiceProvider)cert.PublicKey.Key;

if (cert.HasPrivateKey)
    MessageBox.Show("Got private key");

byte[] encrypted = publicprovider.Encrypt(Encoding.UTF8.GetBytes(text), false);
byte[] decryptedBytes = provider.Decrypt(encrypted, false); 

Even here I am getting the error. Am i Missing something?

The certificate looks valid with both public and private key.

Answer

Matt Palmerlee picture Matt Palmerlee · Oct 4, 2010

I had the same problem with a self-signed cert, the issue was that I was generating the cert with the switch -sky signature instead of -sky exchange (you use signature for signing and exchange for encryption/decryption)

Here is my full command to makecert that works:

makecert -r -pe -a sha1 -n "CN=MyName" -ss my -sr CurrentUser -sky exchange