PadhaikoAll subjects

Cryptography

Network and Cyber Security (ENCT 463)

Open in the Padhaiko app

2.1 Cryptography, its importance, plain text and cipher text

Cryptography provides the mathematical foundation for securing data both in transit (over untrusted networks) and at rest (on disks and cloud storage).

Definition

Core Cryptographic Terminology

Importance of Cryptography

  1. Confidentiality: Ensures eavesdroppers intercepting packets cannot read sensitive payloads.
  2. Data Integrity: Cryptographic hashes and MACs detect even a single-bit alteration in transit or storage.
  3. Authentication: Proves the identity of communicating hosts, servers, and message senders.
  4. Non-Repudiation: Digital signatures cryptographically bind a sender to a message so the sender cannot later deny authoring it.

2.2 Type of ciphers: Symmetric and Asymmetric ciphers, Block and Stream ciphers

Cryptographic ciphers are classified along two major dimensions: key relationship (symmetric vs. asymmetric) and data processing unit (block vs. stream).

1. Symmetric vs. Asymmetric Ciphers

AspectSymmetric Key CryptographyAsymmetric (Public-Key) Cryptography
Keys UsedSingle shared secret key for both encryption and decryptionKey pair: a public key (shared openly) and a private key (kept secret)
Key DistributionDifficult; requires a secure out-of-band channel or key-exchange protocolEasier; public keys can be distributed openly (authenticated via PKI)
Key Scaling ( users)Requires pairwise secret keysRequires only keys ( key pairs)
Speed & OverheadVery fast (– faster); suitable for bulk dataSlow (heavy modular/elliptic arithmetic); used for key exchange and signatures
Security ServicesConfidentiality, integrity (via MAC)Confidentiality, key exchange, authentication, non-repudiation (signatures)
Representative AlgorithmsAES, DES, 3DES, ChaCha20, RC4RSA, ECC, Diffie–Hellman, ElGamal, EdDSA

In practice, protocols like TLS use hybrid cryptography: asymmetric crypto establishes identity and exchanges a session key, and symmetric crypto (e.g., AES-GCM or ChaCha20) encrypts the bulk data stream.

2. Block Ciphers vs. Stream Ciphers

