0% found this document useful (0 votes)
58 views

TLS and SSL

The document discusses Transport Layer Security (TLS) and its predecessor Secure Sockets Layer (SSL). It provides details on how TLS encrypts data transmitted between a client and server using public/private keys. It also discusses how websites use SSL/TLS certificates signed by certificate authorities to establish encrypted connections. The Python SSL library is then introduced as a way to provide TLS encryption for socket-based communication between Python clients and servers using digital certificates for authentication. Steps for securing sockets with TLS for both client and server applications are outlined.

Uploaded by

amdmagdyabass165
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

TLS and SSL

The document discusses Transport Layer Security (TLS) and its predecessor Secure Sockets Layer (SSL). It provides details on how TLS encrypts data transmitted between a client and server using public/private keys. It also discusses how websites use SSL/TLS certificates signed by certificate authorities to establish encrypted connections. The Python SSL library is then introduced as a way to provide TLS encryption for socket-based communication between Python clients and servers using digital certificates for authentication. Steps for securing sockets with TLS for both client and server applications are outlined.

Uploaded by

amdmagdyabass165
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

TLS and SSL

 Transport Layer Security (TLS).


 Because earlier versions of TLS were called the Secure Sockets Layer (SSL),
 The TLS protocol, the successor of the secure socket layer (SSL) protocol,
protects data using encryption. When users send their information to a
website, TLS encrypts it before sending it. Then, only the server with the
same public key as the client can open the message. This rule also applies
when the server sends information back to the client. Only the client with the
corresponding key can read the data.
 For a website to use TLS protocol, you must install a valid TLS/SSL certificate
(often called an SSL certificate).
 the certificate is a data file that contains the website’s identity and the
public key for opening payload messages.
 An SSL certificate must be valid to work. This means that not only must a
credible certificate authority (CA) sign it, but the certificate also must be
active. Every certificate has an issuance date and an expiration date. A
certificate is no longer valid after its expiration date.
Certificate authorities
digicert
Website sent CSR (certificate signed
request
CA replay with signed certificate
Pc send request and website replay with
response + certificate
Checking if a website has a valid SSL
certificate

 When we execute the code, we get


a <Response [200]> (OK) message,
meaning that the Twitter site is
import requests using a valid SSL certificate (as
expected).

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.

 Prerequisite: Installing OpenSSL


Create the private RSA key

 openssl genrsa -out key.pem 2048


Generate a certificate signing request
(CSR) using the private key
 openssl req -new -key key.pem -out signreq.csr -config
"C:\openssl\ssl\openssl.cnf
Sign the CSR request to create the
certificate
 openssl x509 -req -days 365 -in signreq.csr -signkey key.pem -out
certificate.pem
 To view file use
 openssl x509 -text -noout -in certificate.pem
The Python SSL library

 We use the Python SSL library to provide TLS encryption in socket-based


communication between Python clients and servers.
 It uses cryptography and message digests to secure data and detect
alteration attempts in the network. Digital certificates provide
authentication.
ssl — TLS/SSL wrapper for socket objects

 This module provides access to Transport Layer Security (often known as


“Secure Sockets Layer”) encryption and peer authentication facilities for
network sockets, both client-side and server-side. This module uses the
OpenSSL library.
 import ssl
Socket creation

 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)

2. use the context’s wrap_socket()


ssl_sock = context.wrap_socket(sock, server_hostname=host)
3. Read data using ssl_sock
data = ssl_sock.recv(1024)
Client

import socket, ssl

def client(host, port, cafile=None):


context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=cafile)
raw_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
raw_sock.connect((host, port))
print('Connected to host {!r} and port {}'.format(host, port))
ssl_sock = context.wrap_socket(raw_sock, server_hostname=host)
while True:
data = ssl_sock.recv(1024)
if not data:
break
print(repr(data))

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)

2. use the context’s wrap_socket()


conn, address = sok_server.accept()
ssl_sock = context.wrap_socket(conn, server_side=True)

3. Read data using ssl_sock


ssl_sock.sendall('Simple is better than complex.'.encode('ascii'))
ssl_sock.close()
Server
import socket, ssl
def server(host, port, certfile, cafile=None):
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile)
sok_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sok_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sok_server.bind((host, port))
sok_server.listen(1)
print('Listening at interface {!r} and port {}'.format(host, port))
conn, address = sok_server.accept()
print('Connection from host {!r} and port {}'.format(*address))
ssl_sock = context.wrap_socket(conn, server_side=True)
ssl_sock.sendall('Simple is better than complex.'.encode('ascii'))
ssl_sock.close()
Run Server

host='localhost'
port=12345
cafile='ca.crt'
certfile='localhost.pem'
server(host,port,certfile)
Results

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy