[英]RSACryptoServiceProvider, SSLStream(OpenSSL) - Encrypt, Decrypt
After the server authentication, using a openssl certificate.: 服务器身份验证后,使用openssl证书。:
sslStream.AuthenticateAsClient(serverName);
The data encryption, on the client side is made by the this code: 客户端上的数据加密是通过以下代码进行的:
string messsage = "teste123.<EOF>";
byte[] messageRSA = ConvertByte.GetBytes(messsage);
RSACryptoServiceProvider asr = new RSACryptoServiceProvider(2048);
var publicKey = asr.ExportParameters(false);
var csp = new RSACryptoServiceProvider();
csp.ImportParameters(publicKey);
messageRSA = csp.Encrypt(messageRSA, false);
The data goes through a SSLStream, like this: 数据通过SSLStream,如下所示:
sslStream.Write(messageRSA);
sslStream.Flush();
And the server is going to receive the data.: 服务器将接收数据:
byte[] bytes = new byte[2048];
bytes = sslStream.Read(buffer, 0, buffer.Length);
I've created a method just to clean the buffer, because with a "2048" size, i'm going to have a lot of "0" values that i don't need, só with this method i clean all these zeros that i don't need. 我创建了一个仅用于清理缓冲区的方法,因为在使用“ 2048”大小的情况下,我将拥有很多不需要的“ 0”值,因此使用此方法可以清理所有这些零我不需要
RSACryptoServiceProvider asr = new RSACryptoServiceProvider(2048);
var privateKey = asr.ExportParameters(true);
var csp = new RSACryptoServiceProvider();
csp.ImportParameters(privateKey);
decryptedMessage = FixBuffer(buffer);//method that cleans the buffer, and return a valid array, just with the information that i want.
decryptedMessage= csp.Decrypt(decryptedMessage, false);
When it tries to decrypt, i get a CryptographicException
, and the message is Invalid Data
. 当它尝试解密时,我得到
CryptographicException
,并且消息是Invalid Data
。
And the question is,Do i really need the same public private key that i use on the client side to decrypt this data? 问题是,我真的需要在客户端使用相同的公钥来解密此数据吗?
If yes, how can i pass this key to the server side, and decrypt the information correctly? 如果是,我如何将该密钥传递给服务器端,并正确解密信息?
To decrypt the data, you certainly need to use the private key that corresponds to the public key used to encrypt it. 要解密数据,您当然需要使用与用于加密数据的公钥相对应的私钥。 As it stands, you're generating a new (different) key on the server, which will not be usable to decrypt the data.
就目前而言,您正在服务器上生成一个新的(不同的)密钥,该密钥将无法用于解密数据。 As for how to convey the correct key to the server, the answer is that you don't - the server should generate the key, and send the public part (only) to the client, which it can then use to encrypt the message.
至于如何将正确的密钥传达给服务器,答案是您没有这样做-服务器应生成密钥,并将(仅)公共部分发送给客户端,然后客户端可以使用该部分来加密消息。
This all being said, it seems rather unnecessary to be encrypting the data at all, given that the communication is already occurring over an encrypted SSL connection. 综上所述,鉴于通信已经通过加密的SSL连接进行,因此似乎根本不需要对数据进行加密。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.