使用 openssl 库获取 x509 证书哈希

Sn0*_*eze 3 c hash openssl x509 libcrypto

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

当我使用我的终端时,我能够通过使用生成哈希值

openssl x509 -hash -in cert.pem -noout
Run Code Online (Sandbox Code Playgroud)

输出: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);
Run Code Online (Sandbox Code Playgroud)

输出:1817886a

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

jww*_*jww 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)
...
Run Code Online (Sandbox Code Playgroud)

然后,看着apps/x509.c

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

你的声明应该是:

unsigned long hash = X509_subject_name_hash(cert);
Run Code Online (Sandbox Code Playgroud)

然后:

fprintf(stdout, "%08lx\n", hash);
Run Code Online (Sandbox Code Playgroud)

此外,OpenSSL 在 OpenSSL 1.0.1 前后改变了计算主题哈希的方式。这就是为什么有一个X509_subject_name_hashand X509_subject_name_hash_old

如果您正在使用或与 OpenSSL 0.9.8(例如 Mac OS X 10)进行比较,请参阅在 Java 中生成 X509Certificate 的主题哈希。虽然它是 Java,但它详细说明了主题哈希的 OpenSSL 处理。