Introduction

RSA algorithm is an asymmetric cryptography algorithm. Asymmetric actually means that it works on two different keys, i.e., public key and private key. As the name describes, the public key is given to everyone, and the private key is kept private.

In the below sample, I have used the BouncyCastle package for RSA encryption and decryption.

Notes

Step 1. First, you need to install the BouncyCastle package. You can do this via NuGet.

NuGet

Step 2. Import the required package into the service.

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;

Encryption Complete method

        public  string EncryptRSA(string plaintext)
        {
            string encryptedText = "";
            byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);

            // Load the public key from a PEM string or file
            string publicKeyPem = @""; // Replace your public key here
            AsymmetricKeyParameter publicKey;
            using (var reader = new StringReader(publicKeyPem))
            {
                PemReader pemReader = new PemReader(reader);
                publicKey = (AsymmetricKeyParameter)pemReader.ReadObject();
            }
            // Initialize the RSA engine for encryption with the public key
            IAsymmetricBlockCipher rsaEngine = new Pkcs1Encoding(new RsaEngine());
            rsaEngine.Init(true, publicKey); // true for encryption
            // Encrypt the data
            byte[] encryptedData = rsaEngine.ProcessBlock(plaintextBytes, 0, plaintextBytes.Length);
            // Convert the encrypted data to a Base64 string for easy transmission/storage
            encryptedText = Convert.ToBase64String(encryptedData);
            return encryptedText;
        }

Breakdown of the encryption method

Step 1

plaintextBytes: The input string is converted to a byte array using UTF-8 encoding. This byte array represents the data to be encrypted.

byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);

Step 2

using (var reader = new StringReader(publicKeyPem))
{
    PemReader pemReader = new PemReader(reader);
    publicKey = (AsymmetricKeyParameter)pemReader.ReadObject();
}

Step 3

IAsymmetricBlockCipher rsaEngine = new Pkcs1Encoding(new RsaEngine());
rsaEngine.Init(true, publicKey); // true for encryption

Step 4

byte[] encryptedData = rsaEngine.ProcessBlock(plaintextBytes, 0, plaintextBytes.Length);
encryptedText = Convert.ToBase64String(encryptedData);

Output Sample for RSA Encryption

RSA

Decryption Complete method

        public string DecryptRSA(string encryptedText)
        {
            string decryptedText = "";
            try
            {
                
                string pemPrivateKey = @""; // Replace your private key here
                RsaPrivateCrtKeyParameters keyPair;
                using (var reader = new StringReader(pemPrivateKey))
                {
                    keyPair = (RsaPrivateCrtKeyParameters)new PemReader(reader).ReadObject();
                }
                var rsaParams = DotNetUtilities.ToRSAParameters(keyPair);
                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.ImportParameters(rsaParams);
                    // Convert encrypted text from Base64
                    byte[] encryptedData = Convert.FromBase64String(encryptedText);
                    // Decrypt the data
                    byte[] decryptedData = rsa.Decrypt(encryptedData, RSAEncryptionPadding.Pkcs1);
                    return Encoding.UTF8.GetString(decryptedData);
                }           
            }            
            catch { }
            return decryptedText;
        }

Output sample for decryption

Output

Summary

This encryption method ensures that the plaintext is securely transformed into an encrypted format using the RSA algorithm, which can then only be decrypted by the corresponding private key.