在C#中解密Crypto++ RSA密文导致异常

Decrypting Crypto++ RSA cipher text in C# causes exception

我已经使用 Crypto++ 在 C++ 中编写了 3 个函数来生成密钥对、加密和解密字符串。 Crypto++ side:

//Decode public key
RSA::PublicKey pbKeyDecoded;
StringSource ss2(publicKey, true, new Base64Decoder);
pbKeyDecoded.BERDecode(ss2);

Integer m = Integer((const byte*)plaintext.data(), plaintext.size());
Integer crypted = pbKeyDecoded.ApplyFunction(m);
...

我做的是,生成密钥,DER编码,然后编码成Base64。之后,我通过 public 密钥对明文进行加密,并将私钥和密码作为 base64 编码字符串保存在两个单独的文件中。

现在是 C#。我正在读取 base64 字符串,对其进行解码并通过 AsnParser 加载它们,这似乎加载得很好。然后我调用 DecryptC# side:

AsnKeyParser keyParser = new AsnKeyParser("rsa-public.der");
RSAParameters publicKey = keyParser.ParseRSAPublicKey();

CspParameters csp = new CspParameters;
csp.KeyContainerName = "RSA Test (OK to Delete)";    
csp.ProviderType = PROV_RSA_FULL;    // 1
csp.KeyNumber = AT_KEYEXCHANGE;      // 1

RSACryptoServiceProvider rsp = new RSACryptoServiceProvider(csp);
rsp.PersistKeyInCsp = false;
rsp.ImportParameters(privateKey);

//Causes exception here..
var data = rsp.Decrypt(cipherArr, true);
...

但是当我尝试使用 fOAEP = true 对其进行解密时出现异常错误:CryptographicException:解码 OAEP 填充时发生错误。 如果我通过 fOAEP = false 然后我得到 CryptographicException: The parameter is incorrect.

为什么我在尝试解密 Crypto++ 密文时在 C# 中遇到异常?

... I'm getting exception error when I try to decrypt it: CryptographicException: Error occurred while decoding OAEP padding. That's if I pass true for the fOAEP bool, if I pass false to it I get CryptographicException: The parameter is incorrect.

你和 and 遇到了同样的问题"Raw RSA"一定是我们的月...

在等式的 Crypto++ 方面,you are performing raw RSA。您只是在应用前向函数,即求幂,而没有格式化消息:

//Decode public key
RSA::PublicKey pbKeyDecoded;
StringSource ss2(publicKey, true, new Base64Decoder);
pbKeyDecoded.BERDecode(ss2);

Integer m = Integer((const byte*)plaintext.data(), plaintext.size());
Integer crypted = pbKeyDecoded.ApplyFunction(m);
...

在 C# 方面,you are performing RSA decryption 使用带有 PKCS #1.5 填充或 OAEP 填充的 PKCS #1:

RSACryptoServiceProvider rsp = new RSACryptoServiceProvider(csp);
rsp.PersistKeyInCsp = false;
rsp.ImportParameters(privateKey);

//Causes exception here..
var data = rsp.Decrypt(cipherArr, true);

我不清楚您的代码的 C# 版本是否可以执行 OAEP 填充,因为它需要特定版本的 CLR。您可能只有 PKCS 填充可用。


我相信你有两个选择。首先,您可以在 Crypto++ 中使用标准的 RSA 加密方法。 Crypto++ 维基将它们列在 RSA Cryptography and RSA Encryption Schemes:

typedef RSAES<PKCS1v15>::Decryptor RSAES_PKCS1v15_Decryptor;
typedef RSAES<PKCS1v15>::Encryptor RSAES_PKCS1v15_Encryptor;

typedef RSAES<OAEP<SHA> >::Decryptor RSAES_OAEP_SHA_Decryptor;
typedef RSAES<OAEP<SHA> >::Encryptor RSAES_OAEP_SHA_Encryptor;

其次,您需要在 C# 中执行 Raw RSA。要在 C# 中执行原始 RSA,您需要获取一个 BigInteger class 并手动应用反函数。

我鼓励您使用带有 OAEP 填充的 RSA 加密。如果 OAEP 不可用,则第二个选择是 PKCS 填充。最后,如果你只有 Raw RSA,那么我会寻找另一个加密系统,因为 Raw RSA 太不安全了。