423.31 Cryptography basics

Learn how cryptography is used in software code to protect passwords, secure data, and verify identity and how to avoid common mistakes.

Cryptography underpins secure software, from protecting passwords to securing data in transit. When used correctly, it helps prevent broken authentication and session hijacking; when used poorly, it creates a false sense of security. This topic explores cryptographic tools and their role in secure coding.

Objectives

  • Understand how hashing, encryption and secure token generation work in code.

  • Recognise standard cryptographic techniques used in authentication and data protection.

  • Identify implementation mistakes (e.g. outdated algorithms, missing salts) and how they can contribute to broken authentication or session management flaws.

Syllabus references

Secure software architecture
  • Use and explain the contribution of cryptography and sandboxing to the ‘security by design’ approach in the development of software solutions

  • Design, develop and implement secure code to minimise vulnerabilities in user action controls, including: – broken authentication – session management flaws

Why cryptography in code matters

Cryptography isn't just a design principle — it’s something developers need to implement carefully in code.

If misused, cryptographic tools such as and encryption can create a false sense of security. For example:

  • Using outdated algorithms like

  • Forgetting to salt passwords before hashing

  • Hardcoding secret keys in source code

  • Reusing tokens or using weak randomness

1. Password hashing

Hashing is the process of converting input data (like a password or file) into a fixed-length string of characters, using a mathematical function called a hash function. The result is called a hash or digest.

Hashing is:

  • One-way – it cannot be reversed to get the original input

  • Deterministic – the same input always gives the same output

  • Used for integrity and security – like storing passwords, verifying file changes, or indexing data

In secure coding, hashing is used to protect passwords and detect tampering. However, hashing must be combined with salt and a strong algorithm (like SHA-256 or bcrypt) to resist attacks like or brute-force.

Plain text passwords should never be stored or compared directly. Instead, hash them using a one-way function.

A hash is a one‑way transformation of data. To store passwords securely, compute a hash instead of saving the plain text. Use a slow, purpose-built password hash (like bcrypt or Argon2) rather than fast general-purpose hashes such as MD5 or SHA-256. Fast hashes allow attackers to brute‑force millions of guesses per second.

import bcrypt

def hash_password(password):
    salt = bcrypt.gensalt()
    return bcrypt.hashpw(password.encode(), salt)

This code uses bcrypt, which automatically generates a salt and intentionally slows down hashing

2. Salted hashes

To make hashes more secure, add a salt — a random value stored alongside the password to prevent .

A salt is a random value added to each password before hashing. It ensures that identical passwords produce different hashes, thwarting pre‑computed “rainbow table” attacks. Always generate a unique salt per user.

def create_hash(password):
    salt = bcrypt.gensalt()
    return bcrypt.hashpw(password.encode(), salt)

Bcrypt is slow by design, making brute-force attacks much harder. It also handles salting internally.

3. Symmetric encryption

When you need to encrypt and later decrypt data (e.g. API tokens or private messages), use a modern, high‑level encryption library with secure defaults. Never hard‑code encryption keys in your codebase.

from cryptography.fernet import Fernet

key = Fernet.generate_key()
cipher = Fernet(key)

ciphertext = cipher.encrypt(b"Secret message")
plaintext  = cipher.decrypt(ciphertext)

Store encryption keys securely (for example, in environment variables or a secrets manager); if the key is exposed, anyone can decrypt the data

4. Secure tokens and randomness

Tokens are used for sessions, API access and password resets. They must be long, unique and generated with a cryptographically secure random number generator. Use Python’s secrets module to generate unguessable values.

import secrets
token = secrets.token_urlsafe(32)  # returns a 43-character URL-safe token

Always validate tokens on the server, set sensible expiration times and revoke them on logout to prevent session hijacking.

Linking cryptography to authentication & session management

Cryptography is integral to secure authentication. Strong password hashing and salting prevent attackers from discovering credentials. Secure token generation supports stateless authentication schemes such as JSON Web Tokens. Conversely, using outdated hashes, weak randomness, or hard‑coded keys can lead to broken authentication and session management flaws.

For example:

  • Storing passwords using MD5 or SHA‑1 makes them easy to crack.

  • Reusing predictable session tokens allows attackers to hijack sessions.

  • Embedding secret keys in source code exposes them to anyone who can access the repository.

To prevent these issues:

  • Always choose slow password hashes (bcrypt, Argon2) with unique salts.

  • Use a cryptographically secure random generator for tokens and session IDs.

  • Keep encryption keys and tokens out of the codebase and rotate them regularly.

  • Combine cryptography with proper session management practices.

