Mhd.Jarkas
Mhd.Jarkas

Reputation: 414

RSA Encrypt with Public Key

Hi every body I'm building Client/Server meetings System

I had a problem "Cannot implicitly convert type 'string' to 'System.Security.Cryptography.RSAParameters'"

I will explain the process quickly

I received Server reply ( public key ) but when I tried to encrypt using RSA the error above appeared

This is my Code :

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

// mess is Server response as string
RSAParameters publickey = mess;

rsa.ImportParameters(publickey);

byte[] encryptedData = rsa.Encrypt(StringToByte(uname.Text + "|||" + PUBKEY), true);

Upvotes: 0

Views: 13442

Answers (1)

Jude Cooray
Jude Cooray

Reputation: 19862

First of all, ImportParameters() does not accept a string. It is expecting something of type RSAParameters. And it cannot implicitly convert a string to RSAParameter object, and that is why the error is shown.

I believe you haven't fundamentally understood on how RSA works. Or is it technical? Read the examples provided in here to understand it technically.

What you should be looking for is how to correctly export the public key from the server, and use the same public key to encrypt something in the client end.

As you would have guessed ExportParameters and ImportParameters looks promising. However I had trouble sending it through an SMS (in my project). So what I used was ExportCspBlob and ImportCspBlob. Make sure you specify false to ExportCspBlob so as to not include private key information.

To send it as a string, what I had to do was base64 encode the byte array that was returned from ExportCspBlob. To do the conversion, use the Convert class. The methods you are specifically looking for are ToBase64String and FromBase64String

Upvotes: 3

Related Questions