C#RSA加密/解密引发异常 [英] C# RSA encrypt/decrypt throws exception
问题描述
我正在尝试为一小部分信息设置一个简单的服务器端RSA加密,该信息将在客户端进行解密.就像概念证明一样,我写了几行代码以确保可以从xml加载公钥和私钥.但是,我正在努力使最简单的东西也可以在我的机器上工作:
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);
最后一次对Decrypt的调用将引发CryptographicException,并显示消息解码OAEP填充时发生错误".我必须在这里遗漏一些显而易见的东西.我是否需要对rsa实例或初始rsa播种实例进行更多设置?
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?
推荐答案
您应使用公共密钥进行加密,并使用私钥进行解密. 在这里看看:使用公共密钥解密的RSACryptoServiceProvider
You should use public key for encryption and private key for decryption. Take a look here: RSACryptoServiceProvider decrypt with public key
现在,让我们回到 RSACryptoServiceProvider类.这 加密方法仅使用 公钥和Decrypt方法 仅使用私钥解密.
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.
这篇关于C#RSA加密/解密引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!