upgrade
upgrade

🔒Cybersecurity and Cryptography

Secure Coding Practices

Study smarter with Fiveable

Get study guides, practice questions, and cheatsheets for all your subjects. Join 500,000+ students with a 96% pass rate.

Get Started

Why This Matters

Secure coding isn't just a nice-to-have—it's the foundation that determines whether an application becomes a tool or a target. You're being tested on your understanding of how vulnerabilities emerge from coding decisions and how defensive programming techniques prevent exploitation. The practices covered here connect directly to core cryptographic principles like confidentiality, integrity, and authentication, while also demonstrating how theoretical security concepts translate into real-world implementation.

Think of secure coding as the bridge between knowing about attacks and actually stopping them. Every SQL injection, XSS exploit, and session hijack you've studied exists because a developer somewhere didn't follow these practices. Don't just memorize the techniques—know why each practice defends against specific attack vectors and which layer of security (input, processing, storage, transmission) each one protects.


Defending the Input Layer

The first line of defense is treating all external input as potentially hostile. Input validation creates a trust boundary between your application and the outside world.

Input Validation and Sanitization

  • Whitelisting over blacklisting—define exactly what's acceptable rather than trying to block every possible malicious pattern
  • Type and format checking ensures data matches expected structures before processing, preventing injection attacks at their source
  • Rejection vs. sanitization represents a key design choice; rejecting invalid input is generally safer than attempting to "clean" malicious data

Prepared Statements for SQL Injection Prevention

  • Parameterized queries separate SQL logic from user data, making it impossible for input to be interpreted as executable code
  • Binding variables at the database driver level ensures the query structure is fixed before any user input is processed
  • Defense in depth means combining prepared statements with input validation, even though prepared statements alone prevent most SQL injection

Secure File Handling and Upload Validation

  • File type validation must check actual file contents (magic bytes), not just extensions, which attackers easily spoof
  • Storage outside web root prevents direct URL access to uploaded files, blocking path traversal exploits
  • Size limits and virus scanning add additional layers against denial-of-service attacks and malware distribution

Compare: Input validation vs. prepared statements—both prevent injection attacks, but validation works at the application boundary while prepared statements protect specifically at the database layer. If an FRQ asks about defense-in-depth, using both together is your strongest answer.


Managing Identity and Access

Authentication confirms who a user is; authorization determines what they can do. Confusing these concepts is a common exam pitfall.

Proper Authentication and Authorization

  • Multi-factor authentication (MFA) combines something you know, have, or are—dramatically reducing the impact of credential theft
  • Role-based access control (RBAC) maps permissions to job functions rather than individuals, simplifying management and auditing
  • Regular permission audits catch privilege creep, where users accumulate access rights over time beyond what they currently need

Principle of Least Privilege

  • Minimum necessary access limits the blast radius when any single account is compromised
  • Separation of duties ensures no single user can complete a critical action alone, preventing insider threats
  • Time-limited privileges for sensitive operations reduce the window of exposure for elevated access

Secure Session Management

  • Cryptographically random session IDs must be unpredictable; sequential or guessable tokens enable session hijacking
  • Session regeneration after authentication prevents session fixation attacks where attackers pre-set a victim's session ID
  • Secure cookie attributes (HttpOnly, Secure, SameSite) control how browsers handle session tokens across requests

Compare: Authentication vs. authorization—authentication failures let attackers impersonate legitimate users, while authorization failures let authenticated users access resources beyond their role. Both appear frequently in scenario-based questions.


Protecting Data at Rest

How you store sensitive data determines whether a breach becomes a headline or a non-event. Proper cryptographic storage makes stolen data worthless to attackers.

Secure Password Storage with Strong Hashing

  • Adaptive hashing algorithms (bcrypt, Argon2, PBKDF2) are intentionally slow, making brute-force attacks computationally expensive
  • Unique salts per password prevent rainbow table attacks and ensure identical passwords produce different hashes
  • Work factor tuning allows you to increase computational cost over time as hardware improves, future-proofing your implementation

Proper Use of Cryptographic Functions and Libraries

  • Established libraries only—never implement your own cryptographic primitives; subtle flaws create catastrophic vulnerabilities
  • Key management practices including secure generation, storage, rotation, and destruction are often more critical than algorithm choice
  • Algorithm agility means designing systems to swap cryptographic algorithms without major refactoring when vulnerabilities emerge

