解码OAEP填充时发生RSACryptoServiceProvider错误

时间:2015-09-01 01:10:58

标签: c# wcf encryption rsa

我已经阅读了很多关于这个问题的文章,我似乎无法找到解决我的错误的答案。
我有WCF服务;我的应用程序发送生成的公共RSA密钥,服务返回一组用公钥加密的AES密钥+ IV,但是当我的应用程序尝试解密密钥时,我得到"解码OAEP填充时发生错误&# 34; (如果我将true传递给useOAEP)或"参数不正确" (如果我将false传递给useOAEP)。为简单起见,这是将整个代码放在一起使用,将异常处理放在一边:

public static string EncryptAES(byte[] aesKey, byte[] aesIV, string publicRSAKey)
{
    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {
        rsa.FromXmlString(publicRSAKey);
        byte[] encryptedKey = rsa.Encrypt(aesKey, true);
        byte[] encryptedIV = rsa.Encrypt(aesIV, true);
        return string.Format("{0}{1}{2}", Convert.ToBase64String(encryptedKey), "\n", Convert.ToBase64String(encryptedIV));
    }
}
public static byte[] Decrypt(string aesKeyorIV)
{
    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
    {
         byte[] buffer = Convert.FromBase64String(aesKeyorIV);
         rsa.FromXmlString(RSA_Private_Key);
         return rsa.Decrypt(buffer, true); //Exception thrown here
    }
}

(使用RSA_Private_Key)在静态构造函数中生成rsa.ToXmlString(true)publicRSAKey通过在静态构造函数中发送rsa.ToXmlString(false)来传递给服务 我尝试使用Encrypt/Decrypt(byte[], false),但它没有任何区别。我还尝试了Array.Reverse(encryptedKey)然后Array.Reverse(buffer)
私钥在设置后永远不会被发送/修改,因此不可能。我没有想法,调试WCF服务非常糟糕。

2 个答案:

答案 0 :(得分:2)

您所描述的问题可能是由使用不同的公钥私钥引起的。

如果使用相同的RSA提供程序实例生成公钥和公钥+私钥,则密钥将匹配。 e.g。

string publicRSAKey = null;
string publicPlusPrivateRSAKey = null;

using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
    publicRSAKey = rsa.ToXmlString(false);
    publicPlusPrivateRSAKey = rsa.ToXmlString(true);
}

如果您从RSA提供商的两个不同实例创建密钥,那么公钥和公钥+私钥将不匹配。 e.g。

string publicRSAKey = null;
string publicPlusPrivateRSAKey = null;

using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
    publicRSAKey = rsa.ToXmlString(false);
}

using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
    publicPlusPrivateRSAKey = rsa.ToXmlString(true);
}

当钥匙匹配时,我可以毫无问题地往返。当密钥不匹配时,我得到“解码OAEP填充时出错”。

您可以在运行时验证密钥是否匹配?

由于私钥也将包含公钥,您可以查看xml字符串形式中每个键变量的内容,特别是/ RSAKeyValue / Modulus和/ RSAKeyValue / Exponent的XML路径,因为这些应该匹配两个。

答案 1 :(得分:0)

I finally discovered where the bug was. My implementation was as follows, simplified:

  1. App creates public+private key and sends the public key to the service
  2. The service responds with the AES generated keys encrypted with the public key.
  3. The service then tried to decrypt the keys before raising the event to alert the app.

I changed my implementation such as:

  1. The service raised the event with the encrypted message
  2. The app decrypts the message with the private key.

Since I'm using one Visual Studio instance to debug the 2 processes (the service's and visual studio debugger's), I didn't realize that the private/public keys were different.

Thanks to @zespri for the testing ideas.