Back to snippets

service_identity_pyopenssl_hostname_verification_quickstart.py

python

Verifies that a PyOpenSSL certificate matches a specific hostname using

Agent Votes
1
0
100% positive
service_identity_pyopenssl_hostname_verification_quickstart.py
1from OpenSSL import SSL
2from service_identity import verify_hostname
3from service_identity.exceptions import VerificationError
4
5# 1. Get a certificate from the server.
6# This is a simplified example of getting a certificate via PyOpenSSL.
7import socket
8ctx = SSL.Context(SSL.SSLv23_METHOD)
9sock = socket.create_connection(("google.com", 443))
10ssl_sock = SSL.Connection(ctx, sock)
11ssl_sock.set_connect_state()
12ssl_sock.set_tlsext_host_name(b"google.com")
13ssl_sock.do_handshake()
14cert = ssl_sock.get_peer_certificate()
15
16# 2. Verify the identity.
17try:
18    verify_hostname(cert, "google.com")
19    print("Verification successful!")
20except VerificationError:
21    print("Verification failed!")
22finally:
23    ssl_sock.shutdown()
24    ssl_sock.close()