首页 文章

在C#中解密加密RSA密文会导致异常

提问于
浏览
0

我使用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 . 之后,我通过公钥加密明文,并将私钥和密码作为base64编码的字符串保存在两个单独的文件中 .

现在来C# . 我正在读取base64字符串,解码它们并通过AsnParser加载它们,这似乎加载得很好 . 然后我打电话给 Decrypt . C# 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: Error occurred while decoding OAEP padding. 如果我通过 fOAEP = false 然后我得到 CryptographicException: The parameter is incorrect.

为什么我在尝试解密加密密文时会在C#中出现异常?

1 回答

  • 1

    ...当我尝试解密时,我收到异常错误:CryptographicException:解码OAEP填充时发生错误 . 如果我为fOAEP bool传递true,如果我将false传递给它,我会得到CryptographicException:参数不正确 .

    你遇到的问题与Encrypt and Decrypt a message using raw RSA algorithim in Crypto++?How to sync Crypto++ RSA with C# RSA crypto service provider?一样__161633_计划一定是我们这个月...

    在等式的加密一侧,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与PKCS#1.5填充或OAEP填充:

    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 wiki在RSA CryptographyRSA 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#中执行Raw RSA,您需要获取BigInteger类并手动应用反函数 .

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

相关问题