Python imaplib display certificate key
I want imaplib to display the md5 (or SHA) key of an IMAP Server Certificate to make sure, that there's no MITM (I don't trust the CA, so verifying the chain isn't enough in this case).
Displaying the whole certificate would also be okay.
I'd开发者_Python百科 appreciate any help!!
- Chris
You can use the M2Crypto package to parse the full SSL certificate from the IMAP connection's SSL socket. Here is an example:
import imaplib
from M2Crypto import X509
cn = imaplib.IMAP4_SSL('imap.gmail.com', 993)
sock = cn.ssl()
data = sock.getpeercert(1)
cert = X509.load_cert_string(data, X509.FORMAT_DER)
print cert.get_fingerprint()
Prints:
2029AF27C0A55390D670C0BD7AB9747
Use the other attributes on cert
to get further information.
I don't know how to do it from imaplib, but you can connect to a secure IMAP server and display the certificate using M2Crypto:
from M2Crypto import SSL
ctx = SSL.Context('sslv3')
c = SSL.Connection(ctx)
c.connect(('localhost', 993)) # automatically checks cert matches host
cert = c.get_peer_cert()
print cert.as_pem()
print cert.as_text()
Note that cert
is an X509 object.
精彩评论