I am trying to load a rsa object from a generated public key. I used PEM_write_bio_RSAPublicKey
to generate the public key string. Then I used PEM_read_bio_RSA_PUBKEY
to load the rsa object from the public key string. The problem is the rsa object is null. The generated string looks okay as far as I can tell. Any ideas?
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAxIReUspesPy6a4CPBjt/4Jt+H13q9MekMiutzNKdNO1uuwqcdqDX
pKPeTKXyUH6oCyRdUxkk6IVXGlBlxtW7OsxaYWhpfl9z3CCERCEpFmzN++dvlK2v
mckFL66e9q6Y+HwgyP1LJqrszeqlg2d29TCVKfD/UURVNmc/nPPjs9nO+IDhh7+P
NTQ2OqGBq8ghwVL5ZZyW3yVO5OAbRB6pjKBe9+j4B2TGnD5JO9Nu0jlFANZOKFJu
HDVE3XuTvOkuzL2i8Lwp4Myk42tbIgcCe4G58vKFddL651rWhg4hN3fRSx5YtDnQ
r5cgfNBOAww58S8lwXgU8lvzvEoNV+WMgwIDAQAB
-----END RSA PUBLIC KEY-----
gcc test_public_private_key.c -lcrypto -o test
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/err.h>
char* get_public_key() {
RSA* rsa = RSA_new();
int kbits = 2048;
BIGNUM* bne = BN_new();
BN_set_word(bne, RSA_F4);
int status = RSA_generate_key_ex(rsa, kbits, bne, NULL);
if(status == 0) {
fprintf(stderr, "rsa key generation failed\n");
}
BIO *bio = BIO_new(BIO_s_mem());
PEM_write_bio_RSAPublicKey(bio, rsa);
int length = BIO_pending(bio);
char* pem_key = malloc(length+1);
memset(pem_key, '\0', length+1);
BIO_read(bio, pem_key, length);
return pem_key;
}
int main(int argc, char* argv[]) {
char* public_key = get_public_key();
printf("%s", public_key);
BIO* keybio = BIO_new_mem_buf(public_key, -1);
if (keybio == NULL) {
fprintf(stderr, "failed to create key BIO");
}
printf("keybio: %p\n", keybio);
RSA* rsa = PEM_read_bio_RSA_PUBKEY(keybio, NULL, NULL, NULL);
printf("rsa result %p\n", rsa);
BIO_free(keybio);
free(public_key);
return 0;
}