我们如何使用libgcrypt为RSA加密添加pkcs1填充?

时间:2019-09-05 17:24:41

标签: rsa libgcrypt

我正在尝试使用libgcrypt使用RSA公钥加密字符串。它的selftest_encr_1024示例显示了大多数情况,但没有显示如何处理填充。这是我编写的尝试添加PKCS#1类型2填充的代码,但未添加任何填充。我想念什么或做错什么了?

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

1 个答案:

答案 0 :(得分:0)

好吧,我不明白您如何准确地检查PKCS#1填充是否添加到纯文本中。填充过程在加密之前执行,结果数据在加密之后获得。因此无法找出填充。

最后,RSA实现使用_gcry_pk_util_data_to_mpi函数从表达式中提取数据,并且经过全面测试以支持PKCS#1填充。