(archived) Applied Cryptography Notes
Abbreviated as "Big Network Security and Data".
Overview of Cryptography
The four properties of modern cryptography: confidentiality, integrity, authentication, and non-repudiation.
Three periods: classical cryptography (algorithm secrecy), modern cryptography (key secrecy), and contemporary cryptography.
Attacks on cryptographic systems: ciphertext-only attack, known-plaintext attack, chosen-plaintext attack, chosen-ciphertext attack.
Kerckhoffs' principle: Security depends only on the secrecy of the key, not the algorithm. Otherwise, it is a "restricted cryptographic algorithm."
Security classifications: unconditional security, computational security, provable security.
Functions of cryptographic algorithms: encryption, hashing, digital signatures, identity authentication, key agreement.
Private keys are used for signing, public keys are used for verification.
Homework (p14):
1-1, 1-2, 1-4, 1-6, 1-7
Classical Cryptography
Monoalphabetic Substitution Cipher
Caesar
Affine Cipher
Key Phrase Cipher
Place the key at the beginning, and arrange the remaining letters after the key to form the substitution table.
Disadvantages
Word frequency analysis.
Polyalphabetic Substitution Cipher
Vigenère
Hill Cipher
where
Advantages and Disadvantages:
- Resistant to ciphertext-only attacks; large key space.
- Vulnerable to known-plaintext attacks and chosen-plaintext attacks.
OTP (Vernam)
The key must not be reused, and it is theoretically unbreakable.
Playfair
Remove duplicate letters from the key, place them at the beginning, and append the remaining letters. Treat "i" and "j" as occupying the same cell. Arrange them into a 5×5 matrix.
Group the plaintext into pairs (denoted as p1, p2). Then:
- If they are in the same row, the ciphertext is the letter to the right of each plaintext letter (the rightmost wraps around to the first in the row).
- If they are in the same column, the ciphertext is the letter below each plaintext letter (the bottommost wraps around to the top in the column).
- If neither, take the opposite diagonal as the ciphertext, where each ciphertext letter shares the same row as its corresponding plaintext letter.
- If the two letters are the same (or only one remains), insert a predetermined letter (e.g., "x") in the middle (to the right).
Chained Cipher Algorithm
Uses the result of encrypting one plaintext as the encryption key for the next plaintext.
Disadvantage: Error propagation.
Substitution Cipher
Cyclic Permutation
The key specifies the permutation of positions.
It is a special case of the Hill cipher, belonging to the category of linear transformation ciphers.
Columnar Transposition Cipher
Fill the plaintext into a matrix row by row, and the key specifies the order in which columns are read.
Rotor Machine Cipher
Not tested.
Homework:
2.1 2.4 2.5 2.7 2.8 2.10 2.11 2.13 2.14 2.15
Block Cipher
Design Principles
- Diffusion Principle: Each bit of the plaintext should affect as many bits of the ciphertext as possible, and each bit of the ciphertext should be influenced by as many bits of the plaintext as possible.
- Confusion Principle: Even if an adversary obtains both the plaintext and the ciphertext, they should not be able to deduce any information about the key.
- Software Design: Use sub-blocks and simple operations.
- Hardware Implementation: Strive to use regular structures.
If
, it is an idempotent cryptosystem, such as affine ciphers, permutation ciphers, etc. Iterative cryptosystems must be non-idempotent.
Typical Structures
- SPN Structure: Faster diffusion, but encryption and decryption are not similar.
- Feistel Structure: Encryption and decryption are similar, with slower diffusion (at least two rounds are required to change every bit of the input).
DES (Key Points)
- Security entirely depends on the confidentiality of the key.
- Key length is 64 bits (8 bits used for parity check).
Steps:
- Initial Permutation (IP) of the plaintext.
expansion of to obtain : Divide into 8 blocks, denoted as to , then prepend the last of the previous block to , and append the first of the next block to . - Add parity bits to
(multiple of 8), obtain C[0]
andD[0]
via, left-shift once to get C[1]
andD[1]
, and obtain the 48-bitvia PC-2
. -box transformation : Different blocks use different -boxes. Take to as the row of the -box, and as the column of the -box (big-endian). The value obtained from the lookup table serves as the key block. (Key Point) -box transformation. - XOR with
to obtain , completing one round of iteration. - After 16 rounds of iteration, perform an inverse IP permutation.
Advantages:
- Encryption and decryption structures are identical.
- High strength.
Proof of complement symmetry:
For the
function, Thus, the round function
, and further Let
be the swap of left and right blocks, and . Then the encryption function
Improvement: Triple DES.
Block Cipher Modes of Operation
- ECB: Each block of plaintext is encrypted into the corresponding ciphertext block. The last incomplete block (less than 64 bits) is padded with a random string. (Essentially a large monoalphabetic substitution.)
- CBC (Commonly Used): The current plaintext block is XORed with the previous ciphertext block before encryption. The initial vector must be kept strictly confidential.
- CFB: Encryption is performed in units much smaller than the block size. The ciphertext depends on all previous plaintext.
- OFB: Feedback occurs within the block. (Vulnerable to tampering.)
- CTR: Allows parallel processing and precomputation, and can generate a good pseudorandom number sequence.
How to Choose:
- Security
- Efficiency
- Functionality
AES (Key Points)
Mathematical Foundations
Multiplication in the finite field
x-multiplication: Since the modulus chosen for AES is 0x11b
, i.e., 0x1b
.
Cross multiplication: Refers to the multiplication of two degree-4 polynomials in
Here, the dot product between terms corresponds to multiplication in
Steps
Key length: 128 bits.
- SubBytes: Lookup table substitution.
- ShiftRows: Cyclically shift the
-th row left by bytes. - MixColumns (Key step): For each column, perform a cross multiplication, where
is fixed as 3112H
. - AddRoundKey: XOR with the round key column by column.
Overall process:
AddRoundKey()
for i from 1 to 9:
SubBytes()
ShiftRows()
MixColumns()
AddRoundKey()
SubBytes()
ShiftRows()
MixColumns()
Other Symmetric Encryption Algorithms
- IDEA (Block size 64bit, Key length 128bit, Non-Feistel structure)
- RC6 (Block size 128bit, Key length 128, 192, 256bit, Feistel structure)
- SM4 (Block size 128bit, Key length 128bit, Asymmetric Feistel structure)
Asymmetric Encryption
Disadvantages of Symmetric Cryptography
- Poor system openness (how to transmit the key)
- Difficult key management:
devices require keys. - Issues with digital signatures.
Characteristics of Public Keys
- Convenient key management with high openness
- High computational cost for encryption and decryption
Functions of a Public Key
- Conventional key distribution and negotiation
- Digital signatures
- Encryption and decryption (less efficient and not recommended for direct use)
RSA
Specific process: Omitted
Using the Chinese Remainder Theorem (CRT) to achieve fast computation in RSA
Example: Compute
, where , and are distinct primes, and is the private key. Solution: Use Euler's theorem to compute
and separately, then apply CRT to compute .
Miller-Rabin
Fermat's Little Theorem is a necessary condition for a modulus to be prime.
Quadratic Residue Theorem: If
Pseudocode:
# false rate: 1 - 4^(-s)
def WITNESS(a, n):
if pow(a, n-1, n) != 1:
return FALSE
else while n % 2 == 0:
n /= 2
if pow(a, n-1, n) != 1 or -1:
return FALSE
return TRUE
for i from 1 to s:
if WITNESS(integers[i], n) == FALSE
return NOT_PRIME
return PRIME
ElGamal
Description
System parameters:
Select a private key
Encryption:
- Choose a random number
.
Decryption:
Features
- Non-deterministic (dependent on k)
- Ciphertext space is larger than the plaintext space
ECC
SM2 also employs the elliptic curve cryptography system.
Elliptic Curves over the Real Number Field
The equation
If points
It follows that the additive inverse of a point has the same
Thus, the addition operation is defined as follows: draw the line through
From an algebraic perspective,
Elliptic Curves over Finite Fields
Focus on
; is not included in the exam.
It can be proven that an elliptic curve over a finite field forms a cyclic group under the +
operation.
The definition of addition involves taking the corresponding coordinates modulo
Example: Find the number of points in
:
Answer: There are 13 points in total (don't forget the point at infinity!).
ElGamal on Elliptic Curves
Let
be the smallest integer such that . ECDLP: Given
and , finding such that is computationally hard. Similar to the Discrete Logarithm Problem (DLP), point addition can be analogized to modular multiplication, and point doubling to exponentiation.
System parameters:
Key generation: Select a private key
Encryption:
- Map the plaintext message
to a point . - Select a random number
.
Decryption:
- Apply the inverse mapping to
to recover .
Menezes-Vanstone
Primarily addresses the problem of mapping plaintext
to .
System parameters:
Key generation: Select private key
Encryption:
- Select a random number
Decryption:
(Note that , so ) - Obtain
from
Example: Let base point
in be , key , plaintext be , random number , compute the ciphertext. Solution: Compute public key
Therefore, the ciphertext is
Code implementation (done while working on homework at night)
# ECC en&decrypt in GF(p)
# 4/24/2023 junyu33
import gmpy2
a = 1
b = 6
p = 11
G = [2, 7]
d_A = 5
def Add(A: list, B: list) -> list:
lamb = 0
if A == B:
lamb = (3*A[0]*A[0]+a)*gmpy2.invert(2*A[1], p) % p
else:
lamb = (B[1]-A[1])*gmpy2.invert(B[0]-A[0], p) % p
s = (lamb**2 - A[0] - B[0]) % p
t = (lamb*(A[0]-s) - A[1]) % p
return [s,t]
def Mult(X: list, t: int) -> list:
R = X
t = t - 1
while t:
if t & 1:
R = Add(R, X)
X = Add(X, X)
t >>= 1
return R
def enc(M: list, G: list, k: int):
c_1 = Mult(G, k)
P_A = Mult(G, d_A)
Y = Mult(P_A, k)
c_2 = Y[0] * M[0] % p
c_3 = Y[1] * M[1] % p
print(c_1, c_2, c_3)
def dec(c_1: list, c_2: int, c_3: int):
Y = Mult(c_1, d_A)
z_1 = Y[0]
z_2 = Y[1]
m_1 = c_2 * gmpy2.invert(z_1, p) % p
m_2 = c_3 * gmpy2.invert(z_2, p) % p
print(m_1, m_2)
enc([7,9],G,3)
Hash
SHA-1 (Cracked)
big-endian
2**64-1 -> 160 bit
Steps
- Padding: origin +
1000...000
(length448 - len % 512
) +len
- Initial MD buffer:
A = 67452301, B = EFCDAB89, C = 98BADCFE, D = 10325476, E = C3D2E1F0
- Process the message in 512-bit blocks:
A, B, C, D, E ← [(A << 5) + f_t(B, C, D) + E + W_t + K_t], A, (B << 30), C, D
A total of 80 rounds are performed, where:is the logical function, defined as:
(B & C) | (~B & D)
,B ^ C ^ D
,(B & C) | (B & D) | (C & D)
,B ^ C ^ D
for rounds 1–20, 21–40, 41–60, and 61–80, respectively.is the 32-bit sub-message block W[t]
. The first 16 entries correspond directly to the 512-bit input block. Subsequent entries (for t = 16 to 79) are computed as:
W[t] = (W[t-16] ^ W[t-14] ^ W[t-8] ^ W[t-3]) << 1
is a fixed constant (for ):
5A827999
,6ED9EBA1
,8F1BBCDC
,CA62C1D6
- The first 20 rounds use
, the next 20 use , and so on.
- The initial
A, B, C, D, E
values are added to the finalA', B', C', D', E'
values to form the new buffer. After processing all blocks, the resulting buffer is the SHA-1 hash.
Birthday Attack
If the size of the message space is
SM3
A domestic commercial cryptographic hash function.
Operates on 512-bit blocks and produces a 256-bit output.
Used in smart electricity meters and TPM 2.0.
Message Authentication
Classification of Message Authentication Code (MAC):
- Encryption Techniques
- Hash Functions
- HMAC Algorithm (Keyed One-Way Hash Function)
Digital Signature
RSA
The sender uses
The receiver uses
ElGamal
Initialization:
Signature Transformation:
- Select a random number
that is coprime with . - Signature:
, where is a one-way hash function. - Send
.
- Verification:
- Compute
. - Compute
and . If they are equal, the signature is valid.
- Compute
Note:
must not be leaked. The same applies to the encryption part.
DSA
A random
Signature transformation:
- Signing:
- Select
. . . - Send
.
- Select
- Verification:
. . . . If , the signature is valid.
ECDSA
Randomly select
- Signing:
- Choose a random number
- Send
- Choose a random number
- Verification:
; if , accept the signature.
Special Signatures
- Undeniable Signatures
- Blind Digital Signatures
- Group Signatures
Key Management Technologies
Diffie-Hellman (Asymmetric, only used for key exchange between two users)
System parameters:
- Alice selects a private
and computes - Bob selects a private
and computes - Both parties exchange
and - Alice computes
- Bob computes
Clearly, the two computed values are equal, and the key agreement is completed.
Vulnerable to man-in-the-middle attacks.
Shamir's Threshold Scheme
System parameters:
Secret:
A secret polynomial can be constructed as follows:
The key distributor calculates
Using Lagrange interpolation, the secret polynomial can only be reconstructed by any subset of
Specifically, when
Shortcomings:
- Fixed threshold value
- The secret distributor knows the participants' shadows
- Unable to prevent fraud by the secret distributor or participants
Identity Authentication Technology
Concepts, Threats, and Attack Methods
Challenge–Response Authentication:
- Additional communication overhead
- Prevents replay attacks by the claimant but not by the verifier: requires mutual authentication and timestamps.
S/Key One-Time Password Authentication:
- Prevents replay attacks
- Vulnerable to small number attacks (intercepting the server's seed and iteration value, modifying it to a smaller iteration value sent to the user, intercepting the user's password, and computing a larger iteration value)
- Lacks integrity protection mechanisms
Zero-Knowledge Proof Protocol
Let
- Bob randomly selects
, computes , and sends to Alice. - Alice computes
and sends to Bob. - Bob verifies whether
holds. - If the verification succeeds multiple times in repetition, it proves that Alice indeed knows the factors of
.
The theoretical foundation lies in the fact that the difficulty of computing
Kerberos Authentication
Uses a symmetric key system, with authentication services provided by a trusted third party.
Distributes shared keys to communicating parties through tickets.

Secure Communication


Pseudocode:
Sender:
# send.py
# Example usage:
with open("public_key_B.pem", "rb") as f:
public_key_B = RSA.import_key(f.read())
with open('data', 'rb') as f:
data = f.read()
# Party A encrypts the data and signs it
ciphertext = encrypt(data, key)
signature = sign(data, private_key_A)
# Party A encrypts the key using the public key of party B
encrypted_key = encrypt_key(key, public_key_B)
with open('encrypted_key', 'wb') as f:
f.write(encrypted_key)
with open('ciphertext', 'wb') as f:
f.write(ciphertext)
with open('signature', 'wb') as f:
f.write(signature)
with open('public_key_A.pem', 'wb') as f:
f.write(public_key_A.export_key('PEM'))
Receiver:
# receive.py
with open('public_key_A.pem', 'rb') as f:
public_key_A = RSA.import_key(f.read())
with open('encrypted_key', 'rb') as f:
encrypted_key = f.read()
with open('signature', 'rb') as f:
signature = f.read()
with open('ciphertext', 'rb') as f:
ciphertext = f.read()
# Party B decrypts the key and uses it to decrypt the data
key = decrypt_key(encrypted_key, private_key_B)
decrypted_data = decrypt(ciphertext, key)
with open('decrypted_data', 'wb') as f:
f.write(decrypted_data)
# Party B verifies the signature of party A
is_valid = verify_signature(decrypted_data, signature, public_key_A)
if is_valid:
print("The signature is valid")
else:
print("The signature is not valid")
Stream Cipher Fundamentals
Also known as stream ciphers, they belong to the symmetric cryptosystem and are suitable for hardware implementation.
Classification
- Synchronous Stream Ciphers: The state of the memory element is independent of the plaintext or ciphertext, with no error propagation but requiring synchronization.
- Self-Synchronizing Stream Ciphers: The keystream generation is related to the ciphertext, featuring limited error propagation and self-synchronization.
LFSR

Note that the shift direction is from high-order bits to low-order bits, where
The properties are entirely determined by the feedback function. The period
Stream cipher generators based on LFSR include:
- Geffe generator
- Clock-controlled generator
- Alternating step generator
RC4
Two algorithms: Key Scheduling Algorithm (KSA) and Pseudo-Random Generation Algorithm (PRGA).