⚡ Cybersecurity Fundamentals - Deep Technical Dive

Mathematical foundations, cryptographic primitives, protocol internals, and practical implementations

⚠️ SECURITY DISCLAIMER

This documentation covers cryptographic implementations for educational purposes only. Real-world cryptographic implementations require careful consideration of side-channel attacks, timing attacks, and proper randomness. Never roll your own crypto for production systems.

🔐 Core Cryptographic Concepts

Symmetric Encryption

Same key for encryption and decryption

AES-256 ChaCha20 Twofish

Key Size: 128-256 bits | Speed: High | Use: Bulk data encryption

Asymmetric Encryption

Public/private key pairs

RSA-4096 ECC P-384 Ed25519

Key Size: 256-4096 bits | Speed: Low | Use: Key exchange, signatures

Cryptographic Hashes

One-way deterministic functions

SHA-256 SHA-3 BLAKE3

Output: Fixed size | Properties: Collision resistant

Digital Signatures

Message authenticity & integrity

ECDSA EdDSA RSA-PSS

Non-repudiation | Timestamping | Certificate-based

🔐

Encryption - Mathematical Foundations

1. AES-256 (Advanced Encryption Standard)

AES Mathematical Operations:

Galois Field GF(2⁸) arithmetic:
• Addition: XOR operation
• Multiplication: Polynomial multiplication mod irreducible polynomial x⁸ + x⁴ + x³ + x + 1

Key Expansion (Rijndael Key Schedule):
• 256-bit key → 14 rounds × 16 bytes per round key
• Uses Rcon constants and SubWord/RotWord operations

Round Operations (10-14 rounds):
1. SubBytes: S-box substitution (affine transformation)
2. ShiftRows: Byte permutation
3. MixColumns: Matrix multiplication in GF(2⁸)
4. AddRoundKey: XOR with round key
    

AES-256 Round Function Visualization:

Input Block (16 bytes):  00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
        ↓
SubBytes (S-box):
00 → 63, 11 → F2, 22 → 7B, 33 → 6B, ...
        ↓
ShiftRows:
Row 0: unchanged
Row 1: left rotate 1
Row 2: left rotate 2  
Row 3: left rotate 3
        ↓
MixColumns (matrix multiplication):
⎡02 03 01 01⎤   ⎡a0⎤   ⎡b0⎤
⎢01 02 03 01⎥ × ⎢a1⎥ = ⎢b1⎥
⎢01 01 02 03⎥   ⎢a2⎥   ⎢b2⎥
⎣03 01 01 02⎦   ⎣a3⎦   ⎣b3⎦
        ↓
AddRoundKey (XOR with round key):
b0 b1 b2 b3 ⊕ k0 k1 k2 k3 = output
    

Implementation Security Considerations:

Side-Channel Attacks: • Timing attacks on software implementations • Cache timing attacks on lookup tables • Power analysis on hardware implementations • Electromagnetic radiation analysis

Python AES-GCM Implementation (Educational):

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
import os

