How can i send a RsaKeyParameters to a server or vice versa?


I am using the Bouncy Castle on Xamarin Forms to asymmectric encrypt. But i am working on a Client <-> Web Api structure. How can i send the public Key to the other side ? Because the type is RsaKeyParameters .

RsaKeyPairGenerator rsaKeyPairGnr = new RsaKeyPairGenerator();
rsaKeyPairGnr.Init(new KeyGenerationParameters(new SecureRandom(), 512));
AsymmetricCipherKeyPair keyPair = rsaKeyPairGnr.GenerateKeyPair();
RsaKeyParameters publicKey = (RsaKeyParameters)keyPair.Public;


If I have a RsaKeyParameters publicKey and I need to send this to a server, I can convert using:

//convert from key to string
SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded();    
string serializedPublic = Convert.ToBase64String(serializedPublicBytes);
And then, i can convert the serializedPublic to RsaKeyParameters publicKey

//convert from string to key
RsaKeyParameters publicKey2 = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(serializedPublic));

But could someone tell me if passing the public key by querystring via Http library is a good idea ?

You could use Convert.ChangeType for that:

public void Add(object value)
    var t = Convert.ChangeType(value, typeof(T));

See the fiddle:

If you need object insead of T you can use dynamic in your Add method.

 public void Add(object value)
      //When T is decimal, then I get 
      // System.InvalidCastException
      dynamic t1 = value;
      var t = (T)t1;
By : steryd

This video can help you solving your question :)
By: admin