urllib getting SSL certificate info

Jean-Paul Calderone exarkun at divmod.com
Tue Aug 19 17:05:47 EDT 2008


On Tue, 19 Aug 2008 23:06:30 +0300, Ghirai <ghirai at ghirai.com> wrote:
>On Sunday 17 August 2008 20:15:47 John Nagle wrote:
>
>>     If you really need details from the SSL cert, you usually have to use
>> M2Crypto.  The base SSL package doesn't actually do much with certificates.
>> It doesn't validate the certificate chain.  And those strings of
>> attributes you can get are ambiguious; data fields may contain unescaped
>> "/", which is the field separator.  I went through this last year and
>> had to use M2Crypto, which is something of a headache but more or less
>> works.
>>
>> 				John Nagle
>
>Would you mind sharing some code? The module is pretty ugly and on top has no
>docs whatsoever; got tired of reading the source...
>

I don't know about M2Crypto.  Here's some sample code for PyOpenSSL:

  from socket import socket
  from OpenSSL.SSL import Connection, Context, SSLv3_METHOD
  s = socket()
  s.connect(('google.com', 443))
  c = Connection(Context(SSLv3_METHOD), s)
  c.set_connect_state()
  c.send('GET / HTTP/1.1\r\n\r\n')
  cert = c.get_peer_certificate()
  print cert.get_issuer().get_components()
  print cert.get_subject().get_components()

When I run this, I get:

  [('C', 'ZA'), ('O', 'Thawte Consulting (Pty) Ltd.'), ('CN', 'Thawte SGC CA')]
  [('C', 'US'), ('ST', 'California'), ('L', 'Mountain View'), ('O', 'Google Inc'), ('CN', 'www.google.com')]


Jean-Paul



More information about the Python-list mailing list