Back to all posts
C#.NETSecurity

How to RSA Encrypt Decrypt Data – C#

SathishApril 19, 2010
How to RSA Encrypt Decrypt Data – C#

RSA is an asymmetric encryption algorithm that uses a pair of keys: a public key for encryption and a private key for decryption.

RSA Encryption and Decryption in C#

csharp
using System;
using System.Security.Cryptography;
using System.Text;

public class RSAEncryption
{
    private RSACryptoServiceProvider rsa;
    
    public RSAEncryption()
    {
        rsa = new RSACryptoServiceProvider(2048);
    }
    
    public string GetPublicKey()
    {
        return rsa.ToXmlString(false);
    }
    
    public string GetPrivateKey()
    {
        return rsa.ToXmlString(true);
    }
    
    public byte[] Encrypt(string plainText, string publicKey)
    {
        using (RSACryptoServiceProvider rsaEncrypt = new RSACryptoServiceProvider())
        {
            rsaEncrypt.FromXmlString(publicKey);
            byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
            return rsaEncrypt.Encrypt(plainBytes, false);
        }
    }
    
    public string Decrypt(byte[] cipherBytes, string privateKey)
    {
        using (RSACryptoServiceProvider rsaDecrypt = new RSACryptoServiceProvider())
        {
            rsaDecrypt.FromXmlString(privateKey);
            byte[] plainBytes = rsaDecrypt.Decrypt(cipherBytes, false);
            return Encoding.UTF8.GetString(plainBytes);
        }
    }
}

Usage Example

csharp
RSAEncryption rsa = new RSAEncryption();
string publicKey = rsa.GetPublicKey();
string privateKey = rsa.GetPrivateKey();

byte[] encrypted = rsa.Encrypt("Hello, World!", publicKey);
string decrypted = rsa.Decrypt(encrypted, privateKey);
0claps
Share this post

Comments

Protected by reCAPTCHA v3

No comments yet. Be the first to comment.