Mengda
Mengda

Reputation: 41

Can not get public key from .cer files using openssl on C

Using openssl in code EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a) method can not get public key in .cer file.


int load_cert() {

    FILE *fp = fopen("/home/android/cafile/cerfile.cer", "r");
    if (!fp) {
        fprintf(stderr, "unable to open: %s\n", path);
        return EXIT_FAILURE;
    }

    X509 *x509data = NULL;
    // X509 *cert = d2i_X509_bio(fp, NULL);
    d2i_X509_fp(fp, &x509data);
    if (!x509data) {
        fprintf(stderr, "unable to parse certificate in: %s\n", path);
        fclose(fp);
        return EXIT_FAILURE;
    }
    char issuer_name[1024];
    char subject_name[1024];

    X509_NAME_oneline(X509_get_issuer_name(x509data), issuer_name,
                      sizeof(issuer_name));
    X509_NAME_oneline(X509_get_subject_name(x509data), subject_name,
                      sizeof(subject_name));

    printf("Issuer  name: %s\n", issuer_name);
    printf("Subject name: %s\n", subject_name);

    EVP_PKEY *pkey;
    EVP_PKEY *a = NULL;
    //d2i_PUBKEY_fp(fp, &a);
    pkey = d2i_PUBKEY_fp(fp, &a);
    d2i_PUBKEY_fp(fp, NULL);
    if (pkey == NULL) {
        printf("d2i_PUBKEY_fp pkey error\n");
    }
    if (a == NULL) {
        printf("d2i_PUBKEY_fp a error\n");
    }
// any additional processing would go here..
    fclose(fp);
    return 0;
}

cerfile.cer file

issuer_name and subject_name can be obtained correctly, but pkey and a are null.

Upvotes: 1

Views: 280

Answers (1)

Matt Caswell
Matt Caswell

Reputation: 9382

You seem to be expecting the public key to be in a serialized form directly after the X509 certificate in the file. The public key is contained within the certificate - so you already read it when you did the d2i_X509_fp call and it is contained within the x509data object. To extract it out as an EVP_PKEY use X509_get_pubkey as documented here:

https://www.openssl.org/docs/man1.1.1/man3/X509_get_pubkey.html

Upvotes: 1

Related Questions