简体   繁体   English

C#RSA加密/解密引发异常

[英]C# RSA encrypt/decrypt throws exception

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. 我正在尝试为一小部分信息设置一个简单的服务器端RSA加密,该信息将在客户端解密。 Just as a proof of concept I wrote a few lines to ensure that the public and private key could be loaded from xml. 正如概念证明一样,我写了几行代码以确保可以从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.". 最后一次对Decrypt的调用将引发CryptographicException,并显示消息“解码OAEP填充时发生错误”。 I must be missing something totally obvious here. 我必须在这里遗漏一些显而易见的东西。 Do I need more setup of the rsa instances or maybe the initial rsa seeding instance? 我是否需要对rsa实例或初始rsa播种实例进行更多设置?

You should use public key for encryption and private key for decryption. 您应使用公钥进行加密,并使用私钥进行解密。 Take a look here: RSACryptoServiceProvider decrypt with public key 在这里看看: RSACryptoServiceProvider用公共密钥解密

Now, let's get back to the RSACryptoServiceProvider class. 现在,让我们回到RSACryptoServiceProvider类。 The Encrypt method ONLY encrypts using the public key and the Decrypt method only decrypts using the private key. Encrypt方法仅使用公钥加密,而Decrypt方法仅使用私钥解密。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM