Search code examples
c#c++encryptioncryptographycrypto++

How to sync Crypto++ RSA with C# RSA crypto service provider?


I crypt a string text with use of Crypto++, but when want to decrypt it by C# RSA crypto service provider I have an exception.

My code produces same cipher string when encrypt a same string with constant public key by Crypto++ in several time, while there are different results (cipher string) with use of C# RSA crypto service provider.

Is main reason of this problem (run-time error) related to different type of RSA?

My encryption code using Crypto++ is in below:

string message((char*)"hi", 2);
Integer messageInteger((const byte *)message.data(), message.size());
Integer cipherMessage = hostPublicKey.ApplyFunction(messageInteger);
size_t len = cipherMessage.MinEncodedSize();
string str;
str.resize(len);
cipherMessage.Encode((byte *)str.data(), str.size(), Integer::UNSIGNED);

And the Crypto++ decryption code is:

Integer cipherMessage1((byte *)str.data(), str.size());
int size1 = cipherMessage1.ByteCount();
Integer plainInteger = privateKey.CalculateInverse(prng, cipherMessage1);
string recovered;
size_t req = plainInteger.MinEncodedSize();
recovered.resize(req);
plainInteger.Encode((byte *)recovered.data(), recovered.size());

the encryption and decryption operations are done well in same side, but there is mentioned problem in decryption operation in other side.


Solution

  • for encryption use this code:

        RSAES_OAEP_SHA_Encryptor e(publicKey);
        string cipher;
        StringSource stringSource(message, true,
            new PK_EncryptorFilter(rng, e,
                new StringSink(cipher)
            )
        );
    

    and decryption:

        RSAES_OAEP_SHA_Decryptor d(privateKey);
        StringSource stringSource(cipher, true,
            new PK_DecryptorFilter(rng, d,
                new StringSink(recovered)
            )
        );