EVP读取PEM私钥不能正常工作

当我运行以下代码生成密钥时,将其写入字符串,将其打印出来,将其读入密钥,然后再次打印,对OpenSSL_1_0_2e

 #include  #include  #include  #include  #include  #define RSA_KEYLEN 2048 int main() { // Key generation EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL); EVP_PKEY* key = NULL; EVP_PKEY_keygen_init(ctx); EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, RSA_KEYLEN); EVP_PKEY_keygen(ctx, &key); EVP_PKEY_CTX_free(ctx); // Serialize to string unsigned char* keyStr; BIO *bio = BIO_new(BIO_s_mem()); PEM_write_bio_PrivateKey(bio, key, NULL, NULL, 0, 0, NULL); int priKeyLen = BIO_pending(bio); keyStr = (unsigned char*)malloc(priKeyLen + 1); BIO_read(bio, keyStr, priKeyLen); keyStr[priKeyLen] = '\0'; BIO_free_all(bio); // Print the string printf("%s", keyStr); // Reset the key EVP_PKEY_free(key); key = NULL; // Read from string bio = BIO_new(BIO_s_mem()); BIO_write(bio, keyStr, priKeyLen); PEM_read_bio_PrivateKey(bio, &key, NULL, NULL); BIO_free_all(bio); // Free the string free(keyStr); // Serialize to string (again) bio = BIO_new(BIO_s_mem()); PEM_write_bio_PrivateKey(bio, key, NULL, NULL, 0, 0, NULL); priKeyLen = BIO_pending(bio); keyStr = (unsigned char*)malloc(priKeyLen + 1); BIO_read(bio, keyStr, priKeyLen); keyStr[priKeyLen] = '\0'; BIO_free_all(bio); // Print string printf("%s", keyStr); } 

在第二个输出中,私钥显然太短了。 我究竟做错了什么?

我特定问题的解决方案是我试图在EVP_PKEY上设置公钥和私钥,以为我需要加载它们以将其用作密钥对。 实际上,你只加载其中一个。 使用私钥,可以派生公钥。