经过一番调整后,我相信找到了正确的例程。
下面应该让您开始探索其他OpenSSL例程,以防您需要处理其他类型的证书(x509,,pem)。
还可以通过您当地的x509.h
和pem.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;
}
你想要的命令行是'OpenSSL的核实cert.pem'和'OpenSSL的X509 -in cert.pem -text'(转储出的证书数据,包括密钥长度),但我不知道如何映射到C函数。 – Rup 2012-01-12 13:20:27
感谢RUP,我知道openssl verify命令,但我需要从C编程检查它,而不是从命令行。 – Liviu 2012-01-12 13:26:18
我找到了一种方法来做到这一点;请参阅下面的代码。我在Linux和Mac OS X 10.7下测试了这个,但是10.7会抱怨弃用的方法。 – 2012-01-13 11:00:09