// Encryption: Transform data (reversible with key)
Symmetric: Same key for encrypt/decrypt
- AES, DES, RC4
- Fast, key exchange problem
- Use for: Data at rest, sessions
Asymmetric (Public-key): Different keys
- RSA, ECC, DSA
- Slow, solved key exchange
- Use for: SSH, TLS/SSL, digital signatures
// Hashing: One-way transformation (not reversible)
MD5: 128 bits (broken, don't use)
SHA-1: 160 bits (broken for collision, deprecated)
SHA-2: 256/512 bits (SHA-256, SHA-512) secure
SHA-3: Latest standard
Bcrypt: Password hashing (slow, salted)
Argon2: Modern password hashing (resistant to GPU attacks)
// Salt: Random added to password before hashing
Prevents: Rainbow tables, identical password attacks
bcrypt: Automatically salts
Example: bcrypt("password", salt) → unique hash
// Key derivation
Password → KDF (PBKDF2, scrypt, Argon2) → Key
Stretches passwords to make brute-force slow
// TLS/SSL Handshake (HTTPS)
1. Client Hello: Version, ciphers
2. Server Hello: Chosen cipher, certificate
3. Client verifies certificate (issuer, expiry)
4. Key exchange (RSA, Diffie-Hellman)
5. Change cipher spec
6. Finished (verify entire handshake)
Now communication encrypted with symmetric key
Cybersecurity Cheat Sheet
Encryption & Hashing
Authentication & Authorization
// Authentication: Verify identity (Are you who you claim?)
Basic: Username + password
Multi-factor (MFA/2FA): Password + phone/app/hardware key
OAuth 2.0: Delegate to provider (Google, GitHub)
SAML: Enterprise SSO
OpenID Connect: OAuth + user info
// Authorization: What can you do? (Permissions)
ACL (Access Control List): Per-user permissions
RBAC (Role-Based): Users have roles, roles have permissions
ABAC (Attribute-Based): Policies based on attributes
// JWT (JSON Web Token)
Self-contained token
Header.Payload.Signature
Header: {alg: "HS256", typ: "JWT"}
Payload: {user_id: 123, exp: 1234567890, admin: true}
Signature: HMAC(Header.Payload, secret)
Advantages: Stateless, scalable, cross-domain
Disadvantages: Token revocation hard, can't invalidate
// Session vs Token
Session: Store on server, cookie in browser
- Stateful, revocable, secure
- Server load, single data center problem
Token (JWT): Store in browser, no server state
- Stateless, scalable, mobile-friendly
- Can't revoke easily (use blacklist)
// OAuth 2.0 Flow
1. User clicks "Login with Google"
2. Redirects to Google with client_id, redirect_uri
3. User logs into Google
4. Google redirects back with authorization code
5. App backend exchanges code for access token (using client_secret)
6. App uses access token to fetch user info
// Best practices
Never log passwords
Hash passwords (bcrypt, Argon2)
HTTPS only (encrypt credentials)
Short JWT expiry (15 min), refresh tokens (1 week)
MFA for sensitive actions
Rate limit login attempts (prevent brute force)
OWASP Top 10 & Common Attacks
// 1. Injection (SQL, NoSQL, Command)
Attack: Inject code via input
Input: admin" --
SQL: SELECT * FROM users WHERE name="admin" --" (comment out rest)
Result: Bypasses password check
Prevention:
- Prepared statements (parameterized queries)
- Input validation
- ORM (Object-Relational Mapping)
// 2. Broken Authentication
Weak passwords, password reuse, session fixation
Prevention: MFA, password policies, secure session
// 3. Sensitive Data Exposure
Storing passwords in plain text, unencrypted transmission
Prevention: Encryption, HTTPS, hashing
// 4. XML External Entities (XXE)
XML with malicious entities
Example: ]>
Can read files, DoS
Prevention: Disable XML external entities
// 5. Broken Access Control
Users access others' data
Example: GET /api/users/123 (user 456 can see user 123)
Prevention: Check authorization on every request
// 6. Security Misconfiguration
Default credentials, unnecessary services, outdated software
Prevention: Hardening, principle of least privilege
// 7. XSS (Cross-Site Scripting)
Inject JavaScript in web pages
Example:
Steals cookies, credentials
Prevention: Input sanitization, CSP, HTTPOnly cookies
// 8. Insecure Deserialization
Deserialize untrusted data → arbitrary code execution
Prevention: Avoid deserializing untrusted input
// 9. Using Components with Known Vulnerabilities
Outdated libraries with security flaws
Prevention: Dependency scanning, keep libraries updated
// 10. Insufficient Logging & Monitoring
Don't detect attacks
Prevention: Log security events, monitor for anomalies
CSRF & Security Headers
// CSRF (Cross-Site Request Forgery)
Attack: Trick user into performing unwanted action
Example:
1. User logs into bank.com
2. User visits attacker.com
3. attacker.com:
4. Browser sends request (includes bank cookies)
5. Unwanted transfer executes
Prevention:
- CSRF tokens: Random token in form, server validates
- Same-site cookies: Don't send across sites
- Check Referer header (not foolproof)
- POST instead of GET
// Security Headers
Content-Security-Policy: CSP
- Prevent XSS by restricting script sources
- default-src 'self'; script-src 'self' 'unsafe-inline'
X-Frame-Options: Prevent clickjacking
- DENY: Can't be framed
- SAMEORIGIN: Only same origin
- ALLOW-FROM: Specific origin
Strict-Transport-Security (HSTS):
- Force HTTPS for X seconds
- max-age=31536000 (1 year)
X-Content-Type-Options: nosniff
- Prevent MIME type sniffing
Referrer-Policy: no-referrer
- Don't send referrer to external sites
Permissions-Policy (formerly Feature-Policy):
- Control browser features (camera, geolocation)
// Cookie attributes
Secure: Only send over HTTPS
HttpOnly: Can't access via JavaScript (prevents XSS stealing)
SameSite: Strict/Lax/None (CSRF prevention)
Domain: Which domains can access
Path: Which paths can access
Max-Age: Lifetime in seconds
Security Checklist
// Development
✓ Input validation & sanitization
✓ Output encoding (prevent XSS)
✓ Parameterized queries (prevent SQLi)
✓ Principle of least privilege
✓ Don't hardcode secrets (use env vars)
✓ Secure password hashing (bcrypt/Argon2)
✓ Rate limiting (brute force protection)
✓ Logging (audit trail)
✓ HTTPS only
✓ Security headers (CSP, HSTS, etc.)
// Deployment
✓ Remove debug code
✓ No default credentials
✓ Minimal services running
✓ Firewall configured
✓ Regular patching
✓ Secrets management (HashiCorp Vault)
✓ DDoS protection
✓ Monitoring & alerting
✓ Incident response plan
✓ Regular security audits
// Operations
✓ Change management (control releases)
✓ Backup testing
✓ Disaster recovery plan
✓ Access logs review
✓ Vulnerability scanning
✓ Penetration testing (annual)
✓ Employee training
✓ Incident response drills
✓ Data retention policies
✓ GDPR/compliance (data privacy)
// Example env vars (not hardcoded)
DATABASE_URL=postgres://user:password@host:5432/db
API_SECRET=random_secret_key_here
JWT_SECRET=another_random_key