Common mistakes & how to avoid them

  • Using outdated algorithms Avoid MD5 and SHA‑1; choose bcrypt or Argon2

  • Forgetting to salt Hashes without salts are vulnerable to rainbow tables

  • Hard‑coding keys Secrets should be stored securely outside your codebase

  • Predictable tokens Use secrets to generate random tokens and set expiration times

  • Assuming cryptography is a panacea Cryptography must be combined with access control, input validation and safe coding practices.

Summary

Cryptography is a critical component of secure software architecture. By hashing and salting passwords, encrypting sensitive data, and generating secure tokens, you protect users’ identities and your system’s integrity. The syllabus expects you to implement these techniques correctly and understand how poor implementation can lead to broken authentication and session flaws. Sandboxing – covered in topic 420.3 – complements cryptography by isolating untrusted code. Together with proper session management, these practices ensure that security is built into your software from the ground up.

Questions

1. Define cryptography in the context of secure software.

Answer

Cryptography in secure software refers to the use of mathematical techniques to protect information by transforming it into a form that can only be read or used by those with the correct key. It ensures confidentiality, integrity, authentication and non-repudiation of data in software systems. Typical uses include encrypting messages, securing passwords, and verifying the identity of users and systems.

2. Outline TWO ways that cryptography secures web applications, giving examples.

Answer

Data encryption over HTTPS Cryptography ensures that data transferred between a browser and a server is encrypted using SSL/TLS protocols, making it unreadable to anyone intercepting the traffic. For example, a login form sent over HTTPS protects credentials from being captured by attackers.

Password hashing Instead of storing passwords in plain text, cryptographic hash functions (e.g. bcrypt or SHA-256) convert them into irreversible strings. Even if the database is compromised, attackers cannot directly retrieve the original passwords.

3. Explain the process of password hashing and how it helps to secure software systems.

Answer

Password hashing involves converting a password into a fixed-length string using a cryptographic hash function. The result (called a hash) is stored in the database instead of the original password. When a user logs in, their input is hashed again and compared to the stored hash. Since hashes are one-way functions, even if the hash is stolen, it’s computationally difficult to reverse it to reveal the password. This protects user credentials in case of a data breach.

4. Explain salted hashing and why it is preferred for the transmission of passwords.

Answer

Salted hashing involves adding a unique, random value (called a salt) to each user’s password before hashing. This ensures that even if two users have the same password, their stored hashes will be different. Salted hashes prevent attackers from using precomputed lookup tables or rainbow tables to reverse-engineer passwords. Although salted hashes are typically stored rather than transmitted, they make hash storage significantly more secure and are a standard part of secure password handling.

5. Define symmetric encryption and how it is used to secure APIs.

Answer

Symmetric encryption is a method where the same key is used for both encryption and decryption of data. In the context of APIs, symmetric encryption might be used to securely transfer data between client and server once both have established a shared secret key (e.g. during a TLS handshake). It is efficient and fast, making it suitable for encrypting session tokens or API responses that require confidentiality.

6. What are tokens, and how are they used to improve security in web apps?

Answer

Tokens are small pieces of data used to represent user identity or session state securely and temporarily. They are often issued after successful authentication and are sent with each request to prove the user's identity. Common examples include JWT (JSON Web Tokens) and OAuth tokens. Tokens improve security by reducing the need to resend passwords and can carry limited access scopes, expiration times, and cryptographic signatures to prevent tampering.

7. How is cryptography used in session management?

Answer

Cryptography is used in session management to secure the transmission and storage of session identifiers. For example, a session token might be encrypted or signed to ensure that it cannot be forged or altered. Secure cookies may use HTTPS and cryptographic signatures to prevent tampering. Techniques like token expiration and refresh tokens also help mitigate the risk of session hijacking or replay attacks.

8. Make a table of common mistakes in securing web apps with cryptographic methods and how they can be addressed.

Answer
Mistake
Risk
How to address it

Using outdated or broken algorithms (e.g. MD5)

Hashes can be cracked quickly using modern hardware

Use modern algorithms like bcrypt, SHA-256 with salting

Hardcoding keys in source code

Keys can be leaked via code repositories or logs

Store keys in environment variables or a secure key vault

Not using HTTPS

Data can be intercepted during transmission

Always use HTTPS for all API endpoints and form submissions

Reusing or in encryption

Can expose patterns and weaken encryption

Use unique IVs (initialisation vectors) for each encryption operation

Storing passwords in plain text

Entire user base is compromised if database is leaked

Always hash passwords with a salt and use a slow hash algorithm

Failing to expire tokens or sessions

Increases the risk of replay or session hijacking attacks

Set reasonable token expiry and enforce session timeouts

Last updated

Was this helpful?