rsa encrypt string in csharp

Here's an example of how to RSA encrypt a string in C#:

main.cs
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public static string RSAEncrypt(string plaintext, string publicKey)
{
    byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);

    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {
        rsa.FromXmlString(publicKey);
        byte[] encryptedBytes = rsa.Encrypt(plaintextBytes, true);

        return Convert.ToBase64String(encryptedBytes);
    }
}
470 chars
18 lines

This code takes the plaintext string and a public key as input and returns the encrypted string. The plaintext is first converted to a UTF8 byte array. The RSACryptoServiceProvider class is used to encrypt the byte array with the provided public key using the Encrypt method. The resulting byte array is then converted to encoded base 64 string format using the Convert.ToBase64String method and returned as the encrypted string.

gistlibby LogSnag