Encrypt and decrypt data using RSA algorithm in C#

Key takeaways:

  • RSA in C#: C# makes RSA easy with RSACryptoServiceProvider, letting you generate keys, encrypt, and decrypt data.

  • Generate RSA key pair in C#: Creating a new instance of RSACryptoServiceProvider generates both the public and private keys.

  • Steps for encrypting and decrypting data using RSA in C#:

    • Convert the data to be encrypted to a byte array.

    • The Encrypt method is used to encrypt the byte array with the public key.

    • The Decrypt method with the private key is used to decrypt the encrypted byte array.

    • Reconvert the data to its original format.

RSA's security is based on the fact that factoring large prime numbers is really hard. If someone figures out an easy way to factor in huge numbers, RSA as we know it could be broken. Until then, it remains the backbone of secure communication.

In today’s digital age with AI at its peak, securing information is more important than ever. Whether it’s online banking, private messages, or company secrets, we want our data to stay safe from prying eyes. One powerful way to protect information is through encryptionEncryption is converting data into a secret code to protect it from unauthorized access., and one of the most popular encryption methods is RSA.

Let’s explore the world of RSA encryption, learn the basics, and how to encrypt and decrypt data using C#.

What is RSA encryption?

RSA (named after its creators, Rivest, Shamir, and Adleman) is an asymmetric encryption algorithm that uses public-key encryption. This means that, unlike simpler encryption methods, RSA uses two keys for security:

  • Public key: This key is shared openly and is used to encrypt data.

  • Private key: This key is kept secret by the owner and is used to decrypt data.

We can think of it like a mailbox with a lock:

  • Anyone can drop a letter (encrypted message) into the mailbox because it’s publicly accessible.

  • Only the person with the key (private key) can unlock the mailbox and read the letters.

RSA encryption relies on the difficulty of working with large prime numbers, making it highly secure and widely used for online banking, secure websites, and even digital signatures!

RSA encryption democratized security. With it, people everywhere gained the ability to keep their digital communications safe and private.

How does RSA work?

Here’s a quick breakdown of RSA’s process:

  1. Generate keys: Two large prime numbers are chosen and combined to create a public and private key pair.

  2. Encrypt data: The sender uses the recipient’s public key to encrypt the message.

  3. Decrypt data: The recipient then uses their private key to decrypt the message.

Setting up RSA encryption in C#

C# facilitates RSA encryption by providing the RSACryptoServiceProvider class in the System.Security.Cryptography library, which provides built-in methods to handle encryption and decryption.

1. Generating RSA keys

To generate a pair of RSA keys in C#, create a new instance of the RSACryptoServiceProvider class that takes the size of the key.

Here’s how it works:

  • Creating a new instance rsa of RSACryptoServiceProvider using new RSACryptoServiceProvider(keySize) generates both the public and private keys.

  • These keys are based on the specified keySize (e.g., 2048 bits or 4096 bits).

  • The keys are stored within the internal object and are accessible through the RSACryptoServiceProvider methods, such as ToXmlString().

    • ToXmlString(false): This exports only the public key in XML format. This public key can be shared with others for encryption purposes.

    • ToXmlString(true): This exports both the public and private keys in XML format. The private key should be kept secure and used for decryption.

The key size determines the strength of the encryption.

Let’s look at the simple code to generate RSA keys in C#:

using System;
using System.Security.Cryptography;
public class RSAExample
{
private RSACryptoServiceProvider rsa;
public RSAExample(int keySize = 2048)
{
rsa = new RSACryptoServiceProvider(keySize); // Generate RSA key pair of specified key size
}
public string GetPublicKey()
{
return rsa.ToXmlString(false); // Export only the public key
}
public string GetPrivateKey()
{
return rsa.ToXmlString(true); // Export both public and private keys
}
}
Generating RSA keys in C#

2. Encrypting data

To encrypt data with RSA, we need the public key. The public key is used to secure data, ensuring that only the owner of the private key can decrypt it. There are two main steps for encrypting the data:

  1. Convert the plaintext message to bytes. Encoding methods like UTF-8 or ASCII can be used for this.

  2. Use rsa.Encrypt to encrypt the byte array with the public key.

Let’s look at the simple code to encrypt data using the public key in C#:

public byte[] Encrypt(string plainText)
{
byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return rsa.Encrypt(plainBytes, false);
}
Encrypting the data in C#

The rsa.Encrypt method in C# has a parameter called fOAEP, which determines whether to use the OAEP padding scheme or not. If the value is:

  • false: This uses PKCS#1 v1.5 padding, the traditional padding scheme for RSA encryption.

  • true: This uses OAEP (Optimal Asymmetric Encryption Padding), a more secure padding scheme for RSA encryption.

3. Decrypting data

To decrypt data, the private key is required. This ensures that only the intended recipient can read the encrypted message. There are two steps involved in decrypting the data:

  1. Use rsa.Decrypt with the private key to decrypt the encrypted byte array.

  2. Convert the decrypted byte array back to a readable string.

