C# RSA加密/解密抛出异常

发布于 2024-08-09 15:05:53 字数 884 浏览 4 评论 0原文

我正在尝试设置一个简单的服务器端 RSA 加密,对要在客户端解密的一小块信息进行加密。作为概念证明,我写了几行来确保可以从 xml 加载公钥和私钥。然而,我正在努力让最简单的东西在我的机器上工作:

  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);

最后一次调用 Decrypt 抛出 CryptographicException 并显示消息“解码 OAEP 填充时发生错误。”。我一定在这里遗漏了一些完全明显的东西。我是否需要对 rsa 实例进行更多设置,或者可能需要初始 rsa 播种实例?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晒暮凉 2024-08-16 15:05:53

您应该使用公钥进行加密,使用私钥进行解密。
看一下这里:RSACryptoServiceProvider 使用公钥解密< /a>

现在,让我们回到
RSACryptoServiceProvider 类。这
加密方法仅使用加密
公钥和解密方法
仅使用私钥解密。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文