Lesson 42 • Advanced

    Secure Coding Practices

    Security isn't a feature you add later — it's a mindset from line one. A single SQL injection can leak your entire database. One missing input validation can give attackers admin access. This lesson covers the OWASP Top 10 vulnerabilities and their Java-specific defenses.

    Before You Start

    You should know JDBC (SQL injection prevention), REST APIs (input validation), and Exception Handling (secure error messages). Understanding HTTP basics is essential.

    What You'll Learn

    • ✅ OWASP Top 10 vulnerabilities and Java defenses
    • ✅ SQL injection prevention with PreparedStatement
    • ✅ XSS prevention with output encoding
    • ✅ Secure password hashing with bcrypt
    • ✅ CSRF tokens and session management
    • ✅ Input validation and secure deserialization

    1️⃣ OWASP Top 10 — Java Defenses

    The OWASP Top 10 is the industry standard list of critical web application security risks. Every vulnerability here has been exploited in real breaches — and every one has a straightforward Java defense.

    VulnerabilityAttackJava Defense
    SQL InjectionMalicious SQL via inputPreparedStatement, JPA
    XSSScript injection in HTMLOutput encoding
    Broken AuthWeak passwords, no lockoutSpring Security + bcrypt
    Insecure Deser.Malicious serialized objectsAvoid Java serialization
    CSRFForged requestsCSRF tokens (Spring default)

    Try It: XSS Attack & Defense

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Cross-Site Scripting (XSS) — Attack and Defense
    
    console.log("=== XSS Attack & Defense ===\n");
    
    // HTML encoder (simulating OWASP Encoder)
    function escapeHtml(str) {
      return str
        .replace(/&/g, '&')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#x27;');
    }
    
    // 1. Stored XSS attack
    console.log("1. STORED XSS ATTACK:");
    let maliciousComment = '<script>document.location="http://e
    ...

    2️⃣ Password Security

    Analogy: Hashing a password is like putting a letter through a paper shredder. You can verify that a new letter matches the shredded pattern, but you can never reconstruct the original. bcrypt adds salt (randomness) and a work factor (intentional slowness) to make brute-force attacks impractical.

    Never: Plain text, MD5, SHA-1 (cracked in seconds)

    Always: bcrypt with cost ≥ 12 (~250ms per hash)

    Try It: Password Hashing & Brute Force

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Password hashing and brute force resistance
    
    console.log("=== Password Security ===\n");
    
    // Simple hash simulation
    function simpleHash(str) {
      let hash = 0;
      for (let i = 0; i < str.length; i++) {
        hash = ((hash << 5) - hash) + str.charCodeAt(i);
        hash |= 0;
      }
      return Math.abs(hash).toString(16).padStart(8, "0");
    }
    
    // bcrypt simulation (with salt and work factor)
    function bcryptHash(password, cost) {
      let salt = Math.random().t
    ...

    Critical Security Rules

    • ⚠️ NEVER concatenate user input into SQL — always PreparedStatement with ? placeholders
    • ⚠️ NEVER store passwords in plain text — use bcrypt with cost ≥ 12
    • ⚠️ NEVER trust client input — validate on server side, even if client validates
    • ⚠️ NEVER log sensitive data — passwords, credit cards, tokens, session IDs
    • ⚠️ NEVER hardcode secrets — use environment variables or secret managers

    Security Checklist

    • 💡 ✅ All SQL uses PreparedStatement or JPA
    • 💡 ✅ All output is HTML-encoded (prevents XSS)
    • 💡 ✅ Passwords hashed with bcrypt (cost ≥ 12)
    • 💡 ✅ HTTPS everywhere with HSTS header
    • 💡 ✅ CSRF protection enabled (Spring Security default)
    • 💡 ✅ Dependencies scanned for CVEs (Dependabot/Snyk)

    Try It: Security Vulnerability Scanner

    Try it Yourself »
    JavaScript
    // 💡 Try modifying this code and see what happens!
    // Security vulnerability scanner simulation
    
    console.log("=== Security Vulnerability Scanner ===\n");
    
    // Simulated code analysis
    let codeSnippets = [
      {
        code: 'String sql = "SELECT * FROM users WHERE name='" + input + "'"',
        vulnerability: "SQL Injection",
        severity: "CRITICAL",
        fix: 'Use PreparedStatement: "SELECT * FROM users WHERE name = ?"',
        cwe: "CWE-89"
      },
      {
        code: 'response.getWriter().write("<div>" + userInpu
    ...

    📋 Quick Reference

    ThreatDefenseLibrary
    SQL InjectionPreparedStatementJDBC / JPA
    XSSEncode.forHtml()OWASP Encoder
    PasswordsBCrypt.hashpw()jBCrypt / Spring
    CSRFCsrfFilterSpring Security
    CVE Scanningdependency-checkOWASP DC / Snyk

    🎉 Lesson Complete!

    You now write Java code that's secure by default — protecting against the most common attack vectors! Next: JavaFX — building desktop GUI applications.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service