简体   繁体   中英

RSA (client side encryption/ server decryption)

This is a continuation of the project in this question , but without the Bouncy Castle.

So I decided to scrap Bouncy Castle (pity, I loved the name)

ANYWAY

I have a server and a client. the client needs to send a serialized object to the server, the server will then process this object.

It does this, however I'd like to add encryption to the process. But without storing a file or anything like that. the process needs to be session based(in a sense)

So, the client will request a key from the server, the server will generate a key pair and send a key to the client.

Client then uses this key to encrypt the object

string key = ASCIIEncoding.ASCII.GetString(RequestKey(tcpclnt));
var RsaClient =new RSACryptoServiceProvider(2048);
while (key.Length > 0) {
     RsaClient.FromXmlString(key);
     var transmit = ASCIIEncoding.ASCII.GetBytes(stringtosend);
                  var encrypted = RsaClient.Encrypt(transmit,false);

the server then receives these encrypted bytes and tries to decrypt them

 raw = Receive(clientSocket);
 byte[] r = TrimBytes(ASCIIEncoding.ASCII.GetBytes(raw),256);
 var sdecrypted = ASCIIEncoding.ASCII.GetString(RsaServer.Decrypt(r, false));

But alas, the server can't do this. On Decryption it throws an error

Key does not exist.

So, my question is, what am I doing wrong?

Many thanks in advance for any help you can offer.

UPDATE

Altered the code in the server

var RSAKeyInfo = new RSACryptoServiceProvider(2048, new CspParameters(1)).ExportParameters(true);

New error

The parameter is incorrect

Whilst fine as an exercise in the use of cryptography, the use of basic cryptographic algorithms to build your own system for secure communication is a recipe for insecurity. For every weakness you address in your own system, there are likely 10 (or more!) that you won't even have thought of.

My strong suggestion therefore is to use SSL/TLS to secure your communications. This should provide all the security you need whilst also being straightforward to integrate as the .NET Framework's SslStream has the necessary functionality to operate as either the server or client side of the connection.

Doing this will also allow you to optionally use additional security mechanisms in the future, eg certificate based client authentication, with minimal additional effort.

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