使用来自 X509 证书 c++ 的 public 密钥进行 RSA public 加密

RSA public encryption using public key from X509 certificate c++

任务是使用位于 .crt 文件 - X509 证书文件中的 RSA public 密钥加密一些消息。

由于以下问题,我成功获取了证书信息,但找不到任何问题如何使用 x 中的 public 密钥使用 RSA 算法加密消息。

当我尝试用密钥数据创建 BIO 缓冲区并使用 PEM_read_bio_RSA_PUBKEY 函数将密钥写入 RSA 结构时它 returns 一个错误 "error:0906D06C:PEM routines:PEM_read_bio:no start line" 很清楚为什么会出现但不清楚如何正确解决。我如何在不创建另一个缓冲区并使用 "-----BEGIN RSA PUBLIC KEY-----" 和 [= 手动添加行的情况下进行加密有什么问题? 23=]"-----结束 RSA PUBLIC 密钥-----"?

这是我的代码:

unsigned char message[] = "Hello cryptographic world!";
unsigned char *encrypted_text;

int CyferWithHostKeyPub()
{
    ERR_load_crypto_strings();

    int res_length = 0;

    RSA *public_key;
    X509 *x;
    BIO *fp = BIO_new_file("cert.crt", "r");

    if (!fp)
    {
        printf("\nCan't open file.\n");
        return -1;
    }

    x = PEM_read_bio_X509(fp, 0, 0, NULL);

    if (!x) {
        printf("%s\n", ERR_error_string(ERR_get_error(), NULL));
        return 1;
    }

    BIO *membuf = BIO_new_mem_buf((void*)x->cert_info->key->public_key->data, x->cert_info->key->public_key->length);

    public_key = PEM_read_bio_RSA_PUBKEY(membuf, &public_key, NULL, NULL);
    if (!public_key) {
        printf("%s\n", ERR_error_string(ERR_get_error(), NULL));
        return 1;
    }

    int encrypted_length = RSA_size(public_key);
    encrypted_text = new unsigned char[ encrypted_length ];
    RSA_public_encrypt(sizeof(message), message, encrypted_text, public_key, RSA_PKCS1_PADDING);

    RSA_free(public_key);
    X509_free(x);
    BIO_free(membuf);
    BIO_free(fp);

    return encrypted_length;
}

那么,我怎样才能正确地做到这一点?谢谢!

使用X509_get_pubkey() 函数获取对X509 结构中包含的EVP_PKEY 结构的引用。然后你可以使用 EVP_PKEY_get1_RSA() 来获取对 RSA 结构的引用。

有关详细信息,请参阅这些手册页:

https://www.openssl.org/docs/man1.1.0/crypto/X509_get_pubkey.html https://www.openssl.org/docs/man1.1.0/crypto/EVP_PKEY_get1_RSA.html