title: C# - Encrypting and Decrypting Data using RSA
body: <p>I have the following code in C#:</p>
  
  <p><strong>Main Class</strong></p>
  
  <pre><code>X509Certificate2 cert = new X509Certificate2("C:/test.pfx", "hello", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
  
              Encryption enc = new Encryption();
              string encrypted = enc.Encrypt("hello there", cert);
              string decrypted = enc.Decrypt(encrypted, cert);
              Console.WriteLine("Encrypted Text: " + encrypted);
              Console.WriteLine("Decrypted Text: " + decrypted);
  </code></pre>
  
  <p><strong>Encryption Class</strong></p>
  
  <pre><code>public string Encrypt(string plainText, X509Certificate2 cert)
  {
      RSACryptoServiceProvider publicKey = (RSACryptoServiceProvider)cert.PublicKey.Key;
      byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
      byte[] encryptedBytes = publicKey.Encrypt(plainBytes, false);
      string encryptedText = encryptedBytes.ToString();
      return encryptedText;
  }
  
  public string Decrypt(string encryptedText, X509Certificate2 cert)
  {
      RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)cert.PrivateKey;
      byte[] encryptedBytes = Encoding.UTF8.GetBytes(encryptedText);
      byte[] decryptedBytes = privateKey.Decrypt(encryptedBytes, false);
      string decryptedText = decryptedBytes.ToString();
      return decryptedText;
  }
  </code></pre>
  
  <p>As you can see, in the main class I am importing a certificate.  Then I am creating an instance of the Encryption class.  Then I pass plaintext to the Encrypt method along with the certificate in order to get the encrypted text.  Afterwards, I pass the encrypted text to the Decrypt method to get the plaintext back.</p>
  
  <p>My problem is that the result of printing the encrypted text is System.[]Byte (if I comment out the decryption call).  If I do not comment out the decryption call, I get a Cryptographic Exception: Bad Data in the decryption method.</p>
  
  <p>I guess that the encryptedBytes array is not being converted correctly to string.  Furthermore, I am not sure if I am forming the RSAEncryptionProvider correctly.  How can I solve this please?</p>
  
  <p><strong>Update</strong></p>
  
  <p>I solved one issue. When converting from byte array to string, I had to use Encoding.UTF8.GetString(EncryptedBytes). The problem now is that the decrypt method is giving me another cryptographic exception (he data to be decrypted exceeds the maximum for this modulus of 128 bytes).</p>
  
  <p>Does anybody know why this is happening and how to solve it?</p>