C# RSA加密/解密抛出异常
我正在尝试设置一个简单的服务器端 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用公钥进行加密,使用私钥进行解密。
看一下这里:RSACryptoServiceProvider 使用公钥解密< /a>
You should use public key for encryption and private key for decryption.
Take a look here: RSACryptoServiceProvider decrypt with public key