Harunobu Oyama
Harunobu Oyama

Reputation: 149

How can we add pkcs1 padding for RSA encryption using libgcrypt?

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;
}

Upvotes: 2

Views: 700

Answers (1)

Mostafa Barmshory
Mostafa Barmshory

Reputation: 2029

Well, I do not understand how exactly do you check if the PKCS#1 padding is added to plain text. The padding process is performed before encryption, and the result data is obtained after encryption. So it is not possible to find out the padding.

Finally, RSA implementation use _gcry_pk_util_data_to_mpi function to extract data from the expression, and it is fully tested to support PKCS#1 padding.

Upvotes: 0

Related Questions