AspectBlock CipherStream Cipher
Processing UnitEncrypts fixed-size blocks (e.g., bits in DES, bits in AES) at a timeEncrypts bit or byte at a time by XORing plaintext with a pseudorandom keystream
PaddingRequires padding (e.g., PKCS#7) if plaintext is not a multiple of block sizeNo padding required; ciphertext length equals plaintext length
Diffusion & ConfusionHigh diffusion across bits within each block via multiple roundsRelies on keystream unpredictability; changing plaintext bit flips only ciphertext bit
Modes of OperationECB, CBC, CFB, OFB, CTR, GCMKeystream XOR: (must never reuse a key/nonce pair)
ExamplesDES, 3DES, AES, BlowfishRC4 (legacy/broken), ChaCha20, A5/1, Salsa20

2.3 Traditional ciphers: Substitution (Mono-alphabetic, Polyalphabetic) and Transposition ciphers

Classical ciphers illustrate Claude Shannon's two foundational design principles: confusion (obscuring the relationship between key and ciphertext, typically via substitution) and diffusion (spreading plaintext statistics across the ciphertext, typically via transposition).

1. Substitution Ciphers

Each plaintext symbol or group is replaced by another symbol according to a key.

2. Transposition Ciphers

Transposition rearranges the positions of plaintext characters without altering the characters themselves (pure diffusion):

AspectSubstitution CipherTransposition Cipher
TransformationReplaces characters with other characters; positions stay fixedKeeps original characters; permutes their positions
Shannon PrinciplePrimarily ConfusionPrimarily Diffusion
Frequency ProfileChanges letter counts (mono-alphabetic shifts/permutes frequencies; polyalphabetic flattens them)Exact plaintext letter frequencies remain unchanged
Example 1

Vigenère Encryption and Decryption (5 marks)

Encrypt the plaintext SECURE using the Vigenère cipher with keyword KEY (mapping ), and verify decryption of the first two letters.

Convert plaintext and repeating key to numeric indices ():

  • Plaintext SECURE: .
  • Keyword KEY repeated to length (KEYKEY): .

Apply for each letter:

Thus the ciphertext is CIAEVC.

Verify decryption on the first two characters using :

Answer:

Ciphertext: CIAEVC.


2.4 Symmetric Block Ciphers: DES, AES

1. Data Encryption Standard (DES)

Adopted in 1977, DES is a classic Feistel block cipher:

where the round function applies: (1) Expansion ( bits), (2) XOR with -bit subkey , (3) eight -bit S-boxes (non-linear substitution for confusion), and (4) -bit Permutation (diffusion).

2. Advanced Encryption Standard (AES)

Standardized by NIST in 2001 (Rijndael), AES is a non-Feistel Substitution–Permutation Network (SPN) operating on a -bit block arranged as a matrix of bytes (the state).

AspectDESAES
ArchitectureFeistel Network (encrypts half-block per round)Substitution–Permutation Network (transforms entire state)
Block Size bits bits
Key Size bits (effective), , or bits
Rounds, , or (by key size)
Security StatusBroken (brute-forced easily)Current global standard (quantum-resistant at 256-bit against Grover's)

2.5 Asymmetric ciphers: RSA, ECC

1. RSA (Rivest–Shamir–Adleman)

RSA relies on the computational intractability of factoring the product of two large primes.

Definition

RSA Key Generation, Encryption, and Decryption

  1. Key Generation:
    • Choose two distinct large primes and .
    • Compute modulus and Euler's totient .
    • Choose public exponent such that and .
    • Compute private exponent such that (via the Extended Euclidean Algorithm).
    • Public Key: . Private Key: (keep secret).
  2. Encryption (for message ):
  1. Decryption:

In production, textbook RSA must always be paired with randomized padding (OAEP for encryption, PSS for signatures) to prevent deterministic ciphertext attacks and small-message attacks.

2. Elliptic Curve Cryptography (ECC)

ECC performs public-key operations over the algebraic structure of an elliptic curve over a finite field :

AspectRSAECC
Hard Mathematical ProblemInteger Factorization Problem (IFP)Elliptic Curve Discrete Logarithm Problem (ECDLP)
Key Size for 128-bit Security bits bits
Speed & BandwidthFast signature verification; slower keygen and larger keysMuch faster key generation/signing and tiny keys/certificates
Primary ProtocolsLegacy TLS key transport, SSH, X.509 CAs, digital signaturesTLS 1.3 (ECDHE/ECDSA), mobile/IoT security, Signal, cryptocurrencies
Example 2

RSA Key Generation, Encryption, and Decryption (8 marks)

In an RSA system, choose primes and , and public exponent . (a) Compute , , and the private key . (b) Encrypt the plaintext and decrypt the resulting ciphertext to recover .

Compute modulus and Euler's totient :

Since , is a valid public exponent.

Find private exponent satisfying :

Public key is and private key is .

Encrypt using square-and-multiply:

Compute powers of :

Since :

Decrypt to verify :

Compute powers of :

Since :

First , and , so:

Answer:

(a) , , . (b) Ciphertext ; decrypting yields .


2.6 Message digest, Hash functions (MD5, SHA)

A cryptographic hash function maps an arbitrary-length input message to a fixed-length message digest .

Definition

Three Required Security Properties of Hash Functions

  1. Preimage Resistance (One-Wayness): Given a digest , it is computationally infeasible to find any message such that .
  2. Second-Preimage Resistance (Weak Collision Resistance): Given a specific message , it is computationally infeasible to find a different message with .
  3. Collision Resistance (Strong Collision Resistance): It is computationally infeasible to find any two distinct messages such that .

Additionally, good hashes exhibit a strong avalanche effect: flipping a single input bit changes roughly of the output digest bits unpredictably. By the birthday paradox, finding a collision on an -bit hash takes evaluations, which is why modern hashes require at least -bit outputs ( collision resistance).

MD5 and SHA Families

Comparison of Cryptographic Hash Functions
AlgorithmDigest SizeBlock SizeCollision Resistance (Ideal)Current Status
MD5 bits bits (broken in practice)Broken / Do not use
SHA-1 bits bits (broken in practice)Deprecated
SHA-256 (SHA-2) bits bitsRecommended standard
SHA-512 (SHA-2) bits bitsRecommended standard
SHA3-256 (SHA-3) bits-bit rateRecommended standard

2.7 Message authentication, Digital Signatures and Certificates

Sending an unkeyed hash alongside does not protect against an active attacker, because the attacker can modify to and simply recompute . Protecting both integrity and origin requires a secret key.

1. Message Authentication Codes (MAC & HMAC)

A MAC produces a short authentication tag using a shared secret key and message : . The receiver recomputes and verifies equality.

HMAC builds a provably secure MAC from any cryptographic hash function (e.g., HMAC-SHA256):

where is the block-padded key, repeated, and repeated. Because both sender and receiver share the same , a MAC provides integrity and authentication, but not non-repudiation (either party could have generated the tag).

2. Digital Signatures

A digital signature uses asymmetric cryptography to achieve integrity, origin authentication, and non-repudiation:

  1. Signing (Sender): Compute digest , then sign with the sender's private key:

Send to the receiver.

  1. Verification (Receiver): Independently compute and verify using the sender's public key . If valid, only the holder of could have produced for that exact message , preventing repudiation.

3. Digital Certificates (X.509)

A public key alone does not prove who owns it—an attacker in a Man-in-the-Middle position could substitute their own public key. An X.509 Digital Certificate binds a subject's identity (e.g., bank.example.com) to its public key, digitally signed by a trusted Certificate Authority (CA).

Key X.509 certificate fields include:


2.8 Public Key Infrastructure (PKI) and its importance

Public Key Infrastructure (PKI) is the ecosystem of hardware, software, policies, roles, and procedures needed to create, manage, distribute, use, store, and revoke digital certificates.

Core PKI Components

Example 3

How PKI and Digital Signatures Defeat a MITM Attack (Exam Model) (5 marks)

Explain step by step how a web browser uses PKI and X.509 digital certificates to detect an attacker who intercepts a TLS connection and injects a forged server public key.

Present the certificate chain during the TLS handshake: When the browser connects to portal.edu.np, the server (or attacker) sends its leaf X.509 certificate (plus any intermediate CA certificates) claiming the domain name and containing a public key.

Verify the signature chain up to a pre-installed Root CA: The browser hashes the certificate's body and verifies the CA's signature using the parent CA's public key, walking up to an implicitly trusted Root CA stored in the OS/browser trust store. Because the attacker lacks the trusted CA's private key, a forged certificate fails signature verification (or chains to an untrusted self-signed root).

Check identity, validity, and revocation status: The browser verifies that portal.edu.np matches the certificate's Subject Alternative Name (SAN), that the current date lies within Not Before–Not After, and that the certificate is not revoked (via OCSP or CRL). Finally, the server proves possession of the corresponding private key by signing the TLS handshake transcript.

Answer:

An attacker cannot obtain a valid CA-signed certificate for portal.edu.np without passing RA verification or possessing a trusted CA's private key; thus the browser aborts the connection on signature, SAN, or revocation check failure.


Exercises

Question 1

Using RSA with , , and , find , , and the private exponent . Encrypt the plaintext and show decryption back to .

Compute , , and :

Check . Solve : , so .

Encrypt :

Compute powers of : , , , . Since :

Decrypt :

Compute powers of : , , , , . Since :

Answer:

, , ; ; decryption recovers .

Question 2

Encrypt the word NET () using (a) a Caesar cipher with key , and (b) a Vigenère cipher with key BTB ().

Part (a) — Caesar cipher ():

Ciphertext is QHW.

Part (b) — Vigenère cipher (BTB ):

Ciphertext is OXU.

Answer:

(a) QHW (b) OXU.

Question 3

Compare symmetric and asymmetric cryptography on key management, computational speed, and supported security services, and explain why TLS uses a hybrid approach.

Compare symmetric and asymmetric schemes:

  • Key management: Symmetric cryptography requires a shared secret key exchanged safely beforehand ( keys for parties), whereas asymmetric cryptography uses a public/private key pair ( keys) where the public key is shared openly.
  • Speed: Symmetric ciphers (AES, ChaCha20) execute using fast bitwise/substitution operations in hardware; asymmetric algorithms (RSA, ECC) perform modular exponentiation or elliptic curve scalar multiplication and are orders of magnitude slower.
  • Services: Both provide confidentiality; however, symmetric MACs cannot provide third-party non-repudiation because both parties hold the same secret key, whereas asymmetric digital signatures can.

Explain hybrid cryptography in TLS: TLS uses asymmetric cryptography during the handshake to authenticate the server (via X.509 certificates) and agree on a fresh ephemeral symmetric session key (via ECDHE), then switches to fast symmetric authenticated encryption (AES-GCM or ChaCha20-Poly1305) for all application data.

Answer:

Symmetric crypto is fast with harder key distribution and no non-repudiation; asymmetric crypto solves key exchange and non-repudiation but is slow. Hybrid schemes (like TLS) combine asymmetric key exchange/authentication with symmetric bulk encryption.

Question 4

Describe the internal structure of a single AES round (for AES-128) and explain how it differs from the Feistel structure of DES.

Outline the four AES round operations on the byte state:

  1. SubBytes: Non-linear byte substitution via an -bit S-box over (confusion).
  2. ShiftRows: Cyclic left shifts of rows by bytes (diffusion across columns).
  3. MixColumns: Linear matrix multiplication of each column over (omitted in round ).
  4. AddRoundKey: Bitwise XOR of the -bit state with the round subkey.

Contrast with DES's Feistel network: DES operates on -bit blocks split into two -bit halves, transforming only one half per round via and swapping halves over rounds—so encryption and decryption use identical round logic in reverse subkey order. AES is a non-Feistel Substitution–Permutation Network (SPN) that transforms the entire -bit state in every round ( rounds) and requires inverse transformations (InvShiftRows, InvSubBytes, InvMixColumns) for decryption.

Answer:

Each AES round applies SubBytes, ShiftRows, MixColumns (skipped in the final round), and AddRoundKey to the full -bit SPN state, unlike DES's -bit Feistel half-block swap across rounds with a -bit effective key.

Question 5

Distinguish between a cryptographic hash, an HMAC, and a digital signature. Which security properties does each guarantee, and what role do CRL and OCSP play in PKI?

Compare Hash, HMAC, and Digital Signature:

  • Cryptographic Hash (): Unkeyed fixed-size digest; detects accidental corruption but not an active attacker (who can alter and recompute ).
  • HMAC (): Keyed hash using a shared secret ; guarantees integrity and data origin authentication between key holders, but not non-repudiation.
  • Digital Signature (): Asymmetric signature verified by anyone holding ; guarantees integrity, authentication, and non-repudiation.

Explain CRL and OCSP in PKI: Because private keys can be compromised before certificate expiration, PKI must revoke invalid certificates early. A CRL is a periodically published CA-signed list of revoked serial numbers, while OCSP lets clients query certificate status (good/revoked) in real time (with OCSP Stapling avoiding extra round trips and privacy leaks).

Answer:

Hashes give unkeyed digests, HMACs add shared-key integrity/authentication, and digital signatures add public-key non-repudiation; CRL and OCSP allow PKI relying parties to reject certificates revoked prior to expiry.

← Basics of Network and Cyber SecurityNetwork Security Measures →