andrewlocatelliwoodcock

Thoughts on Software

Implementing RSA asymmetric public-private key encryption in C#: generating public / private key pair

with 4 comments


I was originally planning a single post about implementing RSA-based encryption in C# but it quickly got unmanageable so I decided to split it into three separate posts on generating keys, encrypting and decrypting text. And so here is the first post: generating a public / private key pair in C#.

The .Net Framework makes this task remarkably easy for us: we need only instantiate the RSACryptoServiceProvider class passing the key length to use and then return the value of the ToXmlString method of the object. ToXmlString accepts a single parameter, includePrivateParameters, which is a Boolean value indicating whether to return a public / private key pair (includePrivateParameters = true) or just the public key (includePrivateParameters = false).

The key length passed to the constructor of the RSACryptoServiceProvider class is the number of bits to use and so must be a multiple of 8. As discussed in my last post, 1024 bit key length is now the minimum realistic key length to use, with 2048 or 4096 being preferable and much more secure.

The only difference between creating a 1024 bit or 2048 bit key is in the value passed to the constructor of the RSACryptoServiceProvider class: 1024 and 2048 respectively. It really is that simple!

using System.Security.Cryptography;

/// <summary>

/// Generate new 1024 bit public / private key pair

/// </summary>

/// <returns>XML containing new 1024 bit public / private key pair</returns>

public static string Generate1024BitKeys

{

var rsaProvider = new RSACryptoServiceProvider(1024);

return rsaProvider.ToXmlString(true);

}

/// <summary>

/// Generate new 2048 bit public / private key pair

/// </summary>

/// <returns>XML containing new 2048 bit public / private key pair</returns>

public static string Generate2048BitKeys

{

var rsaProvider = new RSACryptoServiceProvider(2048);

return rsaProvider.ToXmlString(true);

}

As RSACryptoServiceProvider will accept any valid value as a constructor parameter, we can also develop a much more generic method of creating public / private key pairs, one which accepts a range of bit length values and returns an XML-encoded public / private key pair to match:

using System.Security.Cryptography;

        /// <summary>

/// Ensure that only a valid key length can be requested. Below is a sample (not exhaustive) of valid values

/// </summary>

public enum RsaKeyLengths

{

        Bit1024 = 1024,

        Bit2048 = 2048,

        Bit4096 = 4096

}

        /// <summary>

/// Generate new public / private key pair at requested bit strength

/// </summary>

/// <returns>Public / private key pair</returns>

public static string GenerateKeys(RsaKeyLengths length)

{

var rsaProvider = new RSACryptoServiceProvider((int) length);

return rsaProvider.ToXmlString(true);

}

So what does the resulting XML-encoded public / private key pair look like? Here’s a sample:

<RSAKeyValue>

<Modulus>u6YibbNNp7KGU+kJcibAUY3cLIymlNJOKkD2sFUhfNKtkBtZgK0AbRHjGHwLk3B3euMgbjElHB2RN+G+jtDrVATiFRnUodAfk8gtbjg/dxcneKKJw7DdL1MTmj2iFvHg149TP7CmL7pUQLeq8+pqYe3Pnsa7h+4ZPprB13eiOVc=</Modulus>

<Exponent>AQAB</Exponent>

<P>7RMAtP9Vt9tBV3hjgx3I3fGqE4sUftoveYddNpS1TbhKfPpsK2278lDakOgqNaNFePzZV05ZTJc1VwsqWCMcvQ==</P>

<Q>yqELyplOjSWo8eUATHi/+RyF6ATuf5MU1iDYG0w7rAbASDrjvWzOTtLpPEi7ocGe/LRw81kT0yqyMl2UFi3xow==</Q>

<DP>DkvHDyMWmC+wkQXBenahVkDscKFCayPdGQcAp/nvtPAYDdFMFJJZcxNNGs/lO7bMya71rD4dRHEZ1lXmB8qWQQ==</DP>

<DQ>ESdJBEGuMKy7fJ7SQ6cFOWV8wIOKXSpqXSYypTzy4EFCDdtOZD7NyEZ6kCvoFm15tBLibPdhgkLfCvx5CNei2Q==</DQ>

<InverseQ>Kv7VG0M1a054/LE1tIg/FWEW2PhRUDRuUoM1KagLBrFqTsCV9vYuIH+Dl/Y3VRPtyT4Q8bf41awB3ofptZLf6w==</InverseQ>

<D>U5qmdjfP3mp03MfUFI7dWriYoySbR20XtE2zW0bin6mB+NWmn+T0bqPsiUkjIzKVmSO+nDm7Lfaib8JdU2YTolyOqPiGx+UG6T9901VkBpp6aVszpT4bDRs96v361T7jWEmo4t8ihXwkNVOGw+SHqqos4TlS/8p1MW6iQrxa9Ik=</D>

</RSAKeyValue>

Written by andrewlocatelliwoodcock

July 20, 2011 at 20:08

Posted in C#, Encryption, Security

Tagged with , , ,

4 Responses

Subscribe to comments with RSS.

  1. […] on from my last post on how to generate a public / private key pair in C#, this is the next post in my series on using […]

  2. Very nice… but it would be a lot more helpful if you post the decryption part of this process.

    yeremyjt

    February 16, 2012 at 21:26

    • That’s a very fair point! It’s been on my to-do list for a while now but I will get around to it … it’s been annoying me a bit too … Thanks for commenting!

      andrewlocatelliwoodcock

      February 19, 2012 at 19:56

  3. Nice post!
    I have done similar work recently on encrypting large text files using RSA / AES256 in C#

    http://www.technical-recipes.com/2013/using-rsa-to-encrypt-large-data-files-in-c/

    Andrew Webb (@Tech_Recipe)

    April 18, 2013 at 21:35


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: