Cobe
Cobe

Reputation: 161

RSA algorithm with use of RSACryptoServiceProvider

I have a little hard time understanding the RSACryptoServiceProvider class... I'm supposed to encrypt a message of length 256 bits, with a key , which is also 256 bits long. Shouldn't the output of also be 256 bits long? Here's my code:

//key generation

byte[] bytes = new byte[32];
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(bytes);
k2 = bytes;

//encryption function

static public byte[] Encryption(byte[] Data, RSAParameters RSAKey, bool DoOAEPPadding)
{  
    byte[] encryptedData;
    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
    {
        RSA.ImportParameters(RSAKey);
        encryptedData = RSA.Encrypt(Data, DoOAEPPadding);
    }
    return encryptedData;
}

And then finally calculating

ciphertext = Encryption(k2, RSA.ExportParameters(false), false);

produces a byte[128] ciphertext aka 1024 bits. Shouldn't I get ciphertext of size byte[32]?

Upvotes: 0

Views: 654

Answers (1)

Maarten Bodewes
Maarten Bodewes

Reputation: 94058

It seems that you use the key, k2, as data for RSA encryption. That's OK if you want e.g. to wrap a 256 bit AES key using RSA. But your RSA key is the second parameter, not the first.

The data in k2 is then padded (according to the older PKCS#1 v1.5 scheme), after which modular exponentiation will be performed using the public exponent and modulus of the RSA key. The modulus of the RSA key determines the key size. This modulus exponentiation will always produce a result between zero and modulus - 1. However, the result is always left-padded to the key size in bytes (with a function called I2OSP).

So it seems your result is 1024 bits, which means that your RSA key pair is also 1024 bits.

Upvotes: 1

Related Questions