Let’s look at the simple code to decrypt data using the private key in C#:

public string Decrypt(byte[] encryptedData)
{
byte[] decryptedBytes = rsa.Decrypt(encryptedData, false);
return System.Text.Encoding.UTF8.GetString(decryptedBytes);
}
Decrypting the data in C#

In the rsa.Decrypt method, the second parameter, fOAEP, behaves the same way as in the Encrypt method. It specifies whether to use the OAEP padding scheme for decryption.

Example

Now that we have individual pieces, let’s look at a simple code example to see RSA encryption and decryption in action in C#. Here, we’ll perform the following steps:

  • Create a simple string message.

  • Generate the RSA keys.

  • Encrypt the message.

  • Decrypt the encrypted message.

Click "Run" to execute the code below.

Program.cs
RSAexample.cs
using System;
public class Program
{
public static void Main()
{
string message = "Hello, RSA encryption!";
// Step 1: Initialize RSA and generate keys
RSAExample rsaExample = new RSAExample();
string publicKey = rsaExample.GetPublicKey();
string privateKey = rsaExample.GetPrivateKey();
// Display keys
Console.WriteLine("Public Key:\n" + publicKey);
Console.WriteLine("\nPrivate Key:\n" + privateKey);
// Step 2: Encrypt the message
byte[] encryptedData = rsaExample.Encrypt(message);
Console.WriteLine("\nEncrypted Data: " + Convert.ToBase64String(encryptedData));
// Step 3: Decrypt the message
rsaExample.LoadPrivateKey(privateKey); // Load the private key for decryption
string decryptedMessage = rsaExample.Decrypt(encryptedData);
Console.WriteLine("\nDecrypted Message: " + decryptedMessage);
}
}
Decrypting the data in C#

Now, let’s go over a few important pointers for RSA.

Important notes for RSA

  • In real-world applications, make sure to store private keys securely. Anyone with access to the private key can decrypt sensitive information.

  • RSA has size limitations, so it’s often used to encrypt smaller pieces of data, like a password or another encryption key.

  • RSA is slow for large data. In practice, RSA is often used to securely share a symmetric key, which is then used for fast encryption of the actual data.

That’s about learning how to use RSA to encrypt and decrypt data in C#. RSA is an important tool in secure communications, allowing sensitive information to be shared safely across the internet. With this understanding, you’re better equipped to keep data secure and protect privacy. Happy coding, and keep those secrets safe!

For a deeper understanding of cryptography, have a look at the “Everyday Cryptography” course.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What is RSA encryption and decryption method?

RSA encryption and decryption is an asymmetric cryptographic method that uses two keys:

  1. A public key for encryption (shared openly).
  2. A private key for decryption (kept secret).

This approach ensures that only the private key owner can decrypt messages encrypted with the public key, making RSA a cornerstone for secure communications like online banking and digital signatures.


What is the formula for encryption and decryption in RSA?

In RSA, the encryption and decryption formulas are based on modular exponentiation:

  • Encryption: Ciphertext = MemodNM^{e} \mod  N. Here, MM is the plaintext message, ee is the public exponent, and NN is the product of two large prime numbers.

  • Decryption: Plaintext = CdmodNC^{d} \mod N, where CC is the ciphertext, dd is the private exponent, and NN is the same modulus used in encryption.

The security of RSA relies on the difficulty of factoring NN into its prime factors.


How many keys are in RSA encryption?

RSA encryption uses two keys:

  • Public key: It is used to encrypt data; it can be shared openly.
  • Private key: It is used to decrypt data; it must be kept secure by the owner.

This two-key system is what makes RSA an asymmetric encryption method, providing both security and privacy.


Is RSA symmetric or asymmetric?

RSA is an asymmetric encryption method. This is because it uses two different keys: a public key for encryption and a private key for decryption. This differs from symmetric encryption, which uses the same key for both encryption and decryption.

For an introduction to the two techniques, have a look at “Symmetric vs. asymmetric encryption”.


Is RSA still used?

Yes, RSA is still widely used today, especially for secure data transmission, digital signatures, and establishing encrypted connections. However, due to advances in computing and the demand for stronger security, it’s often combined with other algorithms (like AES) in hybrid encryption systems. RSA remains a crucial part of many encryption protocols, including SSL/TLS for secure web browsing.


Where is encryption used in real life?

Encryption is essential for securing sensitive data in many areas:

  1. Banking and E-commerce: Protects financial transactions and personal info.
  2. Messaging: End-to-end encryption in apps like WhatsApp ensures message privacy.
  3. Health care: Secures patient records for privacy compliance.
  4. Email and Wi-Fi: Protects against unauthorized access.
  5. Cloud storage: Keeps stored data private.
  6. Digital signatures: Verifies document authenticity.

Encryption is very important for privacy and security in digital communication and storage.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved