C# RSA Encrypting text using a given PKCS#1 public key
<p>I am trying to write a function the receives a string to encode and a public key as base64 encoded string in PKCS#1 format, and returns an encoded string.</p>

<pre><code>    public static string EncryptRsa(string stringPublicKey, string stringDataToEncrypt)
{
    byte[] publicKey = Convert.FromBase64String(stringPublicKey);

    // Code to create an RSACryptoServiceProvider with the public key
    // var rsa = new RSACryptoServiceProvider(??)

    byte[] dataToEncrypt = Encoding.UTF8.GetBytes(stringDataToEncrypt);
    var encryptedData = rsa.Encrypt(dataToEncrypt, true);
    return Convert.ToBase64String(encryptedData);
}
</code></pre>

<p>I've seen many questions and answers over past few day about how to encrypt using the RSA algorithm, but haven't found information on how to create a RSACryptoServiceProvider when I already have an existing key (specifically, in a PKCS#1 format), only how to generate a key pair.</p>

<p>for example: given the following string, how would I encrypt data using RSA encryption?</p>

<p>-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqGKukO1De7zhZj6+H0qtjTkVxwTCpvKe4eCZ0
FPqri0cb2JZfXJ/DgYSF6vUpwmJG8wVQZKjeGcjDOL5UlsuusFncCzWBQ7RKNUSesmQRMSGkVb1/
3j+skZ6UtW+5u09lHNsj6tQ51s1SPrCBkedbNf0Tp0GbMJDyR4e9T04ZZwIDAQAB</p>

<p>-----END PUBLIC KEY----- </p>

<p>Thanks!!</p>