C# RSA encrypt/decrypt throws exception

ε祈祈猫儿з 提交于 2019-12-23 03:59:10

问题


I'm trying to set up a simple server side RSA encryption of a small chunk of info which is to be decrypted on the client side. Just as a proof of concept I wrote a few lines to ensure that the public and private key could be loaded from xml. However, I'm struggling to make even the most simple stuff work on my machine:

  byte[] bytes = Encoding.UTF8.GetBytes("Some text");
  bool fOAEP = true;

  // seeding a public and private key
  RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
  var publicKey = rsa.ToXmlString(false);
  var privateKey = rsa.ToXmlString(true);

  //server side
  RSACryptoServiceProvider rsaServer = new RSACryptoServiceProvider();
  rsaServer.FromXmlString(privateKey);
  var encrypted = rsaServer.Encrypt(bytes, fOAEP);

  //client side
  RSACryptoServiceProvider rsaClient = new RSACryptoServiceProvider();
  rsaClient.FromXmlString(publicKey);
  var decrypted = rsaClient.Decrypt(encrypted, fOAEP);

The last call to Decrypt throw a CryptographicException with the message "Error occurred while decoding OAEP padding.". I must be missing something totally obvious here. Do I need more setup of the rsa instances or maybe the initial rsa seeding instance?


回答1:


You should use public key for encryption and private key for decryption. Take a look here: RSACryptoServiceProvider decrypt with public key

Now, let's get back to the RSACryptoServiceProvider class. The Encrypt method ONLY encrypts using the public key and the Decrypt method only decrypts using the private key.



来源:https://stackoverflow.com/questions/1629992/c-sharp-rsa-encrypt-decrypt-throws-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!