class SecureAES:
    def __init__(self, key_size=256):
        self.key_size = key_size
        self.iv_size = 96  # bits for GCM
        
    def generate_key(self):
        """Generate cryptographically secure key"""
        return os.urandom(self.key_size // 8)
    
    def encrypt(self, plaintext, key, associated_data=b""):
        """AES-GCM authenticated encryption"""
        iv = os.urandom(self.iv_size // 8)
        cipher = Cipher(
            algorithms.AES(key),
            modes.GCM(iv),
            backend=default_backend()
        )
        encryptor = cipher.encryptor()
        
        # Authenticate associated data (not encrypted)
        if associated_data:
            encryptor.authenticate_additional_data(associated_data)
        
        ciphertext = encryptor.update(plaintext) + encryptor.finalize()
        return iv + ciphertext + encryptor.tag
    
    def decrypt(self, data, key, associated_data=b""):
        """AES-GCM authenticated decryption"""
        iv = data[:self.iv_size//8]
        tag = data[-16:]  # GCM tag is 128 bits
        ciphertext = data[self.iv_size//8:-16]
        
        cipher = Cipher(
            algorithms.AES(key),
            modes.GCM(iv, tag),
            backend=default_backend()
        )
        decryptor = cipher.decryptor()
        
        if associated_data:
            decryptor.authenticate_additional_data(associated_data)
        
        return decryptor.update(ciphertext) + decryptor.finalize()
      

2. RSA Cryptosystem

RSA Mathematical Foundation:

Key Generation:
1. Choose two large primes p and q (typically 2048-bit each)
2. Compute n = p × q
3. Compute φ(n) = (p-1)(q-1)
4. Choose e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1
5. Compute d ≡ e⁻¹ mod φ(n)  (modular inverse)

Public Key: (n, e)
Private Key: (d, p, q)

Encryption: c ≡ mᵉ mod n
Decryption: m ≡ cᵈ mod n

Signing: s ≡ mᵈ mod n  
Verification: m ≡ sᵉ mod n
    

RSA Security Considerations:

Padding Schemes: PKCS#1 v1.5, OAEP (Optimal Asymmetric Encryption Padding)
Key Size Recommendations: 2048-bit minimum, 3072-bit recommended, 4096-bit for long-term
Common Vulnerabilities: Small exponent attacks, timing attacks on CRT implementation

🔢

Cryptographic Hashing - In Depth

SHA-256 Algorithm Breakdown

SHA-256 Compression Function:

Initial Hash Values (first 32 bits of fractional parts of square roots of first 8 primes):
h0 = 0x6a09e667
h1 = 0xbb67ae85
h2 = 0x3c6ef372
h3 = 0xa54ff53a
h4 = 0x510e527f
h5 = 0x9b05688c
h6 = 0x1f83d9ab
h7 = 0x5be0cd19

Round Constants K[0..63] (first 32 bits of fractional parts of cube roots of first 64 primes):
K[0] = 0x428a2f98, K[1] = 0x71374491, ..., K[63] = 0xc67178f2

Message Schedule (64 × 32-bit words):
For t = 0 to 15:
    W[t] = M[t]  (message block)
For t = 16 to 63:
    W[t] = σ₁(W[t-2]) + W[t-7] + σ₀(W[t-15]) + W[t-16]

Where:
σ₀(x) = ROTR⁷(x) ⊕ ROTR¹⁸(x) ⊕ SHR³(x)
σ₁(x) = ROTR¹⁷(x) ⊕ ROTR¹⁹(x) ⊕ SHR¹⁰(x)

Compression:
Initialize working variables: a = h0, b = h1, ..., h = h7
For t = 0 to 63:
    T1 = h + Σ₁(e) + Ch(e, f, g) + K[t] + W[t]
    T2 = Σ₀(a) + Maj(a, b, c)
    h = g
    g = f
    f = e
    e = d + T1
    d = c
    c = b
    b = a
    a = T1 + T2

Where:
Ch(x, y, z) = (x ∧ y) ⊕ (¬x ∧ z)
Maj(x, y, z) = (x ∧ y) ⊕ (x ∧ z) ⊕ (y ∧ z)
Σ₀(x) = ROTR²(x) ⊕ ROTR¹³(x) ⊕ ROTR²²(x)
Σ₁(x) = ROTR⁶(x) ⊕ ROTR¹¹(x) ⊕ ROTR²⁵(x)
    
Hash Algorithm Output Size Security (bits) Rounds Performance (MB/s) Status
SHA-256 256 bits 128 (collision) 64 230 Secure
SHA-3-256 256 bits 128 (collision) 24 180 Secure
BLAKE3 256 bits 128 (collision) 7-12 1200 Modern
MD5 128 bits 0 (broken) 64 450 Deprecated
SHA-1 160 bits 0 (broken) 80 300 Deprecated

HMAC (Hash-based Message Authentication Code)

HMAC Definition:
HMAC(K, m) = H((K ⊕ opad) || H((K ⊕ ipad) || m))

Where:
H = Cryptographic hash function (SHA-256, etc.)
K = Secret key (padded if necessary)
opad = Outer padding (0x5c repeated)
ipad = Inner padding (0x36 repeated)
|| = Concatenation

Security Properties:
1. Collision resistance inherited from hash function
2. Prevents length extension attacks
3. Provably secure if hash function is secure
    
🔑

Authentication Protocols

Challenge-Response Authentication

Step 1: Initialization
Client and Server share secret K (or server has client's public key)
Step 2: Challenge Generation
Server generates random nonce N (64-128 bits)
Step 3: Response Computation
Client computes R = HMAC(K, N || timestamp || client_id)
Step 4: Verification
Server computes expected R' and verifies R == R'

OAuth 2.0 + OpenID Connect Flow

JWT (JSON Web Token) Structure:

// JWT Header
{
  "alg": "RS256",        // Algorithm: RSA with SHA-256
  "typ": "JWT",          // Type
  "kid": "2024-01-key"   // Key ID for key rotation
}

// JWT Payload (Claims)
{
  "iss": "https://auth.example.com",  // Issuer
  "sub": "user123",                   // Subject
  "aud": "api.example.com",           // Audience
  "exp": 1704067200,                  // Expiration time (Unix timestamp)
  "iat": 1703980800,                  // Issued at
  "nbf": 1703980800,                  // Not before
  "jti": "a1b2c3d4",                  // JWT ID
  "scope": "read write",              // OAuth scopes
  "email": "user@example.com"
}

// JWT Signature
base64UrlEncode(header) + "." + 
base64UrlEncode(payload) + "." + 
RSASHA256(signing_input, private_key)

// Verification Process:
1. Split JWT into header, payload, signature
2. Decode header to verify algorithm
3. Verify signature using issuer's public key
4. Validate claims (exp, nbf, aud, iss)
5. Check token revocation status
      

Multi-Factor Authentication (MFA) Types:

Factor Type Examples Security Level Usability Implementation
Knowledge Passwords, PINs, Security Questions Low-Medium High Easy
Possession TOTP, Hardware tokens, Smart cards Medium-High Medium Moderate
Inherence Fingerprint, Face ID, Voice recognition High High Complex
Location IP geolocation, GPS verification Low High Easy
Behavior Typing patterns, Mouse movements Medium High Complex
🏛️

X.509 Certificates - Deep Dive

Certificate Structure (RFC 5280)

Certificate ::= SEQUENCE {
    tbsCertificate       TBSCertificate,
    signatureAlgorithm   AlgorithmIdentifier,
    signatureValue       BIT STRING
}

TBSCertificate ::= SEQUENCE {
    version         [0] EXPLICIT Version DEFAULT v1,
    serialNumber    CertificateSerialNumber,
    signature       AlgorithmIdentifier,
    issuer          Name,
    validity        Validity,
    subject         Name,
    subjectPublicKeyInfo SubjectPublicKeyInfo,
    issuerUniqueID  [1] IMPLICIT UniqueIdentifier OPTIONAL,
    subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
    extensions      [3] EXPLICIT Extensions OPTIONAL
}

Validity ::= SEQUENCE {
    notBefore      Time,
    notAfter       Time
}

SubjectPublicKeyInfo ::= SEQUENCE {
    algorithm       AlgorithmIdentifier,
    subjectPublicKey BIT STRING
}

Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension

Extension ::= SEQUENCE {
    extnID      OBJECT IDENTIFIER,
    critical    BOOLEAN DEFAULT FALSE,
    extnValue   OCTET STRING
}
    

Critical Certificate Extensions:

OID Extension Purpose Critical Example Value
2.5.29.15 Key Usage Defines certificate purpose Yes digitalSignature, keyEncipherment
2.5.29.17 Subject Alternative Name Additional identities No DNS:example.com, IP:192.168.1.1
2.5.29.19 Basic Constraints CA or end entity Yes CA:TRUE, pathlen:2
2.5.29.37 Extended Key Usage Specific applications No serverAuth, clientAuth, codeSigning
2.5.29.31 CRL Distribution Points Revocation list location No URI:http://crl.example.com
1.3.6.1.5.5.7.1.1 Authority Info Access OCSP responder location No OCSP;URI:http://ocsp.example.com

Certificate Chain Verification

Step 1: Parse Certificate
• Decode ASN.1 structure
• Verify signature algorithm is supported
• Check certificate format compliance
Step 2: Validate Chain
• Build chain to trusted root CA
• Verify each certificate signs the next
• Check path length constraints
Step 3: Check Validity
• Verify current time within notBefore/notAfter
• Check certificate not revoked (CRL/OCSP)
• Validate key usage and extended key usage
Step 4: Verify Signatures
• Verify each signature in chain
• Check for known weak algorithms
• Validate signature algorithm consistency
🔒

TLS 1.3 Protocol - Complete Analysis

TLS 1.3 Handshake Protocol

TLS 1.3 Full Handshake:

Client                                                  Server

ClientHello
[Random (32 bytes)]
[Key Share (client public key)]
[Supported Cipher Suites]
[Supported Groups]
[Signature Algorithms]
[PSK Modes]
[Supported Versions]
----------------------->
                                             ServerHello
                                             [Random (32 bytes)]
                                             [Key Share (server public key)]
                                             [Selected Cipher Suite]
                                             [Selected Group]
                                             <--------------------
                                             EncryptedExtensions
                                             [Extensions]
                                             <--------------------
                                             CertificateRequest
                                             [Signature Algorithms]
                                             <--------------------
                                             Certificate
                                             [Certificate Chain]
                                             <--------------------
                                             CertificateVerify
                                             [Signature]
                                             <--------------------
                           Finished
                           [Finished MAC]
                           <--------------------
Certificate
[Certificate Chain]
----------------------->
CertificateVerify
[Signature]
----------------------->
Finished
[Finished MAC]
----------------------->
        Application Data (Encrypted)
<-------------------->
    

Cipher Suite Negotiation (TLS 1.3):

// TLS 1.3 Cipher Suites (mandatory to implement)
TLS_AES_128_GCM_SHA256       // 0x1301
TLS_AES_256_GCM_SHA384       // 0x1302
TLS_CHACHA20_POLY1305_SHA256 // 0x1303

// Key Exchange Methods (TLS 1.3)
• secp256r1 (P-256)         // NIST curve
• secp384r1 (P-384)         // NIST curve
• secp521r1 (P-521)         // NIST curve
• x25519                    // Curve25519
• x448                      // Curve448

// Signature Algorithms (RFC 8446)
• rsa_pkcs1_sha256
• ecdsa_secp256r1_sha256
• ed25519
• rsa_pss_rsae_sha256
    

TLS 1.3 Key Schedule

Key Derivation Functions:
• HKDF-Extract(salt, key_material) → PRK
• HKDF-Expand(PRK, info, L) → OKM

Handshake Secret Derivation:
Early Secret = HKDF-Extract(0, 0)
Derived Secret = HKDF-Expand-Label(Early Secret, "derived", "", Hash.length)
Handshake Secret = HKDF-Extract(Derived Secret, (EC)DH Shared Secret)

Master Secret Derivation:
Derived Secret = HKDF-Expand-Label(Handshake Secret, "derived", "", Hash.length)
Master Secret = HKDF-Extract(Derived Secret, 0)

Traffic Key Derivation:
client_handshake_traffic_secret = HKDF-Expand-Label(Handshake Secret, 
    "c hs traffic", ClientHello...ServerHello, Hash.length)
server_handshake_traffic_secret = HKDF-Expand-Label(Handshake Secret,
    "s hs traffic", ClientHello...ServerHello, Hash.length)

client_application_traffic_secret_0 = HKDF-Expand-Label(Master Secret,
    "c ap traffic", ClientHello...ServerFinished, Hash.length)
server_application_traffic_secret_0 = HKDF-Expand-Label(Master Secret,
    "s ap traffic", ClientHello...ServerFinished, Hash.length)

Key Calculation:
key = HKDF-Expand-Label(Secret, "key", "", key_length)
iv = HKDF-Expand-Label(Secret, "iv", "", iv_length)
    

TLS 1.3 vs TLS 1.2 Security Improvements:

Feature TLS 1.2 TLS 1.3 Security Impact
Key Exchange Static RSA, DHE, ECDHE Ephemeral ECDHE only Perfect forward secrecy by default
Handshake 2-RTT minimum 1-RTT (2-RTT with client auth) Reduced attack surface
Cipher Suites 300+ combinations 5 approved suites Removes insecure options
Encryption Application data only Entire handshake encrypted Protects certificates, SNI
Renegotiation Allowed Removed Prevents renegotiation attacks
Compression Allowed Removed Prevents CRIME, BREACH attacks
RC4, MD5, SHA-1 Allowed Removed Eliminates weak algorithms
🛡️

Cryptanalysis Techniques

Attack Vectors on Cryptographic Systems

Mathematical Attacks

  • Integer factorization (RSA)
  • Discrete logarithm (DHE, ECDHE)
  • Lattice reduction attacks
  • Algebraic cryptanalysis

Implementation Attacks

  • Timing attacks
  • Power analysis
  • Cache attacks
  • Fault injection

Protocol Attacks

  • Man-in-the-middle
  • Replay attacks
  • Downgrade attacks
  • Padding oracle attacks

Specific Attack Examples:

Logjam Attack (TLS): Weak DH parameters (512-bit) can be broken, allowing MITM
ROBOT Attack (RSA): Bleichenbacher oracle in TLS implementations
Lucky Thirteen (TLS): Timing attack on CBC-mode padding verification
Sweet32 (3DES): Birthday attack on 64-bit block ciphers
💻

Secure Implementation Guidelines

Crypto Implementation Checklist

Random Number Generation
• Use /dev/urandom (Linux) or BCryptGenRandom (Windows)
• Seed with >128 bits of entropy
• Never use rand(), random(), or Math.random() for crypto
Key Management
• Store keys in HSMs or secure enclaves
• Implement key rotation policies
• Use key derivation functions (PBKDF2, Argon2)
• Never hardcode keys in source code
Algorithm Selection
• Use vetted libraries (OpenSSL, BoringSSL, Libsodium)
• Prefer authenticated encryption (AES-GCM, ChaCha20-Poly1305)
• Use modern elliptic curves (Curve25519, P-256)
• Avoid deprecated algorithms (RC4, MD5, SHA-1)
Side-Channel Protection
• Use constant-time implementations
• Disable hyper-threading for high security
• Implement rate limiting
• Use memory-safe languages where possible
⚛️

Post-Quantum Cryptography

NIST Post-Quantum Standardization Finalists

Algorithm Type Key Size Security Level Performance Status
CRYSTALS-Kyber Lattice-based (KEM) 800-1568 bytes Level 1-5 Fast Standardized
CRYSTALS-Dilithium Lattice-based (Signatures) 2420-4595 bytes Level 2-5 Fast Standardized
Falcon Lattice-based (Signatures) 1289-2305 bytes Level 5 Moderate Standardized
SPHINCS+ Hash-based (Signatures) 7852-49856 bytes Level 1-5 Slow Standardized

Migration Strategy to Post-Quantum Cryptography:

Hybrid Approach: Combine classical and PQ algorithms (e.g., X25519 + Kyber)
Crypto-Agility: Design systems to easily switch algorithms
Long-term Secrets: Assume current crypto broken in 15-20 years
Key Sizes: Prepare for larger key/certificate sizes

Quantum Threat Timeline

2023-2025: Early Preparation
• Inventory cryptographic assets
• Test PQ algorithms in lab environments
• Update crypto policies for PQ readiness
2025-2030: Initial Deployment
• Deploy hybrid solutions
• Update long-term storage encryption
• Train security teams on PQ concepts
2030-2035: Full Transition
• Complete migration to PQ algorithms
• Update all cryptographic protocols
• Deprecate vulnerable classical algorithms

🔬 CONTINUOUS LEARNING REQUIRED

Cryptography is a rapidly evolving field. New attacks are discovered regularly, and algorithms become obsolete. Stay updated through: