现充|junyu33

(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

c=m+k

m=ck

Affine Cipher

k=(k1,k2)

c=k1m+k2

m=(ck2)k11(mod26)

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

ci=mi+ki

mi=ciki

Hill Cipher

C=KM

M=K1C(mod26)

where C and M are column vectors, and Kn is the encryption matrix.

Advantages and Disadvantages:

OTP (Vernam)

ci=miki

mi=ciki

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:

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

If S2=S, it is an idempotent cryptosystem, such as affine ciphers, permutation ciphers, etc.

Iterative cryptosystems must be non-idempotent.

Typical Structures

Li+1=Ri

Ri+1=LiF(Ri,Ki)

DES (Key Points)

Steps:

Advantages:

Proof of complement symmetry:

For the F function, F(k,R)=PS(kE(R))=PS(kE(R))=F(k,R)

Thus, the round function Qk(L,R)=(R,LF(k,R))=(R,LF(k,R)), and further Qk(L,R)=(R,LF(k,R))=Qk(L,R)

Let D be the swap of left and right blocks, and x=(L,R). Then the encryption function Ek(x)=DQk16Qk15...Qk1(x)=DQk16Qk15...Qk1(x)=DQk16Qk15...Qk1(x)=Ek(x)

Improvement: Triple DES.

Block Cipher Modes of Operation

How to Choose:

AES (Key Points)

Mathematical Foundations

Multiplication in the finite field GF(28): omitted.

x-multiplication: Since the modulus chosen for AES is 0x11b, i.e., x8+x4+x3+x+1, when the high bit of the multiplier is 0, it is equivalent to a left shift; otherwise, it is equivalent to a left shift followed by an XOR with 0x1b.

Cross multiplication: Refers to the multiplication of two degree-4 polynomials in GF(28) modulo x4+1. The process can be simplified using matrix multiplication. Specifically, for polynomials a3a2a1a0 and b3b2b1b0, the product d3d2d1d0 is given by:

[d0d1d2d3]=[a0a3a2a1a1a0a3a2a2a1a0a3a3a2a1a0][b0b1b2b3]

Here, the dot product between terms corresponds to multiplication in GF(28) (using x-multiplication), and addition corresponds to XOR.

Steps

Key length: 128 bits.

Overall process:

AddRoundKey()

for i from 1 to 9:
  SubBytes()
  ShiftRows()
  MixColumns()
  AddRoundKey()

SubBytes()
ShiftRows()
MixColumns()

Other Symmetric Encryption Algorithms

Asymmetric Encryption

Disadvantages of Symmetric Cryptography

Characteristics of Public Keys

Functions of a Public Key

RSA

Specific process: Omitted

Using the Chinese Remainder Theorem (CRT) to achieve fast computation in RSA

Example: Compute md(modn), where n=pq, p and q are distinct primes, and d is the private key.

Solution: Use Euler's theorem to compute md(modp) and md(modq) separately, then apply CRT to compute md(modn).

Miller-Rabin

Fermat's Little Theorem is a necessary condition for a modulus to be prime.

Quadratic Residue Theorem: If p is an odd prime, then the solutions to x21(modp) are only x1 or x1.

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: p,αZp.

Select a private key xA, and the public key is yA=αxA(modp).

Encryption:

Decryption:

Features

ECC

SM2 also employs the elliptic curve cryptography system.

Elliptic Curves over the Real Number Field

The equation y2=x3+ax+b can be denoted as E(a,b), or simply E.

If points P, Q, and R are collinear, the additive identity O is defined as O=P+Q+R. For any point P on the curve, P+O=P.

It follows that the additive inverse of a point has the same x-coordinate but opposite y-coordinate.

Thus, the addition operation is defined as follows: draw the line through P and Q, which intersects E at R; then R is the result of P+Q. The doubling operation can be defined analogously (omitted here). It can be shown that this addition satisfies the commutative and associative laws.

From an algebraic perspective, P+Q=(x3,y3)=(λ2x1x2,λ(x1x3)y1), where λ is the slope of the line. If P and Q coincide, then λ=3x2+a2y.

Elliptic Curves over Finite Fields

Focus on GF(p); GF(2n) is not included in the exam.

y2=x3+ax+b(modp) can be denoted as Ep(a,b), abbreviated as Ep.

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 p, and doubling is similar.

Example: Find the number of points in E11(1,6):
Answer: There are 13 points in total (don't forget the point at infinity O!).

ElGamal on Elliptic Curves

Let ord(P) be the smallest integer n such that nP=O.

ECDLP: Given α and β, finding k[0,ord(α)1] such that kα=β 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: E(a,b), base point G (with order n).

Key generation: Select a private key dA, and compute the public key PA=dAG.

Encryption:

Decryption:

Menezes-Vanstone

Primarily addresses the problem of mapping plaintext m to Pm.

System parameters: E(a,b), base point G (with order n).

Key generation: Select private key dA, public key is PA=dAG.

Encryption:

Decryption:

Example: Let base point G in E11(1,6) be (2,7), key d=7, plaintext be (9,1), random number k=6, compute the ciphertext.

Solution: Compute public key PA=dG=7(2,7)=(7,2)

c1=6G=(7,9)

Y=kPA=kdG=42G=3G=(8,3)

c2=8×9=6(modp)

c3=3×1=3(modp)

Therefore, the ciphertext is ((7,9),6,3)

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

Birthday Attack

If the size of the message space is N, then approximately N randomly selected messages are required to have a 50% probability of producing a collision.

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):

Digital Signature

RSA

The sender uses sA=md(modn) to sign.

The receiver uses m=sAe(modn) for verification.

ElGamal

Initialization: eA=αdA(modp)

Signature Transformation:

Note: k must not be leaked. The same applies to the encryption part.

DSA

p, q, and g are public, where q is a prime factor of p1, and g=h(p1)/q(modp).

A random x is selected as the private key, and the public key is y=gx(modp).

Signature transformation:

ECDSA

E(Fp),G,n are the system parameters.

Randomly select d(1,n) as the private key, and Q=dG as the public key.

Special Signatures

Key Management Technologies

Diffie-Hellman (Asymmetric, only used for key exchange between two users)

System parameters: p,α

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: k,n,q

Secret: s,a1,a2,,ak1

A secret polynomial can be constructed as follows:

f(x)=s+a1x+a2x2++ak1xk1

The key distributor calculates f(xi) for each participant based on their key xi and distributes the corresponding value to them.

Using Lagrange interpolation, the secret polynomial can only be reconstructed by any subset of k participants. The process is as follows:

f(x)=i=1kf(xi)j=1,jikxxjxixj(modq)

Specifically, when x=0, the secret s can be computed:

s=f(0)=(1)k1i=1kf(xi)j=1,jikxjxixj(modq)

Shortcomings:

Identity Authentication Technology

Concepts, Threats, and Attack Methods

Challenge–Response Authentication:

S/Key One-Time Password Authentication:

Zero-Knowledge Proof Protocol

Let n=p×q, and assume that Alice knows the factors of n. If Alice wants to convince Bob that she knows the factors without revealing them, she can perform the following steps:

The theoretical foundation lies in the fact that the difficulty of computing y(modn) is equivalent to factorizing n.

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

LFSR

Note that the shift direction is from high-order bits to low-order bits, where x1 is the output, and the value of f becomes the next xn.

The properties are entirely determined by the feedback function. The period T of an n-stage LFSR satisfies T2n1.

Stream cipher generators based on LFSR include:

RC4

Two algorithms: Key Scheduling Algorithm (KSA) and Pseudo-Random Generation Algorithm (PRGA).