公钥RSA解密(C#)

公钥RSA解密(C#),c#,encryption,cryptography,rsa,public-key,C#,Encryption,Cryptography,Rsa,Public Key,我的问题如下: 我收到一个带有RSA私钥的加密字符串。我有解密它的公钥和下一个方法(基于以下建议) 和msdn): 如果调用rsaCryptoServiceProvider.Decrypt,最后一个参数为TRUE,则消息为: System.Security.Cryptography.CryptographyException:解码OAEP填充时出错。 位于System.Security.Cryptography.RSACryptServiceProvider.DecryptKey(SafeKey

我的问题如下:

我收到一个带有RSA私钥的加密字符串。我有解密它的公钥和下一个方法(基于以下建议) 和msdn):

如果调用rsaCryptoServiceProvider.Decrypt,最后一个参数为TRUE,则消息为:

System.Security.Cryptography.CryptographyException:解码OAEP填充时出错。
位于System.Security.Cryptography.RSACryptServiceProvider.DecryptKey(SafeKeyHandle pKeyContext,字节[]pbEncryptedKey,Int32 cbEncryptedKey,布尔值fOAEP,ObjectHandleOnStack ohRetDecryptedKey)
在System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(字节[]rgb,布尔值fOAEP)
在控制台Application 1.Program.DecryptString(字符串inputString、Int32 dwKeySize、字符串xmlString)
我尝试通过以下方式加载公钥替换第一行(实例化提供程序):

但同样的错误也会发生


关于如何解决此问题,您有什么建议吗?

您确实需要使用公钥解密吗?还是需要使用公钥进行验证?您正在解密的信息是什么?这听起来像是XY问题。你需要一个私钥来解密。。。您只能用公钥进行加密和签名验证。@vojta真的不能用公钥解密吗?我已经用java测试了这段代码(当“key”是公钥时):final byte[]bytes=Base64.decodeBase64(text);final Cipher Cipher=Cipher.getInstance(“RSA”);Cipher.init(Cipher.DECRYPT_MODE,key);decryptedText=Cipher.doFinal(bytes);它可以工作..但我需要在C#中完成。@LukePark是的,我需要用“xmlString”中的公钥解密“inputString”(在文章中提到过)(在文章中也提到过)你真的需要用公钥解密吗?还是需要用公钥验证?你解密的信息是什么?这听起来像是XY问题。你需要一个私钥来解密…你只能用公钥进行加密和签名验证。@vojta真的不能用公钥解密吗?我有测试用java编写此代码(当“key”是公钥时):最终字节[]字节=Base64.decodeBase64(文本);final Cipher=Cipher.getInstance(“RSA”);cipher.init(cipher.DECRYPT_模式,密钥);decryptedText=cipher.doFinal(字节);而且很有效。。但是我需要在C#中完成它。@LukePark是的,我需要用“xmlString”中的公钥解密“inputString”(在文章中提到过)
public static string DecryptString(string inputString, int dwKeySize, string xmlString){
    try
    {               
        RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(dwKeySize);
        rsaCryptoServiceProvider.FromXmlString(xmlString);

        int base64BlockSize = ((dwKeySize / 8) % 3 != 0) ?
          (((dwKeySize / 8) / 3) * 4) + 4 : ((dwKeySize / 8) / 3) * 4;
        int iterations = inputString.Length / base64BlockSize;
        ArrayList arrayList = new ArrayList();
        for (int i = 0; i < iterations; i++)
        {
            byte[] encryptedBytes = Convert.FromBase64String(inputString.Substring(base64BlockSize * i, base64BlockSize));
            Array.Reverse(encryptedBytes);                    
            arrayList.AddRange(rsaCryptoServiceProvider.Decrypt(encryptedBytes, false));
        }
        return Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[]);
    }
    catch (Exception exp)
    {
        Console.WriteLine(exp.ToString());                
        throw exp;
    }
}
X509Certificate2 Cert;
Cert = new X509Certificate2(@"C:\Users\user1\Documents\seggar.der"); 
RSACryptoServiceProvider rsaCryptoServiceProvider = new RSACryptoServiceProvider(2048);
rsaCryptoServiceProvider = (RSACryptoServiceProvider)Cert.PublicKey.Key;