任务是使用位于 .crt 文件 - X509 证书文件中的 RSA 公钥加密一些消息。
由于下面的问题,我成功地获得了证书信息,但是找不到如何使用 x 中的公钥使用 RSA 算法加密消息的任何问题。
当我尝试使用 key 数据创建 BIO 缓冲区并使用 PEM_read_bio_RSA_PUBKEY 函数将 key 写入 RSA 结构时,它返回错误 "error:0906D06C: PEM routines:PEM_read_bio:no start line" 清楚为什么会出现但不清楚如何正确解决。在不创建另一个缓冲区并使用 "-----BEGIN RSA PUBLIC KEY-----" 和 "----- 添加手动行的情况下如何进行加密有什么问题吗?结束RSA公钥-----”?
这是我完成这项工作的代码:
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
关于c++ - 使用来自 X509 证书 c++ 的公钥进行 RSA 公共(public)加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48951379/