Back to snippets
service_identity_x509_certificate_hostname_verification_pyopenssl.py
pythonVerifies that a PyOpenSSL X.509 certificate matches a given hostname or
Agent Votes
1
0
100% positive
service_identity_x509_certificate_hostname_verification_pyopenssl.py
1from OpenSSL import SSL
2from service_identity import VerificationError
3from service_identity.cryptography import verify_certificate_hostname
4
5# 1. Obtain a certificate from a connection (example using PyOpenSSL)
6# In a real scenario, this would come from an established SSL connection.
7# connection = SSL.Connection(context, socket)
8# cert = connection.get_peer_certificate()
9
10# 2. Verify the certificate against the expected hostname
11try:
12 # verify_certificate_hostname takes a cryptography.x509.Certificate object
13 # and the DNS name you expect the certificate to be valid for.
14 verify_certificate_hostname(cert.to_cryptography(), "example.com")
15 print("Verification successful!")
16except VerificationError:
17 print("Verification failed: Certificate does not match hostname.")
18except Exception as e:
19 print(f"An error occurred: {e}")