Cryptography
Encryption, hashing, digital signatures, PKI, and cryptographic protocols.
Overview
Cryptography protects data confidentiality, integrity, and authenticity.
Key Concepts
- Symmetric Encryption — Same key for encrypt/decrypt
- Asymmetric Encryption — Public/private key pairs
- Hashing — One-way data transformation
- Digital Signatures — Authentication and integrity
- PKI — Public Key Infrastructure
Symmetric Encryption
AES (Advanced Encryption Standard)
from cryptography.fernet import Fernet
# Generate key
key = Fernet.generate_key()
cipher = Fernet(key)
# Encrypt
plaintext = b"Secret message"
ciphertext = cipher.encrypt(plaintext)
# Decrypt
decrypted = cipher.decrypt(ciphertext)
Common Algorithms
| Algorithm | Key Size | Status |
|---|---|---|
| DES | 56-bit | Broken |
| 3DES | 168-bit | Deprecated |
| AES | 128/192/256-bit | Secure |
| ChaCha20 | 256-bit | Secure |
Asymmetric Encryption
RSA
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes
# Generate key pair
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
public_key = private_key.public_key()
# Encrypt with public key
ciphertext = public_key.encrypt(
plaintext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# Decrypt with private key
plaintext = private_key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
Hashing Algorithms
| Algorithm | Output Size | Security |
|---|---|---|
| MD5 | 128-bit | Broken |
| SHA-1 | 160-bit | Weak |
| SHA-256 | 256-bit | Secure |
| SHA-3 | Variable | Secure |
| bcrypt | Variable | Secure (passwords) |
Digital Signatures
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
# Sign message
signature = private_key.sign(
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
# Verify signature
try:
public_key.verify(
signature,
message,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
print("Signature is valid")
except:
print("Signature is invalid")
Practice
Implement a simple encryption/decryption tool using Python.