## Archive for the ‘**Encryption**’ Category

## Implementing RSA asymmetric public-private key encryption in C#: encrypting under the public key

Following 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 RSA asymmetric encryption in .Net.

Now we have a public / private key pair, we can encrypt an arbitrary string using RSA encryption. To make this code more general, we are going to allow users to specify the bit length of the public key, allowing us to easily encrypt under 1024, 2048 and 4096 bit keys. To this end, I am reusing the RsaKeyLengths enumeration from the last post containing three common bit lengths: 1024, 2048 and 4096.

Performing RSA Encryption is not particularly difficult, but neither is it straightforward.

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

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.

## Introduction to RSA asymmetric encryption

Protecting data has never been more important and yet in my experience a surprising number of people think that data protection starts and ends with SSL. But HTTPS only protects data in *transit,* not at either end of the pipeline. This becomes increasingly important once we are persisting sensitive data such as user passwords. Such data needs to be encrypted so that even if intercepted it cannot be used by an attacker, or the attacker can at least be put to an awful lot of trouble to decrypt the data.