Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the public key from RSACryptoServiceProvider?

Tags:

c#

rsa

encryption

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?

like image 965
CommunistPancake Avatar asked Dec 26 '12 23:12

CommunistPancake


1 Answers

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();
            }
        }
    }
like image 56
Mehmet Ataş Avatar answered Sep 21 '22 04:09

Mehmet Ataş