I'm making a program that has a client and server, and to send data from the client to the server it uses encryption. The data is encrypted with a key and the key gets encrypted with the server's public RSA key, but the server fails to decrypt the key giving me the message Invalid public key ciphertext, cannot decrypt
but sometimes it does work. The RSA keys are saved as plain text and sent to the client on request (public key only). The private key is used only by the server.
To encrypt the key the client does the following:
Botan::AutoSeeded_RNG rng;
Botan::DataSource_Memory DSMPublicServer(serverPublicKey); // serverPublicKey = key from server
Botan::X509_PublicKey *X509Key_publicServer = Botan::X509::load_key(DSMPublicServer); // Load the key
std::unique_ptr <Botan::Public_Key> publicKeyServer(X509Key_publicServer); // The key used to encrypt
Botan::PK_Encryptor_EME encKey(*publicKeyServer, rng, "EME-PKCS1-v1_5");
std::vector <uint8_t> encKey_t = encKey.encrypt(key, rng);
And the server tries to decrypt it as follows:
Botan::AutoSeeded_RNG rngTest;
Botan::DataSource_Memory DSMPrivate(this->myKeyString); // myKeyString = server private key
Botan::PKCS8_PrivateKey *PKCS8Key_Private = Botan::PKCS8::load_key(DSMPrivate, rngTest) // Load the key
std::unique_ptr <Botan::Private_Key> privateKey(PKCS8Key_Private);
Botan::PK_Decryptor_EME dec(*privateKey, rngTest, "EME-PKCS1-v1_5"); // Decryptor
std::vector <uint8_t> dec_t = Botan::unlock(dec.decrypt(this->key)); // This throws errors
this->key.clear(); // The key used on the rest of the data
std::copy(dec_t.begin(), dec_t.end(), std::back_inserter(this->key)); // Put the decrypted key back
If I test this on the server with some data it works fine, but it seems that either data is lost during transmission, but it uses TCP so that should not be it or that the encryption does not run properly every time since it does work sometimes. Is there a way to validate the encrypted data so I can test it before sending or how could I fix the issue?