RSA using BouncyCastle

Trying to do RSA using BouncyCastle, but struggling to find your way around the API? In a previous post (see here) I pondered why the RSA implementation in System.Security.Cryptography is restricted to only the most common usage scenarios. I mentioned BouncyCastle as an alternative for those who wanted a more flexible API, but never got around to providing examples where BouncyCastle was used. By request, this post provides usage examples by building a crude and simple, but efficient set of methods for RSA key generation, encryption, and decryption, all built on top of BouncyCastle.

NOTE: The general cryptographical security of the presented method is beyond the scope of the article. The code presented is not cryptographically secure for large data sets. If you’re here looking for a way to do cryptographically secure RSA in the general case, you should look into more complicated approaches including padding, blinding, and more sophisticated block cipher modes. Cryptography is a topic undergoing constant research, so stay up to date and be sure to evaluate the strength of your solution for the scenarios in which you apply it.

BouncyCastle provides flexibility and control over your encryption approach, which comes at a cost. The BouncyCastle API might be a bit hard to cope with at first, but if you know encryption in general you should be able to find your way around the API without too much effort. This post will be focusing on RSA, since that was my original need, but it should be mentioned that BouncyCastle provides many other asymmetric (and symmetric) algorithms for which the usage is similar to what you find below.

Creating RSA keys

Creating RSA keys is a simple task. The method below lets you specify the key size in bits, and creates a key pair for you.


public AsymmetricCipherKeyPair GenerateKeys(int keySizeInBits)
{
  RsaKeyPairGenerator r = new RsaKeyPairGenerator();
  r.Init(new KeyGenerationParameters(new SecureRandom(),
    keySizeInBits));
  AsymmetricCipherKeyPair keys = r.GenerateKeyPair();
  return keys;
}

That’s all there is to it.

Encryption

Now that we have a key pair, we are ready to encrypt and decrypt using RSA. In the example below, we use a key (public or private) to encrypt a byte sequence. To encrypt a string, simply convert the string to a byte array using Encoding.GetBytes.


public byte[] Encrypt(byte[] data, AsymmetricKeyParameter key)
{
  RsaEngine e = new RsaEngine();
  e.Init(true, key);</p>

<p>int blockSize = e.GetInputBlockSize();</p>

<p>List<byte> output = new List<byte>();</p>

<p>for (int chunkPosition = 0; chunkPosition &lt; data.Length; 
    chunkPosition += blockSize)
  {
    int chunkSize = Math.Min(blockSize, data.Length - 
      (chunkPosition * blockSize));
    output.AddRange(e.ProcessBlock(data, chunkPosition,
      chunkSize));
  }
  return output.ToArray();
}

The approach above uses a list to gather output for the sake of simplicity. Note that the RSA engine can only process a limited block size at a time (block size depends on the key size). The approach above processes a data set of an arbitrary size.

The above method does not impose constraints on which key you use for encryption. Use the public key or the private key as you see fit for your solution.

Decryption

The Decrypt method is very similar to the Encrypt method:


public byte[] Decrypt(byte[] data, AsymmetricKeyParameter key)
{
  RsaEngine e = new RsaEngine();
  e.Init(false, key);</p>

<p>int blockSize = e.GetInputBlockSize();</p>

<p>List<byte> output = new List<byte>();</p>

<p>for (int chunkPosition = 0; chunkPosition &lt; data.Length;
    chunkPosition += blockSize)
  {
    int chunkSize = Math.Min(blockSize, data.Length - 
      (chunkPosition * blockSize));
    output.AddRange(e.ProcessBlock(data, chunkPosition,
      chunkSize));
  }
  return output.ToArray();
}

Again, it’s up to you which key you choose to use. If you want to use the common approach, encrypt using a symmetric cipher, hash the data, and sign the hash with your private key using the above Encrypt method. If you want to use another approach like encrypting the actual data using your private key, you are free to do so.

I hope this post helps those of you who want to apply RSA (or any other asymmetric cipher) to more subtle cases than those supported by the .NET framework.