简体   繁体   中英

How to read RSA public and private keys into single RSA struct?

What I'm trying to do is generate random RSA keys and then store them before my program terminates. This part is working just fine using RSA_generate_key, PEM_write_bio_RSAPrivateKey and PEM_write_bio_RSA_PUBKEY. I can also encrypt/decrypt just find using the RSA structure returned by RSA_generate_key.

However, my problem comes when my program restarts and I want to read back in the keys that I stored previously. I can use PEM_read_bio_RSAPrivateKey and PEM_read_bio_RSA_PUBKEY to pull the keys in, but I need to get them into the same RSA structure, similar to how they are stored by RSA_generate_key.

My code is shown below. I have the keys stored in memory along with a small header that tell me how large the keys are. The private key start right after the header and the public key is stored right after the private key.

privateKey = (uint8_t *) ( buffer + rsaStruct->hdrSize );
publicKey = (uint8_t *) ( privateKey + rsaStruct->privateKeyLength );

bioPrivate = BIO_new_mem_buf( (void *) privateKey, rsaStruct->privateKeyLength );
bioPublic = BIO_new_mem_buf( (void *) publicKey, rsaStruct->publicKeyLength );

bioPrivate = BIO_new_mem_buf( (void *) privateKey, rsaStruct->privateKeyLength + rsaStruct->publicKeyLength );
if( bioPrivate == NULL || bioPublic == NULL ) {
    fprintf( stderr, "%s: BIO_new_mem_buf failed!\n", __FUNCTION__ );
    return ECE_RSA_ERROR_BIO_CREATION_FAILED;
}

PEM_read_bio_RSAPrivateKey( bioPrivate, &keyPair, NULL, NULL );
PEM_read_bio_RSA_PUBKEY( bioPublic, &keyPair, NULL, NULL );

BIO_free( bioPrivate );
BIO_free( bioPublic );

If I try to just send in the same RSA structure, it doesn't seem to work. I'm able to encrypt just fine, but my decryption fails. This could likely be due to the fact that the public key is the last key retrieve and the one used for encryption. If the second call over-writes the address of my RSA struct, I would end up with an RSA structure that has nothing but the public key.

Anyway, if anyone could tell me how to get both the public and private key into the same RSA structure, that would be great!

Comparing to RSA private key, public key additionaly contains only the public exponent. So just copy it from public key to private key structure, and everything should work.

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