Hashlib and Cryptography

Advanced PythonSecurityFree Lesson

Advertisement

Introduction

Hashlib provides secure hashing algorithms for password storage and data integrity.

Hashing

import hashlib

# Basic hashing
data = "hello world"
h = hashlib.sha256(data.encode())
print(h.hexdigest())

# Multiple algorithms
h_md5 = hashlib.md5(data.encode())
h_sha1 = hashlib.sha1(data.encode())
h_sha512 = hashlib.sha512(data.encode())

Password Hashing

import bcrypt

# Hash password
password = "secure_password_123"
hashed = bcrypt.hashpw(password.encode(), bcrypt.gensalt())

# Verify password
bcrypt.checkpw(password.encode(), hashed)

HMAC

import hmac
import hashlib

key = b"secret_key"
message = b"message to authenticate"

sig = hmac.new(key, message, hashlib.sha256)
print(sig.hexdigest())

Practice Problems

  1. Hash files for integrity checking
  2. Implement password verification
  3. Use HMAC for message authentication
  4. Generate secure random tokens
  5. Store and verify passwords safely

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement