简体   繁体   English

C和C#之间的RSA加密

[英]RSA Encryption Between C and C#

I am trying to write a simple RSA encryption scheme to encrypt a small message between a single server and potentially many clients. 我正在尝试编写一种简单的RSA加密方案,以对单个服务器和可能的许多客户端之间的一条小消息进行加密。

The plan I have come up with is to have the client generate a key pair and send the public key to the server. 我想出的计划是让客户端生成密钥对并将公钥发送到服务器。 The server has an object that will store the socket and the public key. 服务器具有一个对象,该对象将存储套接字和公共密钥。 When it comes time to send the message the server will call a method in the Client object that will encrypt the message and send it down to the client. 当需要发送消息时,服务器将在Client对象中调用一个方法,该方法将加密消息并将其发送给客户端。

I will only be encrypting the messages going to the client, so I don't need to worry about a full transaction of keys. 我将只加密发送到客户端的消息,因此无需担心密钥的完整交易。

I think I have that pretty well figured out. 我想我已经很清楚了。

The problems are coming from trying to connect two different implementations of RSA. 问题来自尝试连接RSA的两个不同实现。 The server is written in C# and the client is a MetaTrader client using C. I have decided to use OpenSSL to try to bridge the gap, but so far I haven't been able to produce a key on the client. 服务器是用C#编写的,客户端是使用C的MetaTrader客户端。我已决定使用OpenSSL来缩小差距,但是到目前为止,我还无法在客户端上生成密钥。 I am using the openssl wrapper for c# ( http://openssl-net.sourceforge.net/ ) and I am trying to write a very basic wrapper dll for MetaTrader. 我正在为C#使用openssl包装器( http://openssl-net.sourceforge.net/ ),并且试图为MetaTrader写一个非常基本的包装器dll。 So far it contains two functions, GenerateRSAKeys and DecryptRSA. 到目前为止,它包含两个函数,GenerateRSAKeys和DecryptRSA。

For now, I would just like to produce a PEM formatted string that contains the public key. 现在,我只想生成一个包含公共密钥的PEM格式的字符串。 This is what I have so far for GenerateRSAKeys(). 到目前为止,这是我对GenerateRSAKeys()的了解。

extern "C" unsigned char *__stdcall GenerateRSAKeys (){

int len;
unsigned char *buf = new unsigned char[1024];

rsa = RSA_generate_key(512,RSA_F4,NULL,NULL);

len=i2d_RSAPublicKey(rsa, &buf);

return buf;}

Right now, when sending buf to the server I receive a single character. 现在,将buf发送到服务器时,我收到一个字符。 Such as, "X" 例如“ X”

So my first question is, what is the best way to export the generated public key? 所以我的第一个问题是,导出生成的公共密钥的最佳方法是什么?

You are returning a pointer to a buffer allocated on the stack; 您正在返回一个指向堆栈上分配的缓冲区的指针。 this buffer will be overwritten when the function returns. 函数返回时,此缓冲区将被覆盖。 Try buf = new unsigned char[1024]; 尝试buf = new unsigned char[1024];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM