【问题标题】:How to verify key length of a PEM certificate using openSSL functions如何使用 openSSL 函数验证 PEM 证书的密钥长度
【发布时间】:2012-02-08 18:32:33
【问题描述】:

如何验证以这种方式生成的 PEM 证书的密钥长度:

# 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

我需要的是一个使用 OpenSSL 程序的 C 函数,它对 PEM 证书执行验证(我将它用于 lighttpd HTTPS 服务器),并返回存储在证书中的密钥长度(在本例中为 1024 )。

【问题讨论】:

  • 您想要的命令行是openssl verify cert.pemopenssl x509 -in cert.pem -text(转储出证书数据,包括密钥长度),但我不知道它如何映射到 C 函数。
  • 谢谢 Rup,我知道 openssl verify 命令,但我需要从 C 编程检查它,而不是从命令行。
  • 我找到了一种方法;请参阅下面的代码。我在 Linux 和 Mac OS X 10.7 下对此进行了测试,但 10.7 会抱怨不推荐使用的方法。

标签: c https openssl pem


【解决方案1】:

经过一些调整,我相信已经找到了正确的套路。

以下内容可以帮助您开始探索其他 OpenSSL 例程,以防您需要处理其他类型的证书(x509pem)。

还请阅读您当地的x509.hpem.h,了解可以恢复您所需要的其他信息的结构和函数。

/* 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多