srdrgkcn89
srdrgkcn89

Reputation: 109

Generating a key-pair and encrypt data with this in Mono C#

I have RSA modulus and exponent, i want to generate a public key with this components. Then i want to encrypt a data with this public key.

So i wrote this function:

public static byte[] EncryptRSA(byte[] rsaModulus, byte[] exponent, byte[] data)
    {       
        byte[] response = null;
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        RSAParameters rsaPar = rsa.ExportParameters(false);

        rsaPar.Modulus = rsaModulus;
        rsaPar.Exponent = exponent;

        rsa.ImportParameters(rsaPar);

        response = rsa.Encrypt(data, false);

        return response;
    }

but rsa.ExportParameters method takes long time.

public RSACryptoServiceProvider ()
    : this (1024)
{
    // Here it's not clear if we need to generate a keypair
    // (note: MS implementation generates a keypair in this case).
    // However we:
    // (a) often use this constructor to import an existing keypair.
    // (b) take a LOT of time to generate the RSA keypair
    // So we'll generate the keypair only when (and if) it's being
    // used (or exported). This should save us a lot of time (at 
    // least in the unit tests).
}

As you can see ExportParameters() method is performing RSA key-pair generation which is time consuming operation.

After that i get exception "Private/public key mismatch" at importing RSA parameters.

Upvotes: 1

Views: 1271

Answers (2)

CodesInChaos
CodesInChaos

Reputation: 108800

Simply replace the export with creating a new object:

RSAParameters rsaPar = rsa.ExportParameters(false);

with

RSAParameters rsaPar = new RSAParameters();

That should still be slow in .net but should be fast in mono since it creates keys lazily.

I also strongly recommend using OAEP padding instead PKCS#1v1.5 padding. The latter has weaknesses that can be exploited in practice unless you carefully work around them. So use rsa.Encrypt(data, true) not rsa.Encrypt(data, false).

Upvotes: 3

Maarten Bodewes
Maarten Bodewes

Reputation: 93968

I don't see any clear way of removing the time-out related to generating the key pair. You are probably better off using FromXMLString as I don't see any method to generate the RSAParameters object an other way.

As for the mismatch, that is to be expected - the private key is still in there. Microsoft uses a second RSACryptoServiceProvider (check the sample code) to get around this issue.

Upvotes: 1

Related Questions