1 /* This example code is placed in the public domain. */
9 #include <gnutls/gnutls.h>
10 #include <gnutls/x509.h>
14 static const char *bin2hex(const void *bin, size_t bin_size)
16 static char printable[110];
17 const unsigned char *_bin = bin;
25 for (i = 0; i < bin_size; i++) {
26 sprintf(print, "%.2x ", _bin[i]);
33 /* This function will print information about this session's peer
36 void print_x509_certificate_info(gnutls_session_t session)
41 unsigned int algo, bits;
42 time_t expiration_time, activation_time;
43 const gnutls_datum_t *cert_list;
44 unsigned int cert_list_size = 0;
45 gnutls_x509_crt_t cert;
48 /* This function only works for X.509 certificates.
50 if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509)
53 cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
55 printf("Peer provided %d certificates.\n", cert_list_size);
57 if (cert_list_size > 0) {
60 /* we only print information about the first certificate.
62 gnutls_x509_crt_init(&cert);
64 gnutls_x509_crt_import(cert, &cert_list[0],
67 printf("Certificate info:\n");
69 /* This is the preferred way of printing short information about
73 gnutls_x509_crt_print(cert, GNUTLS_CRT_PRINT_ONELINE,
76 printf("\t%s\n", cinfo.data);
77 gnutls_free(cinfo.data);
80 /* If you want to extract fields manually for some other reason,
81 below are popular example calls. */
84 gnutls_x509_crt_get_expiration_time(cert);
86 gnutls_x509_crt_get_activation_time(cert);
88 printf("\tCertificate is valid since: %s",
89 ctime(&activation_time));
90 printf("\tCertificate expires: %s",
91 ctime(&expiration_time));
93 /* Print the serial number of the certificate.
95 size = sizeof(serial);
96 gnutls_x509_crt_get_serial(cert, serial, &size);
98 printf("\tCertificate serial number: %s\n",
99 bin2hex(serial, size));
101 /* Extract some of the public key algorithm's parameters
103 algo = gnutls_x509_crt_get_pk_algorithm(cert, &bits);
105 printf("Certificate public key: %s",
106 gnutls_pk_algorithm_get_name(algo));
108 /* Print the version of the X.509
111 printf("\tCertificate version: #%d\n",
112 gnutls_x509_crt_get_version(cert));
115 gnutls_x509_crt_get_dn(cert, dn, &size);
116 printf("\tDN: %s\n", dn);
119 gnutls_x509_crt_get_issuer_dn(cert, dn, &size);
120 printf("\tIssuer's DN: %s\n", dn);
122 gnutls_x509_crt_deinit(cert);