Does your company or startup need an expert? If so, write to me to talk about possibilities of professional cooperation.
PROGRAMMING on-line course is approaching! Write to me if you are interested in free early access.

MARCIN.com

Marcin Jamro, PhD, DSc

How to encrypt and decrypt text with RSA asymmetric algorithm?

C#  |  .NET  |  Algorithms

An encryption algorithm is used to encrypt data, which means encoding information (plain text) to another form (cipher text) that should be possible to decode by the authorized person only. There are many encryption algorithms, among which two subtypes can be mentioned, namely symmetric-key and asymmetric-key (also called public-key). Encryption is commonly used in various systems, such as for protecting communication in the popular messengers, for the digital rights management systems, or for protecting wireless communication. Currently, it is a standard to secure communication, so the knowledge of the encryption algorithms should be the "must have" for any developer.

Rivest-Shamir-Adleman Security (RSA) is an asymmetric-key variant. It uses a pair of keys for a user, namely a public key and a private key (also named a secret key). A public key can be shared with anyone and is used to encrypt data. However, the private key should be kept safe and is required to decrypt data, as shown below:

Illustration

There is a set of classes available that makes its application very easy. As an example, let's take a look at the method for encryption:

byte[] Encrypt(string plainText, byte[] publicKey)
{
    using RSA rsa = RSA.Create();
    rsa.ImportRSAPublicKey(publicKey, out int _);
    byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
    return rsa.Encrypt(plainBytes, RSAEncryptionPadding.Pkcs1);
}

Here, you need to create a new instance representing the RSA algorithm and import the public key of the receiver, which is used for encryption. Then, you get bytes from the plain text and encrypt them, returning the byte array.

Is decrypting similar? Just rate it yourself in the code below:

string Decrypt(byte[] cipherBytes, byte[] privateKey)
{
    using RSA rsa = RSA.Create();
    rsa.ImportRSAPrivateKey(privateKey, out int _);
    byte[] plainBytes = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1);
    return Encoding.UTF8.GetString(plainBytes);
}

As you can see, the first line is the same. Then, you need to import the private key (instead of the public one) and decrypt the encrypted byte array. You receive the decrypted byte array that you convert into string in the last line.

If you want to generate a pair of keys, just use ExportRSAPublicKey and ExportRSAPrivateKey methods:

RSA rsa = RSA.Create();
byte[] publicKey = rsa.ExportRSAPublicKey();
byte[] privateKey = rsa.ExportRSAPrivateKey();

The example of encrypting and decrypting a string is shown as follows:

string plainText = "Can we meet today at 09:00?";
byte[] cipherBytes = Encrypt(plainText, publicKey);
string decryptedText = Decrypt(cipherBytes, privateKey);

As you can see, for encryption you need the public key of a receiver, while for decryption the private key is required. Pretty simple, isn't it? By the way, the asymmetric-key algorithms are used nowadays in various protocols, including GNU Privacy Guard (GPG), Pretty Good Privacy (PGP), Internet Protocol Security (IPSec) and Secure Shell Protocol (SSH).

The content, including any part of code, is presented without warranty, either express or implied. The author cannot be held liable for any damages caused or alleged to have been caused directly or indirectly by any content shown on this website.

Hello, I am Marcin

Reliable entrepreneur with 10+ years of companies operation, such as CEO at a few IT companies. I was an author of a few software & hardware products, still open to new ideas & cooperation.

Helpful expert with 10+ years of experience, together with PhD and DSc in Computer Science. I was an author of books and publications, as well as an expert in international projects.

Experienced developer with 10+ years of development and 100+ completed projects. I worked on various complex international projects, e.g. at Microsoft in USA and as CTO at a few companies. I have MCP, MCTS and MCPD certificates.

You can read more about me in my short bio. I am waiting for contact at [email protected], as well as at my Facebook and LinkedIn profiles.

Books

I am an author of a few books and numerous publications, also in high-quality international scientific journals.

If you want to learn data structures and algorithms in the context of C#, let's take a look at my newest book. It is the second edition of C# Data Structures and Algorithms. You can buy it here.

Projects

Do you like traveling? If so, discover an amazing world with local guides, right here and right now at: https://camaica.com

Do you follow your favorite creators? If so, check it out what products they recommend and buy them at: https://refspace.com

Travels

I love travels, learning new cultures and regions, meeting outstanding people, as well as taking pictures of beautiful places. Take a look at my travel diary.