Search code examples
c#wcfclient-serverrsarsacryptoserviceprovider

"The parameter is incorrect." RSACryptoServiceProvider WCF Client/Server C#


I have two local console applications, one is the server that generates the public and private key, the other is a client which receives the public key from the server by consuming a service and sends an encrypted message to the server. The service then tries to decrypt the message and save it in the server, but a CryptographicException is thrown saying that the parameter is incorrect when RSA.Decrypt is called.

Code sample:

byte[] decryptedByteMessage;
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
       decryptedByteMessage = RSADecrypt(encryptedByteMessage, privKey);
}

Decrypt

static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo)
        {
            try
            {
                byte[] decryptedData;
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    RSA.ImportParameters(RSAKeyInfo);
                    decryptedData = RSA.Decrypt(DataToDecrypt, false); // exception here
                }
                return decryptedData;
            }
            catch (CryptographicException e)
            {
                Console.Write(e.Message);
                return null;
            }
        }

I can see that the keys are correct, and the same code works fine in a single console application. I tried to look for a solution, (perhaps CspParameters is required?) but it's just making it more confusing at the moment.

I would be grateful if you could give me some pointers to fix this.


Solution

  • The problem was that I was running the applications in Debug mode inside Visual Studio.

    I tried with the actual Release executables and everything runs as expected.