使用 X509 证书 c++ 中的公钥进行 RSA 公共加密

问题描述 投票:0回答:1

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

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

当我尝试使用密钥数据创建 BIO 缓冲区并使用 PEM_read_bio_RSA_PUBKEY 函数将密钥写入 RSA 结构时,它返回错误 “错误:0906D06C:PEM 例程:PEM_read_bio:无起始行” 这很清楚为什么出现但不清楚如何正确解决。有任何问题吗,我如何在不创建另一个缓冲区并使用 “-----BEGIN RSA PUBLIC KEY-----””-----END RSA PUBLIC KEY--- 手动添加行的情况下进行加密--“

这是我这项工作的代码:

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

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

c++ encryption openssl certificate rsa
1个回答
3
投票

使用

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

请参阅这些手册页以获取更多信息:

https://www.openssl.org/docs/man1.1.1/man3/X509_get_pubkey.html

https://www.openssl.org/docs/man3.0/man3/EVP_PKEY_get1_RSA.html

© www.soinside.com 2019 - 2024. All rights reserved.