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
- Key Size: The example uses a 2048-bit key, which is a common and secure size for RSA.
- Encoding: Data is encoded as UTF-8 before encryption and decoded back after decryption.
- Security: Always handle and store keys securely. Exposing private keys or mishandling encrypted data can compromise security.
Step 1. First, you need to install the BouncyCastle package. You can do this via 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



Join the conversation! Your thoughts help the community grow.