从RSACryptoServiceProvider获取公钥? [英] Get the public key from RSACryptoServiceProvider?

查看:64
本文介绍了从RSACryptoServiceProvider获取公钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用公共密钥加密与客户端和服务器进行通信.服务器应该生成一个1024位的公共密钥,并将其发送给客户端,客户端将使用该密钥将加密的数据发送回服务器.到目前为止,我已经使用以下方法初始化了RSACryptoServiceProvider:

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);

现在,我知道我可以使用 ExportParameters 从RSACryptoServiceProvider获取指数和模数.但是,我想知道如何使用此数据将公钥发送回客户端(也将使用 RSACryptoServiceProvider ),以及客户端如何使用此数据对某些内容进行加密寄回给我?还是我这样做完全错误?

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();
            }
        }
    }

这篇关于从RSACryptoServiceProvider获取公钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