How to verify key length of a PEM certificate using openSSL functions

情到浓时终转凉″ 提交于 2021-02-07 20:28:45

问题


How do I verify the key length of a PEM certificate that is generated in this way:

# openssl genrsa -des3 -out server.key 1024
# openssl req -new -key server.key -out server.csr
# cp server.key server.key.org
# openssl rsa -in server.key.org -out server.key
# openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

What I need is a C function using procedures from OpenSSL, that performs validation on a PEM certificate (I use it for the lighttpd HTTPS server), and returns the length of the key stored in the certificate (in this case, 1024).


回答1:


After some tweaking, I believe have found the right routines.

The following should get you started with exploring other OpenSSL routines, in case you need to handle other types of certificates (x509, pem).

Also read through your local x509.h and pem.h for structures and functions that will recover other information you're after.

/* Compile with 'gcc -Wall -lcrypto foo.c' or similar...
   ---------------------------------------------------------
   $ ./a.out server.crt
   Opened: server.crt
   RSA Public Key: (1024 bit) 

   $ ./a.out server.key
   ERROR: could not read x509 data from server.key                
*/

#include <stdio.h>
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/pem.h>

int main(int argc, char *argv[]) 
{
    FILE *fp = NULL;
    X509 *x509 = NULL;
    EVP_PKEY *public_key = NULL;

    fp = fopen(argv[1], "r");
    if (fp) {
        PEM_read_X509(fp, &x509, NULL, NULL);
        fclose(fp);

        if (x509) {
            fprintf(stderr, "Opened PEM certificate file: %s\n", argv[1]);
            /* do stuff with certificate... */
            public_key = X509_get_pubkey(x509);
            if (public_key) {
                switch (public_key->type) {
                    case EVP_PKEY_RSA:
                        fprintf(stdout, "RSA Public Key: (%d bit)\n", BN_num_bits(public_key->pkey.rsa->n));
                        break;
                    default:
                        fprintf(stdout, "Unknown public key type? See OpenSSL documentation\n");
                        break;
                }
                EVP_PKEY_free(public_key);
            }
            X509_free(x509);
        }
        else {
            fprintf(stderr, "ERROR: could not read x509 data from %s\n", argv[1]);
            return EXIT_FAILURE;
        }
    }
    else {
        fprintf(stderr, "ERROR: could not open file!\n");
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}


来源:https://stackoverflow.com/questions/8835597/how-to-verify-key-length-of-a-pem-certificate-using-openssl-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!