简体   繁体   中英

RSACryptoServiceProvider, SSLStream(OpenSSL) - Encrypt, Decrypt

After the server authentication, using a openssl certificate.:

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.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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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