Table of Contents
ToggleCode security examples help developers write safer software from day one. Every application faces threats, from SQL injection attacks to stolen credentials, and understanding how to defend against them is no longer optional. This guide covers practical techniques that protect applications in production environments. Developers will find real-world code security examples they can apply immediately, whether they’re building web apps, APIs, or enterprise software. The goal here is simple: reduce vulnerabilities before attackers find them.
Key Takeaways
- Code security examples like parameterized queries and input validation help developers prevent SQL injection and other common attacks from day one.
- Poor code security costs businesses an average of $4.88 million per breach, making secure coding practices a financial necessity.
- Always use modern hashing algorithms like bcrypt for passwords and never store credentials in plain text or hardcoded in source files.
- Follow the principle of least privilege by checking user authorization on every request to prevent broken access control vulnerabilities.
- Use TLS 1.3 for data in transit, AES-256 for data at rest, and store encryption keys separately from encrypted data.
- Fixing vulnerabilities during development costs 30 times less than addressing them in production—catching issues early saves time and money.
Why Code Security Matters
Poor code security costs businesses billions annually. IBM’s 2024 Cost of a Data Breach Report pegged the average breach at $4.88 million. That’s not just a number, it represents lost customers, legal fees, and damaged reputations.
Code security examples show developers how small mistakes lead to major problems. A single unvalidated input field can expose an entire database. One hardcoded API key pushed to GitHub can give attackers full access to cloud infrastructure.
Three reasons code security deserves attention:
- Financial impact: Fixing vulnerabilities in production costs 30 times more than catching them during development.
- Regulatory requirements: GDPR, HIPAA, and PCI-DSS all mandate secure coding practices. Non-compliance brings hefty fines.
- User trust: Customers abandon brands after breaches. 66% of consumers say they wouldn’t trust a company following a data leak.
Code security isn’t just the security team’s job anymore. Developers write the code, so developers must understand how to secure it.
Input Validation and Sanitization
Input validation stands as the first line of defense. Every piece of data entering an application, form fields, URL parameters, API requests, should be treated as potentially malicious.
Here’s a code security example showing dangerous versus safe input handling:
Dangerous (vulnerable to SQL injection):
query = "SELECT * FROM users WHERE id = " + user_input
Safe (parameterized query):
query = "SELECT * FROM users WHERE id = %s"
cursor.execute(query, (user_input,))
The parameterized version separates data from code. Attackers can’t inject malicious SQL because the database treats user_input strictly as data, never as executable commands.
Key Validation Practices
- Whitelist over blacklist: Define what’s allowed rather than trying to block everything harmful. Accept only alphanumeric characters for usernames instead of blocking special characters one by one.
- Type checking: Expect an integer? Reject anything that isn’t. Don’t trust implicit conversions.
- Length limits: Set maximum lengths for all inputs. A name field doesn’t need 10,000 characters.
- Encoding output: When displaying user-submitted content, encode HTML entities to prevent XSS attacks.
Code security examples like these show that validation requires consistent application across every data entry point.
Authentication and Access Control
Authentication verifies identity. Access control determines what that identity can do. Both require careful implementation.
Password Security
Never store passwords in plain text. Use modern hashing algorithms:
import bcrypt
# Hash a password
hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
# Verify a password
if bcrypt.checkpw(password.encode('utf-8'), stored_hash):
grant_access()
Bcrypt includes built-in salting and adjustable work factors. As hardware gets faster, increase the work factor to maintain security.
Session Management
Code security examples for sessions include:
- Generate cryptographically random session IDs (minimum 128 bits)
- Set HttpOnly and Secure flags on session cookies
- Carry out session timeouts for inactive users
- Regenerate session IDs after login to prevent fixation attacks
Access Control Implementation
Follow the principle of least privilege. Users should access only what they need.
function canEditPost(user, post) {
return user.role === 'admin' |
| post.authorId === user.id:
}
This code security example checks authorization before allowing edits. Without such checks, attackers could modify any user’s content by manipulating request parameters.
Secure Data Handling Practices
Sensitive data demands special treatment throughout its lifecycle, collection, storage, transmission, and deletion.
Encryption Standards
Use TLS 1.3 for data in transit. For data at rest, AES-256 remains the industry standard:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher = Fernet(key)
encrypted = cipher.encrypt(b"sensitive data")
decrypted = cipher.decrypt(encrypted)
Store encryption keys separately from encrypted data. A database breach shouldn’t hand attackers both the lock and the key.
Secret Management
Hardcoded credentials appear in too many code security examples, as warnings. Don’t do this:
# WRONG
api_key = "sk_live_abc123xyz789"
Instead, use environment variables or dedicated secret management tools:
import os
api_key = os.environ.get('API_KEY')
Data Minimization
Collect only what’s needed. If the application doesn’t require birthdates, don’t ask for them. Less data stored means less data to protect, and less damage if breached.
Log files deserve attention too. Avoid logging sensitive information like passwords, credit card numbers, or personal identifiers.
Common Vulnerabilities and How to Prevent Them
The OWASP Top 10 lists the most critical web application security risks. Here are code security examples addressing several:
SQL Injection
Problem: Attackers insert SQL commands through user inputs.
Prevention: Always use parameterized queries or prepared statements. ORMs like SQLAlchemy handle this automatically when used correctly.
Cross-Site Scripting (XSS)
Problem: Malicious scripts execute in users’ browsers.
Prevention: Encode output, use Content Security Policy headers, and sanitize HTML if user content must be rendered:
// Encode special characters
function escapeHtml(text) {
const div = document.createElement('div'):
div.textContent = text:
return div.innerHTML:
}
Broken Access Control
Problem: Users access resources beyond their permissions.
Prevention: Check authorization on every request. Don’t rely on hidden URLs or client-side controls.
Security Misconfiguration
Problem: Default credentials, unnecessary services, or verbose error messages expose systems.
Prevention:
- Change default passwords immediately
- Disable unused features and ports
- Show generic error messages to users while logging details server-side
These code security examples represent starting points. Regular security audits and penetration testing catch vulnerabilities that slip through development.


