简体   繁体   中英

PEM_read_RSAPrivateKey: Getting RSA key public modulus and exponent

I'm using PEM_read_RSAPrivateKey function in this way:

void test(void)
{
    RSA * privateKey = NULL;
    FILE * fp;

    if(NULL != (fp= fopen("./my_file.key", "r")) )
    {
          privateKey=PEM_read_RSAPrivateKey(fp,NULL,NULL,NULL);
          if(privateKey==NULL)
          {
              printf("\n\tCould NOT read RSA private key file");
          }
          else
          {
              printf("\n\tRSA structure filled");
          }

         // This is working OK and privateKey is NOT NULL

    }
}

Then, I try to retrieve modulus and public exponent to fill them into a personal structure:

struct
{
    unsigned char   modulus[256];
    unsigned char   pub_exp[8];
} s;

But all accesses I tried (I tried a lot) to privateKey->n will result in a segmentation fault.

for example:

unsigned char modulus [2048];
unsigned char exp[2048];
BN_bn2bin(privateKey->n, modulus);  // Segmentation fault results from this call

So my question is: how to copy modulus or public exponent from RSA structure to my structure "s" fields?

May someone help about this? Many thanks, Regards,

Sylvain

how to copy modulus or public exponent from RSA structure

int req = BN_num_bytes(rsa->n);
assert(rc > 0);

unsigned char* buff = malloc(req);
assert(buff != NULL);

int rc = BN_bn2bin(rsa->n, buff);
assert(req == rc);

Be wary of trying to copy the byte buffers into fixed sized arrays. Someone might come along and get you to copy a 4096-bit modulus into your 2048-bit array.

From OpenSSL 1.1.0 many structures were made opaque and you can no longer do things like look directly at the fields in a struct. You should use the provided accessor functions instead. Here you can find more infos: https://wiki.openssl.org/index.php/OpenSSL_1.1.0_Changes


Acces rsa->n in OpenSSL 1.1.0:

RSA *pRsa;
BIGNUM *n;
FILE *pFile = fopen("private.key","r");

pRsa = PEM_read_RSAPrivateKey(pFile, NULL, NULL, password);
RSA_get0_key(pRSA, &n, NULL,NULL);

BN_print_fp(stdout, n);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM