C# BouncyCastle RSA Encryption and Decryption

bouncycastlecencryptionrsa

There are many topics on RSA Encryption and Decryption using BouncyCastle, however I'm encountering some unexpected behaviour.

I'm attempting to encrypt a 64 byte data blocking using a private key of size 64 bytes

I compute the RSA Encryption as followings:

public byte[] Encrypt(byte[] data, AsymmetricKeyParameter key)
{
    var engine = new RsaEngine();
    engine.Init(true, key);
    var blockSize = engine.GetInputBlockSize();
    return engine.ProcessBlock(data, 0, blockSize );
}

I compute the decryption using a public key as follows

public byte[] Decrypt(byte[] data, AsymmetricKeyParameter key)
{
    var engine = new RsaEngine();
    engine.Init(false, key);
    var blockSize = engine.GetInputBlockSize();
    return engine.ProcessBlock(data, 0, blockSize );
}

What I'm finding is that when I encrypt my 64 data using a 64 byte Private Key I get back a 64 byte encrypted dataBlock.

However when I decode the 64 byte array using a 64 byte public key I get back a data block of size 62 bytes. What is stranger is that the values contained in the 62 byte array equal the values of the 64 byte original array (pre encryption) however the decoded array is missing the first index of the original data and the final index.

I've tried using different keys and different sets of data and the same thing happens.

I must be doing something wrong, but I can't see it.

Cheers.

Best Answer

You got the essential concepts wrong.

  1. 512 bit RSA is very weak, use at least 1024 bits
  2. A private key is not for encryption. It's for decryption and signing. The public key is for encryption and verification.
  3. Padding is essential for RSA security. A typical padding scheme requires several dozen bytes.
  4. Even with textbook RSA, RSA can only work on values smaller than the modulus. So a 512 bit modulus can't operate on arbitrary 64 byte / 512 bit values. But only on 511 bits.

You should take a step back, and describe what you actually want to achieve, so we can find a scheme that fits your needs. Only after that you should worry about implementing it.