I am trying to encrypt a string with RSA public key using libgcrypt. Its selftest_encr_1024 sample shows most of the things, but it does not show us how to handle padding. This is the code I wrote trying to add PKCS#1 type 2 padding, but it does not add any padding. What am I missing or doing wrong?
nobu
string rsaEncrypt(const string& pubKey, const string& inText)
{
string outText;
gcry_sexp_t pkey = NULL;
gcry_error_t err = gcry_sexp_sscan (&pkey, NULL, pubKey.c_str(), pubKey.length());
if (!err) {
gcry_mpi_t msg = NULL;
size_t nScanned;
err = gcry_mpi_scan (&msg, GCRYMPI_FMT_STD, inText.c_str(), inText.length(), &nScanned);
if (!err) {
gcry_sexp_t plain = NULL;
err = gcry_sexp_build (&plain, NULL, "(data (flags pkcs1) (value %m))", msg);
if (!err) {
gcry_sexp_t encr = NULL;
err = gcry_pk_encrypt (&encr, plain, pkey);
if (!err) {
gcry_mpi_t encrmsg = gcry_sexp_nth_mpi(encr, 0, GCRYMPI_FMT_USG);
vector<char> buff(inText.length() * 2);
size_t nWritten;
err = gcry_mpi_print(GCRYMPI_FMT_STD, (unsigned char*) &buff[0], buff.size(), &nWritten, encrmsg);
if (!err) {
Web::Base64::encode(outText, &buff[0], nWritten);
}
gcry_sexp_release(encr); encr = NULL;
}
}
}
gcry_sexp_release(pkey); pkey = NULL;
}
if (err) {
std::cout << gcry_strerror(err) << std::endl;
}
return outText;
}