1 /* This example code is placed in the public domain. */
9 #include <gnutls/gnutls.h>
10 #include <gnutls/x509.h>
15 bin2hex (const void *bin, size_t bin_size)
17 static char printable[110];
18 const unsigned char *_bin = bin;
26 for (i = 0; i < bin_size; i++)
28 sprintf (print, "%.2x ", _bin[i]);
35 /* This function will print information about this session's peer
39 print_x509_certificate_info (gnutls_session_t session)
44 unsigned int algo, bits;
45 time_t expiration_time, activation_time;
46 const gnutls_datum_t *cert_list;
47 unsigned int cert_list_size = 0;
48 gnutls_x509_crt_t cert;
51 /* This function only works for X.509 certificates.
53 if (gnutls_certificate_type_get (session) != GNUTLS_CRT_X509)
56 cert_list = gnutls_certificate_get_peers (session, &cert_list_size);
58 printf ("Peer provided %d certificates.\n", cert_list_size);
60 if (cert_list_size > 0)
64 /* we only print information about the first certificate.
66 gnutls_x509_crt_init (&cert);
68 gnutls_x509_crt_import (cert, &cert_list[0], GNUTLS_X509_FMT_DER);
70 printf ("Certificate info:\n");
72 /* This is the preferred way of printing short information about
75 ret = gnutls_x509_crt_print (cert, GNUTLS_CRT_PRINT_ONELINE, &cinfo);
78 printf ("\t%s\n", cinfo.data);
79 gnutls_free (cinfo.data);
82 /* If you want to extract fields manually for some other reason,
83 below are popular example calls. */
85 expiration_time = gnutls_x509_crt_get_expiration_time (cert);
86 activation_time = gnutls_x509_crt_get_activation_time (cert);
88 printf ("\tCertificate is valid since: %s", ctime (&activation_time));
89 printf ("\tCertificate expires: %s", ctime (&expiration_time));
91 /* Print the serial number of the certificate.
93 size = sizeof (serial);
94 gnutls_x509_crt_get_serial (cert, serial, &size);
96 printf ("\tCertificate serial number: %s\n", bin2hex (serial, size));
98 /* Extract some of the public key algorithm's parameters
100 algo = gnutls_x509_crt_get_pk_algorithm (cert, &bits);
102 printf ("Certificate public key: %s",
103 gnutls_pk_algorithm_get_name (algo));
105 /* Print the version of the X.509
108 printf ("\tCertificate version: #%d\n",
109 gnutls_x509_crt_get_version (cert));
112 gnutls_x509_crt_get_dn (cert, dn, &size);
113 printf ("\tDN: %s\n", dn);
116 gnutls_x509_crt_get_issuer_dn (cert, dn, &size);
117 printf ("\tIssuer's DN: %s\n", dn);
119 gnutls_x509_crt_deinit (cert);