Compare: Password hashing vs. encryption—hashing is one-way (you verify by re-hashing), while encryption is reversible with the key. Passwords should always be hashed, never encrypted, because there's no legitimate need to recover the original password.


Securing Data in Transit

Encryption during transmission prevents eavesdropping and tampering. TLS creates an authenticated, encrypted channel between endpoints.

Secure Communication Using HTTPS

  • TLS certificates provide both encryption and server authentication, preventing man-in-the-middle attacks
  • HTTP Strict Transport Security (HSTS) forces browsers to use HTTPS, preventing protocol downgrade attacks
  • Certificate pinning in sensitive applications adds protection against compromised certificate authorities

Protection Against Cross-Site Request Forgery (CSRF)

  • Anti-CSRF tokens are unique per session and validated server-side, ensuring requests originate from your application's forms
  • SameSite cookie attribute restricts when cookies are sent with cross-origin requests, providing browser-level CSRF protection
  • State-changing operations should never use GET requests, which are trivially triggered via image tags or links

Protection Against Cross-Site Scripting (XSS)

  • Output encoding transforms special characters into safe representations based on context (HTML, JavaScript, URL, CSS)
  • Content Security Policy (CSP) headers restrict which scripts can execute, containing damage even if XSS vulnerabilities exist
  • DOM-based XSS requires client-side validation since the malicious payload never touches the server

Compare: CSRF vs. XSS—CSRF tricks authenticated users into performing unwanted actions (exploits trust the server has in the browser), while XSS injects malicious scripts into pages viewed by other users (exploits trust the user has in the website). Defense mechanisms are completely different.


Operational Security Practices

Secure code requires secure processes. Security is a continuous practice, not a one-time achievement.

Secure Error Handling and Logging

  • Generic user-facing errors prevent information disclosure; detailed stack traces belong only in secured logs
  • Centralized, tamper-evident logging creates an audit trail for incident response and forensic analysis
  • Log injection prevention requires sanitizing data written to logs, preventing attackers from corrupting your audit trail

Regular Security Updates and Patch Management

  • Dependency scanning identifies vulnerable libraries in your software supply chain before attackers exploit them
  • Patch prioritization based on severity and exploitability ensures critical vulnerabilities are addressed first
  • Automated update pipelines reduce the window between patch availability and deployment

Code Review and Security Testing

  • Static Application Security Testing (SAST) analyzes source code for vulnerabilities without executing the program
  • Dynamic Application Security Testing (DAST) tests running applications, finding issues that only manifest at runtime
  • Security-focused code review catches logic flaws and design issues that automated tools miss

Secure Coding for Mobile Applications

  • Platform-specific secure storage (Keychain on iOS, Keystore on Android) protects sensitive data from other apps
  • Certificate pinning is especially critical on mobile, where users may connect through untrusted networks
  • Code obfuscation adds a layer of protection against reverse engineering, though it's not a substitute for server-side security

Compare: SAST vs. DAST—SAST finds vulnerabilities early in development but produces more false positives, while DAST tests actual application behavior but requires a running environment. Mature security programs use both.


Quick Reference Table

ConceptBest Examples
Injection PreventionPrepared statements, input validation, output encoding
Authentication SecurityMFA, strong password hashing (bcrypt/Argon2), session management
Access ControlLeast privilege, RBAC, regular permission audits
Cryptographic StorageSalted hashing, established libraries, proper key management
Transport SecurityHTTPS/TLS, HSTS, certificate validation
Client-Side Attack PreventionCSP headers, anti-CSRF tokens, SameSite cookies
Secure Development LifecycleCode review, SAST/DAST, patch management
Information ProtectionGeneric error messages, secure logging, file upload validation

Self-Check Questions

  1. Which two practices both defend against injection attacks but operate at different layers of the application stack? Explain how they complement each other.

  2. A system stores passwords using SHA-256 without salts. Identify two specific vulnerabilities this creates and which secure coding practice addresses each.

  3. Compare and contrast CSRF and XSS attacks: What trust relationship does each exploit, and why do they require completely different defensive measures?

  4. An FRQ describes an application where users gradually accumulate permissions they no longer need. Which principle is being violated, and what practices would remediate this?

  5. Why should password hashing algorithms be "slow," while encryption algorithms prioritize speed? Connect your answer to the specific threat models each addresses.