使用openssl库获取x509证书哈希值

3

我目前正在开发一款应用程序,它使用openssl库(libcrypto)来生成证书。现在我需要获取已有证书的哈希值。

当我使用终端时,可以通过以下命令生成哈希值:

openssl x509 -hash -in cert.pem -noout

输出:01da0e2b

这是我的代码,我尝试使用C语言中的库生成哈希值。

X509 *cert = NULL;
FILE *fp = fopen(currentCert.UTF8String, "r");
PEM_read_X509(fp, &cert, NULL, NULL);

long hash = X509_subject_name_hash(cert);
char *mdString = malloc(sizeof(long));
sprintf(mdString, "%lx",hash);
printf(mdString);

输出结果: 1817886a

但实际上我的输出结果不同。有人知道我做错了什么吗?


1
只需使用 printf("0x%08lx",hash),无法理解将其序列化为 char * 的原因,这也是不正确的,因为缓冲区的大小应该取决于数字的位数。 - cmidi
2个回答

5

但实际上我的输出结果不同。有没有人知道我做错了什么?

以下是OpenSSL的使用方法...

$ cd openssl-1.0.2-src
$ grep -R X509_subject_name_hash *
apps/x509.c:                BIO_printf(STDout, "%08lx\n", X509_subject_name_hash(x));
apps/x509.c:                BIO_printf(STDout, "%08lx\n", X509_subject_name_hash_old(x));
crypto/x509/x509.h:unsigned long X509_subject_name_hash(X509 *x);
crypto/x509/x509.h:unsigned long X509_subject_name_hash_old(X509 *x);
crypto/x509/x509_cmp.c:unsigned long X509_subject_name_hash(X509 *x)
crypto/x509/x509_cmp.c:unsigned long X509_subject_name_hash_old(X509 *x)
...

接下来,看一下apps/x509.c文件:

...
} else if (subject_hash == i) {
    BIO_printf(STDout, "%08lx\n", X509_subject_name_hash(x));
}
...

你的声明应该是:

unsigned long hash = X509_subject_name_hash(cert);

然后:

fprintf(stdout, "%08lx\n", hash);

此外,OpenSSL在OpenSSL 1.0.1左右改变了计算主题哈希的方式。这就是为什么有X509_subject_name_hashX509_subject_name_hash_old的原因。

如果您正在使用或与OpenSSL 0.9.8进行比较(例如Mac OS X 10),请参见Generate Subject Hash of X509Certificate in Java。虽然这是Java,但它详细说明了OpenSSL处理主题哈希的方法。


是的,这个可行。实际上我发现服务器正在使用一个旧的openssl库。所以我不得不使用X509_subject_name_hash_old(cert)。谢谢你的回答! - Sn0wfreeze

3

您没有为字符串分配足够的内存,虽然我不能确定这是您问题的原因。

char *mdString = malloc(sizeof(long));

该代码将为字符串分配4个字节,但显然需要容纳8个字节和一个终止符,因此我建议

char *mdString = malloc(sizeof(long)*2 + 1);

我认为你是正确的,但实际上我得到了相同的输出。 “1817886a” - Sn0wfreeze

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接