I'm trying to use public key encryption for communication with a client and server. The server is supposed to generate a 1024-bit public key and send it to the client, where the client will use that key to send encrypted data back to the server. So far, I've initialized the RSACryptoServiceProvider with this:
RSACryptoServiceProvider rsaEncryption = new RSACryptoServiceProvider(1024);
Now, I'm aware that I can use ExportParameters
to get the exponent and modulus from the RSACryptoServiceProvider. However, I'm wondering, how can I use this data to send a public key back to the client (which would also be using an RSACryptoServiceProvider
), and how can the client use this data to encrypt something to send back to me?
Or am I doing this completely wrong?
Your logic seems ok and it seems that you only need some sample code.
using System;
using System.Security.Cryptography;
using System.Text;
namespace RSA
{
class Program
{
static void Main(string[] args)
{
try
{
var rsaServer = new RSACryptoServiceProvider(1024);
var publicKeyXml = rsaServer.ToXmlString(false);
var rsaClient = new RSACryptoServiceProvider(1024);
rsaClient.FromXmlString(publicKeyXml);
var data = Encoding.UTF8.GetBytes("Data To Be Encrypted");
var encryptedData = rsaClient.Encrypt(data, false);
var decryptedData = rsaServer.Decrypt(encryptedData, false);
Console.WriteLine(Encoding.UTF8.GetString(decryptedData));
Console.WriteLine("OK");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.Read();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With