TLS and SSL
TLS and SSL
response=requests.get('https://twitter.com/')
print(response)
import requests
response=requests.get('https://ww
w.expired.badssl.com/')
print(response)
Create a self-signed SSL certificate in
Python
The process of self-generating an SSL certificate for our local Python
application has three steps:
Create the private RSA key.
Generate a certificate signing request (CSR) using the private key.
Sign the CSR request to create the certificate.
ssl.create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, ca
path=None, cadata=None)
Return a new SSLContext object with default settings for the given purpose.
Load_cert_chain() Method Of SSLContext
Class In Python
Method Signature:
load_cert_chain(certfile, keyfile=None, password=None)
Parameters:
certfile - Path of the X.509 certificate file in PEM(Privacy Enhanced Email)
format.
keyfile - The private key of the certificate
password - Password for the private key if the private key is encrypted. The
value to this parameter can be a string, bytes or bytearray or a function returning
string, bytes or bytearray.
Return value:
None
Wrap_socket() Method Of SSLContext
Class In Python
Method Signature:
wrap_socket(sock, server_side=False, do_handshake_on_connect=True,
server_hostname=None, session=None);
Parameters:
sock – The socket instance from which the SSLSocket needs to be created.
server_side – Denotes whether the SSLSocket being created is a server socket or
a client socket.
server_hostname – Server hostname to which the client is connecting to. This
parameter needs to be supplied a value only if the server_side = False.
Return Value:
An object of type ssl.SSLSocket
Securing a Socket with TLS for Both Client
and Server
First, create a TLS context object that knows all of your preferences
regarding certificate validation and choice of cipher.
Second, use the context’s wrap_socket() method to let the OpenSSL library
take control of your TCP connection, exchange the necessary greetings
with the other end, and set up an encrypted channel.
Finally, perform all further communication with the ssl_sock
that has been returned to you so that the TLS layer always has the chance to
encrypt your data before it actually hits the wire
Client
1. Create Context
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH,
cafile=cafile)
host='localhost'
port=12345
cafile='ca.crt'
client(host,port,cafile)
Server
1. Create Context
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile)
host='localhost'
port=12345
cafile='ca.crt'
certfile='localhost.pem'
server(host,port,certfile)
Results