Search code examples
c#encryptionxamarinrsaencryption-asymmetric

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;

Solution

  • 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 ?