How Security Works in Python
Overview
Security in Python is not built-in by default at a high level, but it is achieved by:
• Using secure libraries and frameworks.
• Writing secure code (e.g., avoiding SQL injection, XSS, CSRF).
• Implementing secure authentication, encryption, and access control.
Popular Python Security Packages
Area Package Description
Cryptography cryptography High-level and low-level encryption
(AES, RSA, etc.)
PyCrypto / py- Cryptographic operations (signing, en-
cryptodome cryption, hashing)
hashlib (built-in) Secure hashing (SHA-256, SHA-512)
bcrypt Password hashing using bcrypt algo-
rithm
passlib Password hashing and verification
Authentication python-jose, pyjwt JWT (JSON Web Tokens) for secure
authentication
authlib OAuth, OpenID, and JWT tools
Web Security Flask-SeaSurf, Django CSRF protection
middleware
bleach Clean/sanitize HTML to prevent XSS
secure Set HTTP security headers easily in
Flask
Scanning & bandit Static code analyzer for security issues
Hardening
safety Checks your [Link] for
known vulnerabilities
SSH/SSL paramiko Secure SSH connections
ssl (built-in) Secure sockets for HTTPS and SS-
L/TLS protocols
Secrets Manage- python-dotenv, Load and hide secret values (like API
ment [Link] keys) securely
keyring Store secrets in OS-level secure storage
Table 1: Python Security Packages
1
Basic Examples for Each Package
Cryptography: Encrypting with Fernet
1 from cryptography . fernet import Fernet
2
3 key = Fernet . generate_key ()
4 cipher = Fernet ( key )
5 encrypted = cipher . encrypt ( b " Hello , secure world ! " )
6 print ( cipher . decrypt ( encrypted ) ) # b ’ Hello , secure world ! ’
PyCryptodome: AES Encryption
1 from Crypto . Cipher import AES
2 import os
3
4 key = os . urandom (16)
5 cipher = AES . new ( key , AES . MODE_EAX )
6 nonce = cipher . nonce
7 ciphertext , tag = cipher . en cr ypt _a nd _d ig es t ( b " Secret data " )
8 print ( ciphertext ) # Encrypted bytes
hashlib: SHA-256 Hashing
1 import hashlib
2
3 data = " Hello , world ! " . encode ()
4 hash_object = hashlib . sha256 ( data )
5 print ( hash_object . hexdigest () ) # SHA -256 hash
bcrypt: Password Hashing
1 import bcrypt
2
3 password = b " mysecret "
4 hashed = bcrypt . hashpw ( password , bcrypt . gensalt () )
5 if bcrypt . checkpw ( b " mysecret " , hashed ) :
6 print ( " Password is correct ! " )
passlib: Password Hashing
1 from passlib . hash import pbkdf2_sha256
2
3 password = " mysecret "
4 hashed = pbkdf2_sha256 . hash ( password )
5 print ( pbkdf2_sha256 . verify ( " mysecret " , hashed ) ) # True
2
pyjwt: Creating a JWT
1 import jwt
2
3 payload = { " user " : " alice " }
4 token = jwt . encode ( payload , " secret_key " , algorithm = " HS256 " )
5 print ( token ) # JWT token
authlib: OAuth Client (Simplified)
1 from authlib . integrations . requests_client import OAuth2Session
2
3 client = OAuth2Session ( " client_id " , " client_secret " )
4 redirect_uri = " https :// example . com / callback "
5 uri , state =
client . c r e a te _ a u t h o r i z a t i o n _ u r l ( " https :// auth - server . com / auth " )
6 print ( uri ) # Authorization URL
Flask-SeaSurf: CSRF Protection
1 from flask import Flask
2 from flask_seasurf import SeaSurf
3
4 app = Flask ( __name__ )
5 csrf = SeaSurf ( app )
6
7 @app . route ( " / form " , methods =[ " POST " ])
8 @csrf . exempt
9 def form () :
10 return " CSRF - protected form "
bleach: Sanitizing HTML
1 import bleach
2
3 dirty_html = " < script > alert ( ’ XSS ’) </ script > <p > Hello </ p > "
4 clean_html = bleach . clean ( dirty_html , tags =[ " p " ] , strip = True )
5 print ( clean_html ) # <p > Hello </ p >
secure: HTTP Security Headers
1 from flask import Flask
2 from secure import SecureHeaders
3
4 app = Flask ( __name__ )
5 secure_headers = SecureHeaders ()
3
6
7 @app . route ( " / " )
8 def home () :
9 resp = app . make_response ( " Hello " )
10 secure_headers . flask ( resp )
11 return resp
bandit: Running Security Scan
1 # Run in terminal : bandit -r my_project /
2 # Example output for a vulnerable file
3 # [ main ] Found 1 issues in file : insecure . py
4 # >> Issue : [ B105 : ha r d c o d e d _ p a s s w o r d _ s t r i n g ] Hardcoded password
safety: Checking Vulnerabilities
1 # Run in terminal : safety check -r requirements . txt
2 # Example output :
3 # + django ==2.2.0
4 # > Vulnerability : CVE -2021 -12345
paramiko: SSH Connection
1 import paramiko
2
3 ssh = paramiko . SSHClient ()
4 ssh . s e t _ m i s s i n g _ h o s t _ k e y _ p o l i c y ( paramiko . AutoAddPolicy () )
5 ssh . connect ( " example . com " , username = " user " , password = " pass " )
6 stdin , stdout , stderr = ssh . exec_command ( " ls " )
7 print ( stdout . read () . decode () )
8 ssh . close ()
ssl: Creating SSL Context
1 import ssl
2 import socket
3
4 context = ssl . c r e at e _ d e f a u l t _ c o n t e x t ()
5 with socket . create_con nectio n (( " example . com " , 443) ) as sock :
6 with context . wrap_socket ( sock ,
server_hostname = " example . com " ) as ssock :
7 print ( ssock . version () ) # TLS version
4
python-dotenv: Loading Environment Variables
1 from dotenv import load_dotenv
2 import os
3
4 load_dotenv ()
5 api_key = os . getenv ( " API_KEY " )
6 print ( api_key ) # Securely loaded API key
keyring: Storing a Password
1 import keyring
2
3 keyring . set_password ( " my_app " , " username " , " secretpassword " )
4 password = keyring . get_password ( " my_app " , " username " )
5 print ( password ) # secretpassword