cryptography - 在 private.pem 文件中,PEM_write_PrivateKey() 函数没有存储 RSA private 密钥

  显示原文与译文双语对照的内容
0 0

这是我使用的代码通过引用栈溢出的问题由其他用户从这里问道。 但是当我尝试使用 PEM_write_PrivateKey() 函数将 private 键写入文件时。 它不是这样做的。 这个函数调用后,控制台屏幕会自动关闭。 private.pem 文件不包含任何内容。


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
#include <openssl/objects.h>
#include <openssl/err.h>
#include <openssl/x509.h>

int main()
{

//
//Local variables definition
//
EVP_PKEY_CTX *evp_ctx = NULL;
EVP_PKEY *ppkey = NULL;
FILE *fpPri = NULL;
FILE *fpPub = NULL;
int retValue = 1;

for (;;)
{
//
//Function allocates public key algorithm context using the algorithm
//specified by id
//
 evp_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
 if (NULL == evp_ctx)
 {
 printf("RSA Public key algorithm context is not allocatedn");
 break;
 }//if
 printf("RSA Public key algoritm context allocatedn");

//
//Function initializes a public key algorithm context using key pkey
//for a key genration operation
//
 retValue = EVP_PKEY_keygen_init(evp_ctx);
 if (1!= retValue)
 {
 printf("Initialization of public key alogorithm context failedn");
 break;
 }//if
 printf("Public key alogorithm context initializedn");

//
//Setting RSA key bit to 2048
//
 retValue = EVP_PKEY_CTX_set_rsa_keygen_bits(evp_ctx, 2048);
 if (1!= retValue)
 {
 printf("RSA key bits not set to 2048n");
 break;
 }//if
 printf("RSA key bits set to 2048n");

//
//Function performs a key generation operation
//
 retValue = EVP_PKEY_keygen(evp_ctx, &ppkey);
 if (1!= retValue)
 {
 printf("Key generation operation failedn");
 break;
 }//if
 printf("Key generated successfullyn");

//
//Creating a file to store RSA private key
//
 fpPri = fopen("./private.pem","w+");
 if (NULL == fpPri)
 {
 printf("File pointer of private.pem file is not openedn");
 break;
 }//if
 printf("File pointer or private.pem file openedn");

 retValue = PEM_write_PrivateKey(fpPri, ppkey, NULL, NULL, 0, 0, NULL);
 if (1!= retValue)
 {
 printf("Private key is not written to file private.pemn");
 break;
 }//if
 printf("Private key written to file private.pemn");

//
//Final break statement
//
 break;
}//for

//
//Releasing all the memory allocations and the handles
//

getchar();

return 0;
 }

时间: 原作者:

0 0

也许是因为你从未叫过 SSL_library_init() 。

另外,你的缓冲文件可能在程序退出之前没有被刷新。 在程序结束之前,你应该调用:

 
fflush(fpPri);

 
原作者:
...