头文件
#include <stdio.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/bio.h>
#include <openssl/pem.h>
十六进制转换
int arrayToStr(unsigned char *buf, int buflen, char *out)
{
int i;
for(i = 0; i < buflen; i++)
{
sprintf(out + 2*i, "%02x", buf[i]);
}
return buflen * 2;
}
获取公钥hash
此处是获取出来的公钥为PKCS8格式(oid+XY),对公钥使用sha1获取摘要
int main(int argc, char *argv[]) {
EVP_PKEY *pkey = NULL;
unsigned char pub_data[1024] = {0};
unsigned char *temp = NULL;
unsigned char md[1024] = {0};
unsigned char buf[1024] = {0};
int pub_len,md_len = 0;
BIO *bio = BIO_new_file(argv[1], "r");
if (bio == NULL) {
printf("err\n");
return -1;
}
X509 *x509 = PEM_read_bio_X509(bio, NULL, 0, NULL);
BIO_free(bio);
if (x509 == NULL) {
printf("err\n");
return -2;
}
pkey = X509_get0_pubkey(x509);
pub_len = i2d_PUBKEY(pkey, NULL);
if(pub_len < 1){
printf("err\n");
return -1;
}
temp = pub_data;
i2d_PUBKEY(pkey,&temp);
EVP_Digest(pub_data, pub_len, md, &md_len, EVP_sha1(), NULL);
arrayToStr(md,md_len,(char *)buf);
printf("%s\n",buf);
return 0;
}