Give a description of the topic, and what you hope the reader will get from this. For example, this page will cover addition of the natural numbers. Talk about how this relates to something in cryptography, either through a protocol, or an attack. This can be a single sentence, or verbose.
Laws of Addition
For all integers, the addition operation is
Associative:
Commutative:
Distributive:
Interesting Identity
Sage Example
Further Resources
Links to
Other interesting
Resources
Contains an identity element: a+0=0+a=a
Has an inverse for every element: a+(−a)=(−a)+a=0
Closed: ∀a,b∈Z,a+b∈Z
a+(b+c)=(a+b)+c
a+b=b+a
a(b+c)=ab+ac
(1+2+3+…+n)2=13+23+33+…+n3
sage: 1 + (2 + 3) == (1 + 2) + 3
True
sage: 1 + 2 == 2 + 1
True
sage: 5*(7 + 11) == 5*7 + 5*11
True
sage: sum(i for i in range(1000))^2 == sum(i^3 for i in range(1000))
True
Mathematical Notation
Introduction
Throughout CryptoBook, discussions are made more concise by using various mathematical symbols. For some of you, all of these will feel familiar, while for others, it will feel new and confusing. This chapter is devoted to helping new readers gain insight into the notation used.
If you're reading a page and something is new to you, come here and add the symbol, someone else who understands it can explain its meaning
Mathematical Objects
Special Sets
: denotes the set of complex numbers
: denotes the set of real numbers
: denotes the set of integers
We refer to unit groups by or . Example:
We refer to finite fields with elements by
We refer to a general field by
Relation operators
means is an element of (belongs to)
Logical Notation
means for all
means there exists. means uniquely exists
Operators
means the probability of an event to happen. Sometimes denoted as or as
CryptoBook
About this project
CryptoBook is a community project, developed by members of to create a resource for people to learn cryptography. The focus of this project is to create a friendly resource for the mathematical fundamentals of cryptography, along with corresponding implementation.
Think of this as an alternative SageMath documentation source, where the focus is its application in solving cryptographic problems.
If you're interested in contributing, come chat to us in our
N: denotes the set of natural numbers (non-negative integers)
Z/nZ: denotes the set of integers mod n
We refer to the algebraic closure of this field by kˉ
C
R
Z
R×
R∗
(Z/nZ)×
q
Fq
k
∈
∀
∃
∃!
Pr(A)
A
Pr[A]
P(A)
"""
We can call each of these sets with Sage using the
following commands. Comments are the result of the
input.
"""
CC
# Complex Field with 53 bits of precision
RR
# Real Field with 53 bits of precision
ZZ
# Integer Ring
QQ
# Rational Field
NN
# Non negative integer semiring
Zmod(11) # or `Integers(11)` or `IntegerModRing(11)`
# Ring of integers modulo 11
"""
Example of defining a field and then its
algebraic closure
"""
GF(3)
# Finite Field of size 3 , where GF stands for Galois Field
GF(3).algebraic_closure()
# Algebraic closure of Finite Field of size 3
"""
If you want to find which field an element belongs to you can use the
`.parent()` function
"""
x = 7
print(x.parent())
# Integer Ring
y = 3.5
print(y.parent())
# Real Field with 53 bits of precision
"""
If you want to "lift" an element from a quotient ring R/I to the ring R
use the `.lift()` function
"""
R = ZZ
RI = Zmod(11)
x = RI(5)
print(x.parent())
# Ring of integers modulo 11
y = x.lift()
print(y.parent())
# Integer Ring
print(y in R)
# True
Contributors
Optional space to say that you've worked on the book
Thank you!
🥳 CryptoBook is the result of the hard work of the CryptoHack community. Thanks to all of our writers, whether it's been line edits or whole section creation. This only exists because of the generosity and passion of a group of cryptographers.
Our Writers
...
You?
Join CryptoBook
If you would like to join the team, come over to our and talk with us about your ideas
The aim of CryptoBook is to have a consolidated space for all of the mathematics required to properly learn and enjoy cryptography. The focus of any topic should be to introduce a reader to a subject in a way that is fun, engaging and with an attempt to frame it as an applied resource.
The second focus should be to cleanly implement the various topics using SageMath, so that there is a clear resource for a new reader to gain insight on how SageMath might be used to create the objects needed.
Write about what you love and this book will be a success.
Descriptions of attacks against cryptosystems are strongly encouraged, however full SageMath implementations should not be included, as this has the potential for destroying CryptoHack challenges, or making all attacks known by so many people that CTFs become a total nightmare!!
Proposed topics
This list is not complete so please add to it as you see fit.
Mathematical Background
Fundamentals
Congruences
GCD, LCM
Bézout's Theorem
Number Theory
Mainly thinking things like
Prime decomposition and distribution
Primality testing
Euler's theorem
Abstract Algebra
Mainly thinking things like:
Groups, Rings, Fields, etc.
Abelian groups and their relationship to key-exchange
Lagrange's theorem and small subgroup attacks
Basilar Cryptanalysis forms
Introduction to Cryptanalysis
A linear Approach to Cryptanalysis
Matsui's Best biases algorithm
Elliptic Curves
Weierstrass
Montgomery
Edwards
Generating Elliptic Curves
Generating curves of prime order
Generating supersingular curves
Hyperelliptic curves
Generalization of elliptic curves
Recovering a group structure using the Jacobian
Example: genus one curves, jacobian is isomorphic to the set of points
Security background
Basic Concepts
Confidentiality, Integrity etc
Encryption, Key generation
Asymmetric Cryptography
RSA
Textbook protocol
Padding
Bleichenbacher's Attack
Paillier Cryptosystem
Textbook protocol
ElGamal Encryption System
Textbook protocol
ElGamal Digital Signature Scheme
Diffie-Hellman
Textbook protocol
Strong primes, and why
Elliptic Curve Cryptography
ECDSA
EdDSA
Symmetric Cryptography
One Time Pad
XOR and its properties
XOR as One Time Pad
Generalized One Time Pad
Block Ciphers
AES
Stream Ciphers
Affine
RC4
Hashes
Introduction
Trapdoor Functions
MD family
Isogeny Based Cryptography
Isogenies
Isogeny graphs
Torsion poins
Cryptographic Protocols
Zero-knowledge proofs
Schnorr proof of knowledge for dlog
Core definitions
Proof of equality of dlog
Formal Verification of Security Protocols
Definition of Formal Verification
Uses of Formal Verification
Handshake protocols, flawed protocols
Usefull Resources ( Books, articles ..) // based on my material
Cryptanalytic Attacks on RSA (Yan, Springer, 2008)
If something doesn't make sense, make a comment using GitBook, or ask in the Discord.
If you are confident that something is wrong, just fix it. There's no need to ask.
If you think something doesn't have enough detail, expand on it, or leave a comment suggesting that.
If a page is getting too long, break it down into new pages. If you're unsure, then leave a comment or talk in the discord
If you want to write about something new and learn as you type, this is fine! But please leave a warning at the top that this is new to you and needs another pair of eyes.
If there's big subject you're working on, claim the page and save it, show us that that's what you're doing so we don't overlap too much
General Tips
Introduce new objects slowly, if many things need to be assumed, then try to plan for them to appear within the somewhere.
It is better to cover less, and explain something well, than it is to quickly cover a lot. We're not racing
When explaining anything, imagine you are introducing it for a first time. Summaries exist elsewhere online, the goal of CryptoBook is education
If anything on any page is unclear, then please leave a comment, or talk in the discord. We are all at different levels, and I want this to be useful for everyone. Let's work on this as a big team and create something beautiful.
Try and use the hints / tips blocks to break up dense text, for example:
To use , you can wrap your text in $$maths here$$. If this is at the beginning of a paragraph, it makes it block, otherwise it is inline
Page Structure
A page should have a clear educational goal: this should be explained in the introduction. References to prerequisites should be kept within the book and if the book doesnt have this yet, it should be placed into .
The topic should be presented initially with theory, showing the mathematics and structures we will need. A discussion should be pointed towards how this appears within Cryptography
Motivating a new reader is the biggest challenge of creating a resource. People will be coming here to understand cryptography and SageMath, so keep pointing back to the goal!
Within a discussion of a topic, a small snippet of code to give an example is encouraged
If you write code better than you write maths, then just include what you can and the page will form around that
An example page is given in
Formatting
Mathematics notation
There's no "right or wrong" but it's good to be consistent, I think?
All maths must be presented using using either both block and inline
We seem to be using mathbb for our fields / rings. So let's stick with that? Maybe someone has a good resource for notation we can work from?
Code Blocks
Make sure all code blocks have the right language selected for syntax highlighting
Preference is to SageMath, then to Python, then others.
Code should be cope-pastable. So if you include print statement, include the result of the output as a comment
Algorithms
Algorithms should be presented as??
Division and Greatest common divisor
Author: Zademn
Introduction
Two of the skills a cryptographer must master are:
Knowing his way and being comfortable to work with numbers.
Understanding and manipulating abstract objects.
This chapter of fundamentals proposes to prepare you for understanding the basics of number theory and abstract algebra .We will start with the most basic concepts such as division and build up knowledge until you, future cryptographer, are able to follow and understand the proofs and intricacies of the cryptosystems that make our everyday life secure.
We will provide examples and snippets of code and be sure to play with them. If math is not your strongest suit, we highly suggest to pause and ponder for each concept and take it slow.
For the math-savy people we cover advanced topics in specific chapters on the subjects of number theory and group theory.
So what are we waiting for? Let's jump right in!
Division
Let be the set denoting the integers.
Definition - Divisibility
For we say that divides if there is some such that
Notation:
Example
For we have because we can find such that .
Properties
and implies
Example: Let and
Definition - Division with remainder
Let with ,
There exists unique such that and
is called the quotient and the remainder
Examples:
To find python offers us the divmod() function that takes as arguments
If we want to find only the quotient we can use the // operator
If we want to find the remainder we can use the modulo % operator
Exercises:
Now it's your turn! Play with the proprieties of the division in Python and see if they hold.
Greatest common divisor
Definition
Let be 2 integers. The greatest common divisor is the largest integer such that and
Notation:
Examples:
Remark:
for all other common divisors of we have
Things to think about
What can we say about numbers with ? How are their divisors?
Fermat's Little Theorem in Detail
Would you like to be an author?
Introduction
Since we can add, subtract, multiply, divide even... what would be missing? Powering! I'm not talking about some power fantasy here, but rather introduce some really really important theorems. Fermat little's theorem proves useful in a great deal of situation, and is along with Euler's theorem a piece of arithmetic you need to know. Arguably the most canonical example of using these is the RSA cryptosystem, whose decryption step is built around Euler's theorem.
Fermat's Little Theorem
Since we want to talk about powers, let's look at powers. And because I like 7, I made a table of all the powers of all the integers modulo 7.
On the last row, there is a clear pattern emerging, what's going on??? Hm, let's try again modulo 5 this time.
Huh, again?! Clearly, there is something going on... Sage confirms this!
Claim (Fermat's Little Theorem): Leta prime.
When, this is equivalent to what we observed:. There are several proofs of Fermat's Little Theorem, but perhaps the fastest is to see it as a consequence of the Euler's Theorem which generalizes it. Still, let's look a bit at some applications of this before moving on.
A first funny thing is the following:. When, this means we have found a non-trivial integer that when multiplied toyields 1. That is, we have found the inverse of, wow. Since the inverse is unique modulo, we can always invert non-zero integers by doing this. From a human point of view, this is really easier than using the extended euclidean algorithm.
demo application for that one RSA related message attack?
Resultant
eliminate multivariate polynomials at the expense of increasing polynomial degree
demo application for that one RSA Coppersmith short padding related message attack?
Groebner Basis
what if you did GCD and Resultants at the same time, like whoa
and what if it took forever to run!
Quadratic Residues
Pollard rho
Sieves
Contribute as much or as little as you want, but try to only work on topics that
You are interested in
You have some experience of thinking about
External resources should be included at the end of the page. Ideally the book should be self-contained (within reason) but other resources are great as they offer other ways to learn
3∣6 and 3∣9⇒3∣(6⋅5+9⋅2)⟺3∣48 . We can find k=16such that 48=3⋅16
a∣b and b∣c implies a∣c
if a∣band b∣a then a=±b
Z={…,−1,0,1,2,3…}
a,b,∈Z
a
b
k∈Z
a⋅k=b
a∣b
a=2,b=6
2∣6
k=3
6=2⋅3
a∣a,1∣a and a∣0
a∣b
a∣c
a∣(bu+cv)∀u,v,∈Z
b=6,u=5
c=9,v=2
a,b∈Z
b≥1
q,r∈Z
a=bq+r
0≤r<b
q
r
q,r
a,b
q
r
a,b∈Z
d∈Z
d∣a
d∣b
gcd(a,b)=d
c
a,b
c∣d
a,b
gcd(a,b)=1
6
2
0
1
4
2
2
4
1
3
0
1
1
6
1
6
6
4
0
1
2
4
4
2
1
5
0
1
4
5
2
3
6
6
0
1
1
1
1
1
1
4
4
1
3
0
1
3
2
4
4
0
1
1
1
1
Power
0
1
2
3
4
5
6
1
0
1
2
3
4
Power
0
1
2
3
4
1
0
1
2
3
4
2
0
p
∀a∈Z,ap≡a[p]
a=0
ap−1≡1[n]
∀a∈Z,a⋅ap−2≡ap−1≡1[p]
p>2
a
a
p
5
1
# Example
a = 3
b = 6
print(a+b)
# 9
// todo
q, r = divmod(6, 2)
print(q, r)
# 3 0
q, r = divmod(13, 5)
print(q, r)
# 2 3
# Note that 13 = 2 * 5 + 3
q = 13 // 5
print(q)
# 2
r = 13 % 5
print(r)
# 3
# In python we can import math to get the GCD algo
import math
print(math.gcd(18, 12)) # -> 6
# Sage has it already!
print(gcd(18, 12)) # -> 6
p, itworks = 1, True
for _ in range(100):
p = next_prime(p)
Fp = GF(p) # Finite Field of size p
itworks &= all(Fp(x)^(p-1) == 1 for x in range(1,p))
print(itworks)
# True
Euclidean Algorithm
Introduction
Although we have functions that can compute our gcdeasily it's important enough that we need to give and study an algorithm for it: the euclidean algorithm.
It's extended version will help us calculate modular inverses which we will define a bit later.
Euclidean Algorithm
Important Remark
If and then . Therefore
Algorithm
We write the following:
Or iteratively until we find a . Then we stop
Now here's the trick:
If then divides
Pause and ponder. Make you you understand why that works.
Example:
Calculate
Code
Exercises:
Pick 2 numbers and calculate their by hand.
Implement the algorithm in Python / Sage and play with it. Do not copy paste the code
Extended Euclidean Algorithm
This section needs to be expanded a bit.
Bezout's identity
Let . Then there exists such that
The extended euclidean algorithm aims to find given
Theorems of Wilson, Euler, and Fermat
Wilson's Theorem
A positive integer n>1is a prime if and only if:
(n−1)!≡−1modn
Euler's Theorem
Let and s.t. , then:
Fermat's Little Theorem
Let be a prime and , then:
or equivalently:
Reference
Continued Fractions
Continued Fractions
Continued fractions are a way of representing a number as a sum of an integer and a fraction.
Mathematically, a continued fraction is a representation
a0+a1+a2+⋱b2b1b0
ai,biare complex numbers. The continued fraction with bi=1∀i is called a simple continued fraction and continued fractions with finite number of ai are called finite continued fractions.
Consider example rational numbers,
the continued fractions could be written as
Notation
A simple continued fraction is represented as a list of coefficients() i.e
for the above example
Computation of simple continued fractions
Given a number , the coefficients() in its continued fraction representation can be calculated recursively using
The above notation might not be obvious. Observing the structure of continued fraction with few coefficients will make them more evident:
SageMath provides functions continued_fraction and continued_fraction_list to work with continued fractions. Below is presented a simple implementation of continued_fractions.
Convergents of continued fraction
The convergent of a continued fractionis the numerical value or approximation calculated using the firstcoefficients of the continued fraction. The firstconvergents are
One of the immediate applications of the convergents is that they give rational approximations given the continued fraction of a number. This allows finding rational approximations to irrational numbers.
Convergents of continued fractions can be calculated in sage
Continued fractions have many other applications. One such applicable in cryptology is based on Legendre's theorem in diophantine approximations.
Theorem: if, thenis a convergent of.
Wiener's attack on the RSA cryptosystem works by proving that under certain conditions, an equation of the formcould be derived whereis entirely made up of public information andis made up of private information. Under assumed conditions, the inequalityis statisfied, and the value(private information) is calculated from convergents of(public information), consequently breaking the RSA cryptosystem.
Modular Arithmetic
Authors: A~Z, perhaps someone else but not yet (or they've decided to remain hidden like a ninja)
Introduction
Thinking not over the integers as a whole but modulo some integerninstead can prove quite useful in a number of situation. This chapter attempts to introduce to you the basic concepts of working in such a context.
Congruences
For the following chapter, we will assumeis a natural integer, andandare two integers. We say thatandare congruent modulowhen, or equivalently when there is an integersuch that. We denote this byor . I will use the first notation throughout this chapter.
Remark: When, we have, whereis the remainder in the euclidean division ofby
This relation has a number of useful properties:
Seeing as addition and multiplication are well defined, the integers moduloform a ring, which we note. In sage, you can construct such ring with either of the following
Powering modulois relatively fast, thanks to the algorithm, so we needn't worry about it taking too much time when working with high powers
As a side note, remember that if an equality holds over the integers, then it holds modulo any natural integer. This can be used to prove that a relation is never true by finding a suitable modulus, or to derive conditions on the potential solutions of the equation.
Example: by choosing an appropriate modulus, show that not even god is able to find integersandsuch that
Modular Inverse
Since we can multiply, a question arises: can we divide? The answer is yes, under certain conditions. Dividing by an integeris the same as multiplying by its inverse; that is we want to find another integersuch that. Since, it is clear from that such an inverse exists if and only if. Therefore, the units moduloare the integers coprime to, lying in a set we call the unit group modulo:
Finding the modular inverse of a number is an easy task, thanks to the (that outputs solutions inandto the equationfrom above).
Integer Factorization
Overview
Given a composite integer , can it be decomposed as a product of smaller integers (hopefully as a unique product of prime factors)?
As easy as it may sound, integer factorization in polynomial time on a classical computer stands one of the unsolved problems in computation for centuries!
Lets start dumb, all we need to do is check all the numbers such that or programmatically n%p==0
Ideals
Example: Ideals of the integers
Definition - Ideal of
is an ideal we have
a+b∈I and az∈I
Example: aZ={az:z∈Z}→2Z,3Z,4Z,… - multiples of a
Remarks:
∀a,b∈Zwe have b∈aZ⟺a∣b
I1+I2={a1+a2:a1∈I1,a2∈I2} is an ideal
Example: Consider 18Z+12Z. This ideal contains 6=18⋅1+12⋅(−1)⇒18Z+12Z=6Z
Seems like its an O(n)algorithm! whats all the deal about?
By polynomial time, we mean polynomial time in bwhen nis a b-bit number, so what we looking at is actually a O(2b)which is actually exponential (which everyone hates)
Now taking a better look at it, one would realize that a factor of ncan't be bigger than n
Other observation would be, if we already checked a number (say 2) to not be a divisor, we dont need to check any multiple of that number since it would not be a factor.
n
1<p<n
p∣n
def my_gcd(a, b):
# If a < b swap them
if a < b:
a, b = b, a
# If we encounter 0 return a
if b == 0:
return a
else:
r = a % b
return my_gcd(b, r)
print(my_gcd(24, 15))
# 3
# In sage we have the `xgcd` function
a = 24
b = 15
g, u, v = xgcd(a, b)
print(g, u, v)
# 3 2 -3
print(u * a + v * b)
# 3 -> because 24 * 2 - 15 * 3 = 48 - 45 = 3
def continued_fraction_list(xi):
ai = floor(xi)
if xi == ai: # last coefficient
return [ai]
return [ai] + continued_fraction_list(1/(x - ai))
pow(2, 564654533, 7) # Output result as member of Z/7Z
# 4
power_mod(987654321, 987654321, 7) # Output result as simple integer
# 6
Zmod(7)(84564685)^(2^100) # ^ stands for powering in sage. To get XOR, use ^^.
# 5
Zn = Zmod(10)
Zn(7).is_unit()
# True
Zn(8).is_unit()
# False
3 == 1/Zn(7) == Zn(7)^(-1) == pow(7,-1,10) # member of Z/10Z
# True
inverse_mod(7, 10) # simple integer
# 3
Zn(3)/7
# 9
Zn(3)/8
# ZeroDivisionError: inverse of Mod(8, 10) does not exist
Zn.unit_group()
# Multiplicative Abelian group isomorphic to C4 (C4 being the cyclic group of order 4)
xgcd(7, 10) # find (gcd(a, b), u, v) in au + bv = gcd(a, b)
# (1, 3, -2) <-- (gcd(7, 10), d, -k)
def factors(n):
divisors = []
for p in range(1,n):
if n%p==0:
divisors.append(p)
return divisors
Groups
Authors: Ariana, Zademn
Reviewed by:
Introduction
Modern cryptography is based on the assumption that some problems are hard (unfeasable to solve). Since the we do not have infinite computational power and storage we usually work with finite messages, keys and ciphertexts and we say they lay in some finite setsM,K and C.
Furthermore, to get a ciphertext we usually perform some operations with the message and the key.
For example in AES128 since the input, output and key spaces are 128 bits. We also have the encryption and decryption operations:
The study of sets, and different types of operations on them is the target of abstract algebra.
In this chapter we will learn the underlying building blocks of cryptosystems and some of the hard problems that the cryptosystems are based on.
Definition
A setpaired with a binary operation is a group if the following requirements hold:
Closure: For all - Applying the operation keeps the element in the set
Associativity: For all
Identity: There exists an elementsuch that
For , means when and when . For , .
If , then is commutative and the group is called abelian. We often denote the group operation by instead of and we typically use instead of .
Remark
The identity element of a group is also denoted with or just if only one groups is present
Examples of groups
Integers modulo (remainders) under modular addition .
Let's look if the group axioms are satisfied
.
Because of the modulo reduction
Modular addition is associative
is the identity element
Therefore we can conclude that the integers mod with the modular addition form a group.
Example of non-groups
is not a group because we can find the element that doesn't have an inverse for the identity .
is not a group because we can find elements that don't have an inverse for the identity
Exercise
Is a group? If yes why? If not, are there values for that make it a group?
sɹosᴉʌᴉp uoɯɯoɔ puɐ sǝɯᴉɹd ʇnoqɐ ʞuᴉɥ┴ :ʇuᴉH
Proprieties
The identity of a group is unique
The inverse of every element is unique
. The inverse of the inverse of the element is the element itself
Orders
In abstract algebra we have two notions of order: Group order and element order
Group order
The order of a group is the number of the elements in that group. Notation:
Element order
The order of an element is the smallest integer such that . If such a number doesn't exist we say the element has order . Notation:
We said our messages lay in some group . The order of this group is the number of possible messages that we can have. For we have possible messages.
Let be some message. The order of means how many different messages we can generate by applying the group operation on
Subgroups
Definition
Let be a group. We say is a subgroup of if is a subset of and forms a group.
Notation:
Proprieties
The identity of is also in
The inverses of the elements in are found in
How to check ? Let's look at a 2 step test
Closed under operation:
Closed under inverses:
Generators
Let be a group,an element and . Consider the following set:
This set paired the group operation form a subgroup of generated by an element .
Why do we care about subgroups? We praise the fact that some problems are hard because the numbers we use are huge and exhaustive space searches are too hard in practice.
Suppose we have a big secret values space and we use an element to generate them.
If an elementwith a small order is used then it can generate only possible values and if
Example
For now, trust us that if given a prime , a value and we compute for a secret , finding is a hard problem. We will tell you why a bit later.
Examples
// subgroups, quotient groups
// cyclic groups
Fields
A setFwith two binary operations +,⋅:F×F→Fis a field if the following holds:
R,+is a commutative group with identity 0
R−{0},⋅is a commutative group with identity1.
Distributivity:
// field extensions, algebraic elements
Introduction
Lattices, also known as Minkowski's theory after Hermann Minkowski, or the geometry of numbers (deprecated!) allows the usage of geometrical tools (i.e. volumes) in number theory.
The intuitive notion of a lattice (perhaps surprisingly) matches its mathematical definition. For example, lattices are formed by
points on an infinite checkerboard;
centers of a hexagonal tessellation;
integers on the real number line.
The last example should hint at how we generalize this concept to arbitrary dimensions. In general, lattices consist of discrete points which appear at "regular intervals."
Definitions
A lattice is a subgroup of generated by , i.e.
where are linearly independent vectors. Collectively, form a basis of.
We say a set of vectors are linearly independent if the only solution to the equation is when all are zero.
Taking a step back, this definition should resemble that of a vector space, with one exception: scalars are integers! The discrete nature of lattices comes from this restriction.
Some more terminology from linear algebra will be useful. The dimension of a lattice, denoted, is . A lattice is complete if . Note that we can always choose a subspace of such that the lattice is complete, namely the subspace generated by .
The region
is known as the fundamental mesh.
In the image above, we see the points of a lattice in . The red vectors are one set of basis vectors and the shaded region is the corresponding fundamental mesh. The green vectors also form another set of basis vectors with its corresponding fundamental mesh. We see here that the basis vectors and fundamental mesh is not unique to a lattice.
Although the fundamental mesh is not unique, it turns out that the (dimensional) volume of the fundamental mesh is constant for any given lattice. Hence we can define the volume of a lattice as the volume of a fundamental mesh. However this definition can be hard to handle hence we provide an equivalent definition via determinants:
Letbe amatrix whose rows are given by the basis vectors. Then the volume of a fundamental mesh is given by
A subset of is known as centrally symmetric if implies . It is convex if for any , the line joining is contained in , i.e. . Finally we can introduce the most important theorem about lattices, the Minkowski's Lattice Point Theorem:
Let be a complete lattice of dimension and be a centrally symmetric convex set. Suppose
Then contains at least one nonzero point of . This result is primarily used to prove the existence of lattice vectors.
Throughout this section, denotes the norm and denotes the inner product.
Proof sketch of Minkowski's theorem
This proof is by some sort of a pigeonhole argument on volumes. Consider the set
We have , hence the inclusion cannot be injective, thus we can find some , . Hence is a nontrivial lattice point.
Exercises
1) Let be the lattice generated by (take the rows as basis vectors).
Compute the volume of this lattice
Show that generates the same lattice
Show that each row in is in the lattice butdoes not generate the lattice. This is one key difference from the case of linear algebra (over fields).
2) Letbe matrices whose row vectors are basis for lattices . Both lattices are the same iff there exists some such that . Find for problem 1. Note that is the group of invertible matrices with integer coefficients, meaning and have integer coefficients.
3) Show that the condition in Minkowski's lattice point theorem is strict, i.e. for any complete latticeof dimension , we can find some centrally symmetric convex setwithbut the only lattice point inis the origin.
4*) Letbe the shortest nonzero vector for some lattice with dimension. Show that
Rings
A setwith two binary operations is a ring if the following holds:
is a commutative group with identity
is a monoid (group without the inverse axiom) with identity.
LLL reduction
Introduction
In this section, we hope to bring some intuitive understanding to the LLL algorithm and how it works. The LLL algorithm is a lattice reduction algorithm, meaning it takes in a basis for some lattice and hopefully returns another basis for the same lattice with shorter basis vectors. Before introducing LLL reduction, we'll introduce 2 key algorithms that LLL is built from, Gram-Schmidt orthogonalization and Gaussian Reduction. We give a brief overview on why these are used to build LLL.
As the volume of a lattice is fixed, and is given by the determinant of the basis vectors, whenever our basis vectors gets shorter, they must, in some intuitive sense, become more orthogonal to each other in order for the determinant to remain the same. Hence, Gram-Schmidt orthogonalization is used as an approximation to the shortest basis vector. However, the vectors that we get are in general not in the lattice, hence we only use this as a rough idea of what the shortest vectors would be like.
Lagrange's algorithm can be thought as the GCD algorithm for 2 numbers generalized to lattices. This iteratively reduces the length of each vector by subtracting some amount of one from another until we can't do it anymore. Such an algorithm actually gives the shortest possible vectors in 2 dimensions! Unfortunately, this algorithm may not terminate for higher dimensions, even in 3 dimensions. Hence, it needs to be modified a bit to allow the algorithm to halt.
a(b+c)=ab+ac,(a+b)c=ac+bc
Distributivity: a(b+c)=ab+ac,(a+b)c=ac+bc
// ideals, diff types of domains
R
+,⋅:R×R→R
R,+
0
R,⋅
1
for all
Inverse: For all elements a∈G, there exists some b∈Gsuch that b⋅a=a⋅b=e. We usually denotebas a−1
✓∀a∈Z/nZwe take n−amodnto be the inverse of a. We check that
a+n−a≡n≡0modn
n−a+a≡n≡0modn
∀a,b∈G:(ab)−1=b−1a−1
Proof: (ab)(b−1a−1)=a(bb−1)a−1=aa−1=e.
is small enough an attacker can do a brute force attack.
K=M=C={0,1}128
Enc:K×M→CDec:K×C→M
G
⋅:G×G→G
a,b∈G:
a⋅b∈G
a,b,c∈G:
(a⋅b)⋅c=a⋅(b⋅c)
e∈G
a⋅e=e⋅a=a
n∈Z
an
n timesa⋅a…⋅a
n>0
(a−n)−1
n<0
n=0
an=e
ab=ba
⋅
+
⋅
na
an
G
1G
1
n
=(Z/nZ,+)
Z/nZ={0,1,...,n−1}
✓
∀a,b∈Z/nZ let c≡a+bmodn
c<n⇒c∈Z/nZ
✓
✓
0+a≡a+0≡amodn⇒0
n
(Q,⋅)
0
1
(Z,⋅)
1
(Z/nZ∖{0},⋅)
n
∀
a∈G:(a−1)−1=g
G
∣G∣
a∈G
n
an=1G
n
∞
∣a∣
M
∣M∣
M={0,1}128
∣M∣=2128
m∈M
m
m
(G,⋅)
H
G
H
G
(H,⋅)
H≤G
G
H:
1H=1G
H
H
H≤G
∀a,b∈H→ab∈H
∀a∈H→a−1∈H
G
g∈G
∣g∣=n
{1,g,g2,...,gn−1}=denoted⟨g⟩.
G
g
G
g
g∈G
n
n
n
p
g∈Z/pZ
y=gxmodp
x
x
a∈G
L
Rn
bi
L=i=1∑dZbi={i=1∑daibiai∈Z}
bi
{bi}i=1d
L
vi
∑iaibi=0
ai
dimL
d
d=n
Rn
bi
Φ={i=1∑dxibi0≤xi<1}
R2
m
B
d×n
vol(L)=∣det(BBT)∣
X
Rn
x∈X
−x∈X
x,y∈X
x,y
X
{tx+(1−t)y∣0≤t≤1}⊂X
L
n
X
vol(X)>2nvol(L)
X
L
∥v∥=∑ivi2
ℓ2
⟨a,b⟩=∑iaibi
21X={21x∣x∈X}
vol(21X)>vol(L)
21X→Rn/L
x1=x2+ℓ
x1,x2∈21X,ℓ∈L,x1=x2
x1−x2∈L
L
B=(−119−88−7)
B′=(100111)
C=(100212)
C
B,B′
d×n
L,L′
U∈GLd(Z)
B′=UB
U
GLd(Z)
U
U−1
L
n
X
vol(X)=2nvol(L)
X
v
L
n
∥v∥≤π2Γ(2n+1)n1vol(L)n1
Lagrange's algorithm
Overview
Lagrange's algorithm, often incorrectly called Gaussian reduction, is the 2D analouge to the Euclidean algorithm and is used for lattice reduction. Intuitively, lattice reduction is the idea of finding a new basis that consists of shorter vectors. Before going into Lagrange's algorithm, we first recap the Euclidean algorithm:
The algorithm primarily consists of two steps, a reduction step where the size of mis brought down by a multiple of nand a swapping step that ensures mis always the largest number. We can adapt this idea for lattices:
Here is actually the Gram-Schmidt coefficient and it turns out that this algorithm will always find the shortest possible basis! Using the basis
the Lagrange reduction looks like
and here we see it clearly gives the shortest vectors.
Optimality proof
Let be a lattice. The basis is defined to be the shortest for any other basis , we have and . Note that this generally cannot be generalized to other dimensions, however in dimension 2, this is possible and is given by Lagrange's algorithm. The proof is a somewhat messy sequence of inequalities that eventually lead to the conclusion we want.
Let be the output of the Lagrange reduction for some lattice . To prove that Lagrange reduction gives the shortest basis, we first show that is the shortest vector in .
We know that from the algorithm directly. Let be any element in . We first show that :
Since , this quantity is only when and is a positive integer for all other cases, hence and is a shortest vector of . Note that we can have multiple vectors with the same norm as , for instance . So this is not a unique shortest vector.
Suppose there exists some basis for such that . We show that . Let .
If , then as must form a basis. This means that and by the inequality above, we must have or . The first case tells us that . By squaring the second case, we get
but since is the shortest vector, .
Otherwise, we have and , so
Hence proving Lagrange's algorithm indeed gives us the shortest basis vectors.
Exercises
1) Show that the output of Lagrange's algorithm generate the same lattice as the input.
2) Find a case where . Notice that the vectors here is the equality case for the bound given in Exercise 4 of the introduction, this actually tells us that the optimal lattice circle packing in 2D is given by this precise lattice! It turns out that this is actually the optimal circle packing in 2D but the proof is significantly more involved. (See for the details)
3*) Let , show that
and show that for all steps in the algorithm except the first and last, hence decreases by at least at each loop and the algorithm runs in polynomial time.
Discrete Log Problem
Discrete log problem
Given any groupGand elementsa,bsuch that an=b, the problem of solving fornis known as the disctete log problem (DLP). In sage, this can be done for general groups by calling discrete_log
Discrete log over
Typically, one considers the discrete log problem in , i.e. the multiplicative group of integers. Explicitly, the problem asks forgiven . This can be done by calling b.log(a) in sage:
This section is devoted to helping the reader understand which functions are called when for this specific instance of DLP.
Whenis composite and not a prime power, discrete_log() will be used, which uses generic algorithms to solve DLP (e.g. Pohlig-Hellman and baby-step giant-step).
When is a prime, Pari znlog will be used, which uses a linear sieve index calculus method, suitable for .
When , SageMath will fall back on the generic implementation discrete_log()which can be slow. However, Pari znlog can handle this as well, again using the linear sieve index calculus method. To call this within SageMath we can use either of the following (the first option being a tiny bit faster than the second)
Example
Given a small prime, we can compare the Pari method with the Sage defaults
We can also solve this problem with even larger primes in a very short time
Discrete log over
// elliptic curve discrete log functions
Lattice reduction
Overview
Having introduced the LLL reduction, we now provide a more general notions of a reduced basis for a lattice as well as provide bounds for the basis vectors. The key idea behind introducing these definitions is that once we know some basis vector is []-reduced, we can bound the sizes of the basis, which is important when algorithms require short vectors in a lattice. For fast algorithms, LLL-reduction is typically the most important notion as it can be computed quickly. Two main definitions appear often when discussing lattice reductions, which we will provide here.
HKZ reduced
Definition
Let as the projection to the orthogonal complement of .Then the basis is HKZ-reduced if it is size-reduced and . This definition gives us a relatively simple way to compute a HKZ-reduced basis by iteratively finding the shortest vector in orthogonal projections.
Minkowski reduced
Definition
The basis is Minkowski-reduced if has minimum length among all vectors in linearly independent from. Equivalently, has minimum length among all vectors such that can be extended to form a basis of. Such a notion is strongest among all lattice reduction notions and is generally extremely hard to compute. Another equivalent definition is
LLL reduction
Overview
There are a few issues that one may encounter when attempting to generalize Lagrange's algorithm to higher dimensions. Most importantly, one needs to figure what is the proper way to swap the vectors around and when to terminate, ideally in in polynomial time. A rough sketch of how the algorithm should look like is
There are two things we need to figure out, in what order should we reduce the basis elements by and how should we know when to swap. Ideally, we also want the basis to be ordered in a way such that the smallest basis vectors comes first. Intuitively, it would also be better to reduce a vector by the larger vectors first before reducing by the smaller vectors, a very vague analogy to filling up a jar with big stones first before putting in the sand. This leads us to the following size reduction algorithm:
Gram-Schmidt Orthogonalization
Overview
Gram-Schmidt orthogonalization is an algorithm that takes in a basis as an input and returns a basis where all vectors are orthogonal, i.e. at right angles. This new basis is defined as
where is the Gram-Schmidt coefficients.
One can immediately check that this new basis is orthogonal
Z5 = Zmod(5) # Technically it's a ring but we'll use the addition here
print(Z5.list())
# [0, 1, 2, 3, 4]
print(Z5.addition_table(names = 'elements'))
# + 0 1 2 3 4
# +----------
# 0| 0 1 2 3 4
# 1| 1 2 3 4 0
# 2| 2 3 4 0 1
# 3| 3 4 0 1 2
# 4| 4 0 1 2 3
a, b = Z5(14), Z5(3)
print(a, b)
# 4 3
print(a + b)
# 2
print(a + 0)
# 4
print(a + (5 - a))
# 0
n = 11
Zn = Zmod(n)
a, b = Zn(5), Zn(7)
print(n - (a + b))
# 10
print((n - a) + (n - b))
# 10
Z12 = Zmod(12) # Residues modulo 12
print(Z12.order()) # The additive order
# 12
a, b= Z12(6), Z12(3)
print(a.order(), b.order())
# 2 4
print(a.order() * a)
# 0
print(ZZ.order()) # The integers under addition is a group of infinite order
# +Infinity
p = 101 # prime
Zp = Zmod(p)
H_list = Zp.multiplicative_subgroups() # Sage can get the subgroup generators for us
print(H_list)
# ((2,), (4,), (16,), (32,), (14,), (95,), (10,), (100,), ())
g1 = H_list[3][0] # Weak generator
print(g1, g1.multiplicative_order())
# 32 20
g2 = Zp(3) # Strong generator
print(g2, g2.multiplicative_order())
# 3 100
## Consider the following functions
def brute_force(g, p, secret_value):
"""
Brute forces a secret value, returns number of attempts
"""
for i in range(p-1):
t = pow(g, i, p)
if t == secret_value:
break
return i
def mean_attempts(g, p, num_keys):
"""
Tries `num_keys` times to brute force and
returns the mean of the number of attempts
"""
total_attempts = 0
for _ in range(num_keys):
k = random.randint(1, p-1)
sv = pow(g, k, p) # sv = secret value
total_attempts += brute_force(g, p, sv)
return 1. * total_attempts / num_keys
## Let's try with our generators
print(mean_attempts(g1, p, 100)) # Weak generator
# 9.850
print(mean_attempts(g2, p, 100)) # Strong generator
# 49.200
def euclid(m,n):
while n!=0:
q = round(m/n)
m -= q*n
if abs(n) > abs(m):
m, n = n, m
return abs(m)
def lagrange(b1,b2):
mu = 1
while mu != 0:
mu = round((b1*b2) / (b1*b1))
b2 -= mu*b1
if b1*b1 > b2*b2:
b1, b2 = b2, b1
return b1, b2
sage: G = DihedralGroup(99)
sage: g = G.random_element()
sage: discrete_log(g^9,g) # note that if the order of g is less than 9 we would get 9 mod g.order()
9
Applications
We shall now provide a few instances where lattices are used in various algorithms. Most of these uses the LLL algorithm as it is quite fast.
Definitions
A basis{bi}i=1dis size-reduced if ∣μi,j∣≤21. Intuitively this captures the idea that a reduced basis being "almost orthogonal".
Let Lbe a lattice, 1≤i≤dimL=d, we define the ithsuccessive minimaλi(L) as
Intuitively, λi(L)is the length of the "ith shortest lattice vector". This intuition is illustrated by the definition of λ1:
However this is not precise as if vis the shortest lattice vector, then −vis also the shortest lattice vector.
Unfortunately, a basisbifor Lwhere λi(L)=∥bi∥for dimensions 5 and above. This tells us that we can't actually define "the most reduced basis" in contrast to the 2D case (see Lagrange's algorithm) and we would need some other definition to convey this intuition.
An alternate definition ofλi(L)that will be helpful is the radius of the smallest ball centered at the origin such that the ball contains at leastilinearly independent vectors inL.
Exercises
1) Show that both definitions of λi are equivalent
2) Consider the lattice L=2000102001002010002100001. Show that the successive minima are all2but no basisbican satisfy ∥bi∥=λi.
λi(L)=min(1≤j≤imax(∥vj∥):vj∈L are linearly independent)
λ1(L)=min(∥v∥:v∈L)
Bounds
πi
{bj}j=1i−1
∣∣bi∗∣∣=λ1(πi(L))
i+34≤(λi(L)∣∣bi∣∣)2≤4i+3
Bounds
The proof presented here is based off [Waerden 1956]. We proceed by induction. Letbibe a Minkowski-reduced basis for some latticeL. The lower bound is immediate and for i=1, the upper bound is immediate as well.
Let v1,v2…vibe linearly independent vectors such that∥vj∥=λj(L). Let Li−1be the sublattice generated by b1,b2,…bi−1. Evidently somekmust exist such thatvkis not in Li−1. Consider the new lattice L′=L∩span(b1,b2,…bi−1,vk). Letvk′be the shortest vector inL′−Li−1such thatb1,b2,…,bi−1,vk′is a basis for L′and we have
Ifn=1, then we are done sincevkcan be extended to a basis of L, so ∥bi∥≤∥vk∥=λk(L)≤λi(L). Otherwise, we have n2≥4. Let vk′=p+qwherepis the projection ofvk′inLi−1. Since by definition we have∥p∥2≤∥p±bi∥2, we must have
Furthermore, since
we have ∥q∥2≤41λk2, hence we have
but since λi(L)2≤∥bi∥2by definition, the case of i=2,3cannot occur here (hence n=1in these cases).
Exercises
1) Show that both definitions of Minkowski-reduced lattice are equivalent
2) Consider the lattice L=2000102001002010002100001. We have showed in a previous exercise that the successive minima are all2but no basisbican satisfy ∥bi∥=λi, show that for any Minkowski reduced basis bi, the basis must satisfy ∥bi∥2=max(1,(45)i−4)λi(L)2
We can further improve this by optimizing the Gram Schmidt computation as this algorithm does not modify B∗at all. Furthermoreμchanges in a very predictable fasion and when vectors are swapped, one can write explicit formulas for howB∗changes as well.
Next, we need to figure a swapping condition. Naively, we want
for all i. However, such a condition does not guarantee termination in polynomial time. As short basis vectors should be almost orthogonal, we may also want to incorperate this notion. Concretely, we want ∣μi,j∣to be somewhat small for all pairs of i,j, i.e. we may want something like
However, since μi,j=⟨bj∗,bj∗⟩⟨bi,bj∗⟩, this condition is easily satisfied for a sufficiently long bj∗, which is not what we want. The key idea is to merge these two in some way and was first noticed by Lovász - named the Lovász condition:
It turns out that using this condition, the algorithm above terminates in polynomial time! More specifically, it has a time complexity of O(d5nlog3B)where we havedbasis vectors as a subset of Rnand Bis a bound for the largest norm of bi. 41<δ ensures that the lattice vectors are ordered roughly by size and δ<1ensures the algorithm terminates.
Polynomial time proof
This follows the proof provided by the authors of the LLL paper. We first prove that the algorithm terminates by showing it swaps the vectors finitely many times. Letdbe the number of basis vectors as a subset of Rn. Let dibe the volume of the lattice generated by {bj}j=1iat each step of the algorithm. We have di=∏j=1ibj∗. Now consider the quantity
This quantity only changes whenever some bi∗changes, i.e when swaps happen. Let's consider what happens when we swap biand bi+1. Recall the Gram-Schmidt algorithm:
From this, see that when we swap biand bi+1, bi∗is replaced by bi+1∗+μi+1,ibi∗. Now using the Lovász condition, we see that we havebi+1∗+μi+1,ibi∗2<δ∥bi∗∥2, hence the value of dimust decrease by at least δ, i.e. the new diis less than δdi. All other dj,j=imust remain the same as the volume remains fixed when we swap basis vectors around. Hence at each swap, Ddecreases by δ. This is why we need δ<1.Now we are left with showing diis bounded from below then we are done.
Let λ1(L)be the length of the shortest (nonzero) vector in the lattice. We can treat dias the volume of the lattice Ligenerated by{bj}j=1i. Let xibe the shortest vector in the lattice in Li. By using Minkowski's lattice point theorem, we have
(Note that the value of Ciisn't particularly important, one can use a easier value like i)
Hence we see that di, and hence Dhas a (loose) lower bound Dmin=∏i=1ddi,min, meaning that there are at most logDminδlogDswaps. Since at each iteration,keither increases by1when there is no swaps or decreases by at most1when there is swaps and kranges from2tod, the number of time the loop runs must be at most 2logDminδlogD+d, hence the algorithm terminates.
This proof also gives us a handle on the time complexity of the operation. LetBis the length of the longest input basis vector. Since we have di≤Bi, D≤B2m2+mand the algorithm loops O(d2logB)times. The Gram-Schmidt orthogonalization is the most expensive part in the entire process, taking up O(d2n)arithmetic operations. By using classical algorithm for arithmetic operations, each takes O(nlogB)time. From this, we deduce that the time complexity of the LLL algorithm is O(d5mlog2B), a somewhat reasonable polynomial time algorithm.
Let bibe the output of the LLL algorithm, it turns out that we have the bound
which requires δ>41. Such bounds for the shortest vector will be elaborated in more detail in the section on reduced basis.
Exercises
1) Implement the LLL in sage and experimentally verify that Ddoes indeed decrease byδeach time.
2) Show that the time complexity analysis is correct, and indeed each loop takes at most O(d2n)operations.
Let Bbe the matrix where the ith row is given by biandB∗be the matrix where the ith row is given by bi∗, then the Gram-Schmidt orthogonalization gives us B=μB∗where μi,i=1,μj,i=0and μi,jis the Gram-Schmidt coefficient. As an example, consider the basis of a subspace of R4:
Instead of doing the Gram-Schmidt orthogonalization by hand, we can get sage to do it for us:
This outputs two matrices, B∗and μ:
One can quickly verify that B=μB∗ and that the rows of B∗are orthogonal to each other.
A useful result is that
Intuitively, this tells us that the more orthogonal a set of basis for a lattice is, the shorter it is as the volume must be constant.
Exercises
1) Show that the basis bi∗is orthogonal.
2) Verify that the output of sage is indeed correct.
3) Show that μμT=1and B∗B∗T is a diagonal matrix whose entries are ∥bi∗∥. Conclude that det(BBT)=det(B∗B∗T)=∏i∥bi∗∥.
4*) Given the Iwasawa decomposition B=LDOwhere Lis a lower diagonal matrix with 1on its diagonal, Dis a diagonal matrix and Oan orthogonal matrix, meaning OOT=1, show that B∗=DOand μ=L. Furthermore, prove that such a decomposition is unique.
sage: R = Integers(99)
sage: a = R(4)
sage: b = a^9
sage: b.log(a)
9
x = int(pari(f"znlog({int(b)},Mod({int(a)},{int(n)}))"))
x = gp.znlog(b, gp.Mod(a, n))
p = getPrime(36)
n = p^2
K = Zmod(n)
a = K.multiplicative_generator()
b = a^123456789
time int(pari(f"znlog({int(b)},Mod({int(a)},{int(n)}))"))
# CPU times: user 879 µs, sys: 22 µs, total: 901 µs
# Wall time: 904 µs
# 123456789
time b.log(a)
# CPU times: user 458 ms, sys: 17 ms, total: 475 ms
# Wall time: 478 ms
# 123456789
time discrete_log(b,a)
# CPU times: user 512 ms, sys: 24.5 ms, total: 537 ms
# Wall time: 541 ms
# 123456789
p = getPrime(100)
n = p^2
K = Zmod(n)
a = K.multiplicative_generator()
b = a^123456789
time int(pari(f"znlog({int(b)},Mod({int(a)},{int(n)}))"))
# CPU times: user 8.08 s, sys: 82.2 ms, total: 8.16 s
# Wall time: 8.22 s
# 123456789
def LLL(B):
d = B.nrows()
i = 1
while i<d:
size_reduce(B)
if swap_condition(B):
i += 1
else:
B[i],B[i-1] = B[i-1],B[i]
i = max(i-1,1)
return B
def size_reduce(B):
d = B.nrows()
i = 1
while i<d:
Bs,M = B.gram_schmidt()
for j in reversed(range(i)):
B[i] -= round(M[i,j])*B[j]
Bs,M = B.gram_schmidt()
return B
The Coppersmith algorithm can be made even more general. There are two main extensions, first to an unknown modulus, then to multivariate polynomials.
Unknown modulus
This extension of Coppersmith allows one to find small roots modulo an unknown some unknown factor of a number. More specifically, suppose that we have some unknown factorbofNsuch that b<Nβand some monic polynomialfof degreedsuch that f(x0)=0(modb)for some x0<Ndβ2. Then we can findx0in time polynomial in .
One key reason why this is possible is because we dont need to explicitly know the modulus to determine if a small root exists, i.e. is sufficient for a root less thanto exist. The algorithm here is extremely similar to the Coppersmith algorithm, except we add more polynomials into the lattice. The polynomials that we will use are
The latticegenerated by these polynomials would have
As we require the shortest vector to have length at most , repeating the computations from the previous section, we obtain
It turns out that the maxima of is as . One way to achieve this is by settingand we obtain
and this indeed achieves the bound. Similar to the Coppersmith algorithm, one chooses a sufficiently big such that the remainding bits can be brute forced in constant time while the algorithm still remains in polynomial time.
Exercises
1) We show that the maximum ofis indeed . We can assume that . Since and , the maximum occurs when and , hence we have reduced this to maximizing which achieves its maximum of at .
Hard lattice problems
This section is not complete. Help is needed with relevance + examples in cryptography, algorithms + hardness, relations between problems.
Also needs review from more experienced people.
Introduction
Now that we are comfortable with lattices we shall study why are they important to cryptography.
Like we said, when we construct cryptosystems we usually are looking for hard problems to base them on. The lattice world provides us with such problems such as the shortest vector problem or the closest vector problem.
What makes lattices even more special is that some cryptographic problems (which we will study in the next chapter) can be reduced to worst-case lattice problems which makes them crazy secure. Moreover, some problems are even secure against quantum computers.
But enough talk, let's get right into it!
Shortest vector problem + GapSVP
Before we go into any problems we must first define the concept of distance in a lattice.
Let:
Lattice
the basis of the lattice
the dimension of the lattice
Distance function
Given some distance function (Example: Euclidean norm) the distance from a vector to the lattice is the distance from the vector to the closest point in the in lattice.
We will denote the length of the shortest vector with and the length of the next independent vectors in order with
Shortest vector problem
Given a lattice and an arbitrary basis for it our task is to find the shortest vector .
Approximate SVP
We relax the SVP problem a bit. Given an arbitrary basis find a shortest nonzero lattice vector such that . Here is some approximation factor.
Decision SVP (GapSVP)
Given a lattice with a basis we must distinguish if or
Sage example
Closest Vector problem + GapCVP
Closest vector problem
Given a lattice with an arbitrary basis and a vector find the closest lattice vector to
Approximate CVP
Given a lattice with an arbitrary basis and a vector find the closest lattice vector to
Decision CVP (GapCVP)
Given a lattice with a basis and a vector we must decide if
There exists s.t
Sage example
Bounded distance decoding
Given a lattice with an arbitrary basis , a vector and a real number find a lattice vector s.t
Remark
If we have the solution to the BDD problem is guaranteed to be unique.
Shortest independent vectors (SIVP)
Given a full rank lattice with an arbitrary basis find linearly independent lattice vectors of length at most or for the approximate version.
Hardness of lattice problems
Resources
Pictures taken from and "Cryptography made simple - Nigel Smart" and edited a bit
Or generated by me
LLL reduced
Definition
Let δ∈(41,1). A basis{bi}i=1dis δ- LLL-reduced if it is size reduced and satisfy the Lovász condition, i.e.
δ∥bi∗∥2≤bi+1∗+μi+1,ibi∗2
This notion of reduction is most useful to use for fast algorithms as such a basis can be found in polynomial time (see LLL reduction).
Bounds
Short integer solutions (SIS)
Introduction
In this section we will study the short integer solution problem and a hashing algorithm that is based on this algorithm.
Short integer solution problem
Definition
Let be a Short Integer Solution problem. We define it as such:
Given uniformly random vectors , forming the columns of a matrix , find a nonzero integer vector of norm (short) such that
Without the constraint the solution would be as simple as Gaussian elimination. Also we want otherwise would be a fine solution.
Notice that a solution for can be converted to a solution for the extension by appending s to
big easy (the more vectors we are given, the easier the problem becomes)
big hard (the more dimension we work in the harder the problem becomes)
Solution existence is based on parameters set. One should think about them as follows:
is the security parameter. The bigger it is the harder the problem becomes
is set depending from application to application. Usually
, think of it as
SIS as a SVP problem
// TODO
Ajtai's hashing function
Parameters: ,
Key:
Input: Short vector
Hash function properties:
Compression
We know and . Since we chose .
Collision resistance:
halp here
Sage example:
Cryptanalysis
Inverting the function:
Given and find such that
Formulating as a lattice problem:
Find arbitrary such that
All solutions to are of the form where
So we need to find a short vector in
Equivalent, find closest to (CVP)
Hermite normal form
// TODO
Security Reduction
If somebody can explain the security bounds and reduction better, please do.
Resources
+
- page 18
Lattices of interest
Needs review.
Introduction
In this chapter we will study some specific types of lattices that appear in cryptography. These will help us understand how certain problems we base our algorithms on reduce to other hard problems. They will also give insight about the geometry of lattices.
Intuitively, if we have a problem (1) in some lattice space we can reduce it to a hard problem (2) in another related lattice space. Then if we can prove that if solving problem (1) implies solving problem (2) then we can conclude that problem (1) is as hard as problem (2)
Understanding this chapter will strengthen the intuition for the fututre when we will study what breaking a lattice problem means and how to link it to another hard lattice problem.
Dual lattice
Let L⊂Rnbe a lattice. We define the dual of a lattice as the set of all vectors y∈span(L) such that y⋅x∈Zfor all vectors x∈L:
Note that the vectors in the dual lattice L∨ are not necessarily in the initial lattice L. They are spanned by the basis vectors of the lattice L.
Examples:
(Zn)∨=Zn because the dot product of all vectors in Znstays in Zn
Scaling: (k⋅L)∨=k1⋅LProof:
If y∈(kL)∨⇒y⋅kx=k(x⋅y)∈Z∀x∈L⇒y∈k1L∨
If y∈(k1L)∨⇒yv∈L∨⇒ky⋅x=k(x⋅y)=y⋅kx∈Z∀x∈L⇒y∈(kL)∨
Plot: 2Z2 - green, 21Z2 - red
Intuition: We can think of the dual lattice L∨ as some kind of inverse of the initial lattice L
Basis of the dual lattice
We will now focus on the problem of finding the basis B∨ of the dual lattice L∨given the lattice L and its basis B.
Reminder: We can think of the lattice L as a transformation given by its basis B∈GLn(R)on Zn.
We have the following equivalences:
Therefore L∨=(B−1)T⋅Znso we have found a base for our dual lattice:
Let's look at some plots. With green I will denote the original lattice and with red the dual. The scripts for the plots can be found in in the interactive fun section
Properties
L1⊆L2⟺L2∨⊆L1∨
(L∨)∨=L=The dual of the dual is the initial lattice (to prove think of the basis of L∨)
det(L∨)=det(L)−1 (to prove think of the basis of L∨)
For consider the vector dot product and addition
-
- has no geometric meaning, they are in different spaces
Successive minima
We've seen that we can find the basis of the dual lattice given the basis of the original lattice. Let's look at another interesting quantity: the successive minima of a lattice L and its dual L∨. Let's see what can we uncover about them.
We recommend to try and think about the problem for a few minutes before reading the conclusions.
What is λ1(2Z2)? What about λ1((2Z2)∨)? Can you see some patterns?
Reminder: We defined the successive minima of a lattice Las such:
λi(L)=min(1≤j≤imax(∥vj∥):vj∈L are linearly independent)
Claim 1:
Proof:
By Minkowski's bound we know:
λ1(L)≤n⋅det(L)1/n and λ1(L∨)≤n⋅det(L∨)1/n=det(L)1/nn. By multiplying them we get the desired result.
From this result we can deduce that the minima of the L and L∨have an inverse proportional relationship (If one is big, the other is small).
Claim 2:
Proof:
Letx∈L be such that ∥x∥=λ1(L). Then take any set (y1,...,yn) of n linearly independent vectors in L∨.
Not all of them are orthogonal to x. Hence, there exists an i such that yi⋅x=0 .
By the definition of the dual lattice, we have yi⋅x∈Z and hence 1≤yi⋅x≤∥yi∥⋅∥x∥≤λ1⋅λn∨
Geometry + Partitioning
// TODO
Q-ary lattices
We've seen that in cryptography we don't like to work with infinite sets (like Z) and we limit them to some finite set using the mod operation (Z→Z/qZ). We will apply the same principle to the lattices so let us define the concept of a q-ary lattice.
Definition:
For a number q∈Z,q≥3we call a lattice q-ary if
Intuition:
qZn⊆L is periodic modq
We use arithmetic modq
We will now look at 2 more types of lattices that are q-ary. Let A∈(Z/qZ)n×m be a matrix with m>n. Consider the following lattices:
Lq(A)={y∈Zm:y=ATxmodq∈ for some x∈Zn}⊂ZmLq⊥(A)={y∈Zm:Ay=0modq}⊂Zm
Intuition:
Think of Lq(A) as the image of the matrix A, the matrix spanned by the rows of A
Think of Lq⊥(A) as the kernel of A modulo q. The set of solutions Ax=0
Remark: If the same matrix A is used (A is fixed ) then Lq(A)=Lq⊥(A)
Claim:
Lq(A) and Lq⊥(A) are the dual of each other (up to scaling): Lq(A)=q1Lq⊥(A)
Proof:
Firstly we will show Lq⊥(A)⊆q(Lq(A))∨
Let y∈Lq⊥(A)⇒Ay≡0modq⟺Ay=qzfor some z∈Zm
Let y′∈Lq(A)⇒y′≡ATxmodq⟺y′=ATx+qz′ for some x∈Zn,z′∈Zm
Then we have:y⋅y′=y⋅(ATx+qz′)=y⋅ATx+q(y⋅z′)=qzAy⋅x+q(y⋅z′)=qz⋅x+q(y⋅z′)
⇒q1y⋅y′∈Z⇒q1y∈Lq(A)∨
The second part is left as an exercise to the reader :D. Show Lq⊥(A)⊇q(Lq(A))∨
Nguyen, P. Q., & Vallée, B. (Eds.). (2010). The LLL Algorithm. Information Security and Cryptography. doi:10.1007/978-3-642-02295-1
Massive survey, lots of detail if you're extremely interested)
May, A. (2003). New RSA Vulnerabilities Using Lattice Reduction Methods. Universität Paderborn.
Excellent exposition to LLL and coppersmith as well as showing some RSA attacks via LLL
Lenstra, A. K., Lenstra, H. W., & Lovász, L. (1982). Factoring polynomials with rational coefficients. Mathematische Annalen, 261(4), 515–534. doi:10.1007/bf01457454
The original LLL paper, quite a nice read overall + proof that LLL works
Coppersmith, D. (1996). Finding a Small Root of a Univariate Modular Equation. Lecture Notes in Computer Science, 155–165. doi:10.1007/3-540-68339-9_14
Coppersmith, D. (1996). Finding a Small Root of a Bivariate Integer Equation; Factoring with High Bits Known. Lecture Notes in Computer Science, 178–189. doi:10.1007/3-540-68339-9_16
Both of these paper introduces the coppersmith algorithm as well as provide some examples
Waerden, B. L. (1956). Die Reduktionstheorie Der Positiven Quadratischen Formen. Acta Mathematica, 96(0), 265–309. doi:10.1007/bf02392364
Notation
lattice
dimension of lattice
volume of lattice
Proof of correctness
We now consider cd=med=mnecessary for the successful description of an RSA ciphertext. The core of this result is due to Euler's theorem which states
As a reminder, we say two integers are coprime if they share no non-trivial factors. This is the same statement that gcd(a,n)=1.
From the definition of the protocol, we have that
for some . Combining this with Euler's theorem, we see that we recover from the ciphertext
When the requirement does not hold, we can instead look at the equivalences modulo and respectively. Clearly, when we have that and our correctness still holds. Now, consider the case where we have that and Since we have already excluded the case that we can conclude that as is prime. This means that and by the multiplicative properties of the function, we determine that We conclude by invoking the Chinese Remainder theorem with
that The case for follows in a parallel manner.
Coppersmith algorithm
This algorithm solves for small roots of polynomials modulo any integer, meaning given some polynomial f(x)∈Z[x]of degree dand any integer N, then if f(x0)=0(modN),∣x0∣<Nd1, this algorithm can findx0with time polynomial in logNand d. The key idea behind this algorithm is to construct a polynomialg(x)such that g(x0)=0in R. As roots of polynomials over the reals can be found easily, this gives an easy way to find x0. We shall introduce the Coppersmith algorithm in a few iterations, with each iteration approaching the Nd1bound.
Polynomials in lattices
We first consider a criteria for a root of a polynomial moduloto exists over the reals as well. Supposeis a polynomial of degree. Define the norm of a polynomial to be . Given , if
then in . The proof is a relatively straightforward chain of inequalities:
and since implies for some , we know that must beto satisfy the inequality above.
With this, if we can find some polynomials such that , then if we can find some such that , then we can find easily. This gives a brief idea as to why lattices would be useful in such a problem.
To use lattices, notice that we can encode the polynomial as the vector with components . In this way, adding polynomials and multiplying polynomials by numbers still makes sense. Lets suppose that and (otherwise multiplyby . Consider the polynomials and consider the latticegenerated by and , . As a matrix, the basis vectors are
As every element in this lattice is some polynomial , if , then. Furthermore, if and a short vectorhas length less than , then we have in .
The volume of this lattice is and the lattice has dimension . By using the LLL algorithm, we can find a vector with length at most
As long as , then by the above criteria we know that this vector has has a root over . This tells us that
While this isn't the bound that we want, this gives us an idea of what we can do to achieve this bound, i.e. add more vectors such that the length of the shortest vector decreases.
Achieving the bound
One important observation to make is that any coefficients in front ofdoes not matter as we can simply brute force the top bits of our small root in time. Hence we only need to getfor some fixed constant.
In order to achieve this, notice that if , then . This loosens the inequality required for a polynomial to have as a small root as our modulus is now larger. With this in mind, consider the polynomials
where we will determinelater. Here , hence we shall consider the lattice generated by . As an example, if we have
the basis vectors of our lattice would look like
We have the following immediate computations of :
hence when using the LLL algorithm, the shortest LLL basis vectorhas length
and we need for . Hence we have
Since , this will achieve the bound that we want. However as for big , the LLL algorithm would take a very long time, we typically choose a suitably largesuch that the algorithm is still polynomial in and brute force the remaining bits.
Exercises
1) We often see in literature. We shall now show where this mysteriouscomes from. The other term will appear in the next exercise. Typically, one sets to simplify calculations involving the LLL algorithm as . Suppose we want , show that this gives us .
2) We show that we can indeed find small roots less thanin polynomial time. In the worse case, the longest basis vector cannot exceed . Hence the LLL algorithm will run in at mosttime.
Let
and choose , then is a constant hence the number of bits needed to be brute forced is a constant. This gives us the approximate run time of .
3) We shall show that this is the best bound we can hope for using lattice methods. Suppose there exists some algorithm that finds roots less than in polynomial time. Then consider the case whenand . Show that this forces the lattice to have a size too big for the algorithm to run in polynomial time, assuming the algorithm finds all small roots.
Common Modulus Attack
What to do when the same message is encrypted twice with the same modulus but a different public key?
Imagine we have Alice and Bob. Alice sends the SAME message to Bob more than once using the same public key. The internet being the internet, a problem may happen; a bit is flipped, and the public key changed while the modulus stayed the same.
What we know
Let be the following:
Wiener's Attack
Wiener's attack is an attack on RSA that uses continued fractions to find the private exponent when it's small (less than , where is the modulus). We know that when we pick the public exponent to be a small number and calcute its inverse
Wiener's theorem
Wiener's attack is based on the following theorem:
RSA application
Tutorial for application with RSA. We are going to use openSSL, openSSH and pycryptodome for key generation, key extraction and some implementation with python
Pycryptodome:
Pycryptodome is a python library about cryptography, see the documentation below: There is an example of RSA key generation with pycryptodome:
RSA
Will be introduced in this page the fundamentals of RSA, mathematical requirement and also some application with python and openSSL.
This page is pretty long, probably could be split up
Edit: I haved deleted the last part, application with RSA, and i made a special part for this. Maybe we can do the same with the second part: Arithmetic for RSA.
Recovering the Modulus
When you want to recover N given some (plaintext, ciphertext) pairings
Scenario
Consider the case that that you know a set of (plaintext, ciphertext) pairings - this may be that you are provided them, or that you have access to some functionality that returns ciphertexts for provided plaintexts. If you do not know the modulus, but know the exponent used (note: this may be prone to a brute-force regardless), then given these pairings you can recover the modulus used.
Encryption
Author: Chuck_bartwoski
Introduction
A typical application of cryptography is secure communication. Informally a secure communication channel is one that provides both confidentiality and Integrity of the messages. In this section we investigate confidentiality, therefore we may assume that integrity is already guaranteed by some other means. (see section on integrity...#TODO)
We assume that two parties that want to communicate share a secret key . Prior to sending a message, the sender encrypts the message with the secret key, this produces a ciphertext that is then sent. The receiver uses the same key to decrypt the message and recover the message.
from Crypto.Util.number import long_to_bytes, bytes_to_long
n, m, q = 20, 40, 1009
set_random_seed(1337)
A = random_matrix(Zmod(q),n, m)
print(A.parent())
# Full MatrixSpace of 20 by 40 dense matrices over Ring of integers modulo 1009
print(A.lift().parent())
# Full MatrixSpace of 20 by 40 dense matrices over Integer Ring
msg = b'msg'
x = vector(Zmod(q), [int(i) for i in bin(bytes_to_long(msg))[2:].zfill(m)]) # pad message
print(len(x)
# 40
print(x.parent())
# Vector space of dimension 40 over Ring of integers modulo 1009
print(len(A * x))
# 20
n = 5 # lattice dimension
B = sage.crypto.gen_lattice(m=n, q=11, seed=42)
B_dual = sage.crypto.gen_lattice(m=n, q=11, seed=42, dual=True)
B_dual_ = (B.inverse().T * 11).change_ring(ZZ) # Scale up to integers
B_dual_.hermite_form() == B_dual.hermite_form() # Reduce form to compare
# True
n = 5 # lattice dimension
B = sage.crypto.gen_lattice(m=n, q=11, seed=42)
B_dual = sage.crypto.gen_lattice(m = n, q=11, seed=42, dual=True)
l1 = IntegerLattice(B).shortest_vector().norm().n()
B_dual_lll = B_dual.LLL()
lnd = 0
for v in B_dual_lll:
lv = v.norm()
if lv > lnd:
lnd = lv
lnd = lnd.n() / 11
print(lnd * l1 > 1)
# True
@interact
def draw_cvp(v1x = input_box(label = "v1 x =", default = 1),
v1y = input_box(label = "v1 y =", default = 0),
v2x = input_box(label = "v2 x =", default = 0),
v2y = input_box(label = "v2 y =", default = 1),
wx = input_box(label = "w x =", default = 1.8),
wy = input_box(label = "w y =", default = 1.7),
box = 5, search = 10):
v1 = vector((v1x, v1y))
v2 = vector((v2x, v2y))
print(v1, v2)
vecs = []
# Generate vectors
for i in range(-search,search):
for j in range(-search,search):
vecs.append(i*v1 + j*v2)
# Plot stuff
G = Graphics()
for p1 in vecs:
x1, y1 = p1
if x1 > -box and x1 < box and y1 > -box and y1 < box:
G += point(p1, color = 'green', size = 30)
G += line([p1, p1 + v2], linestyle = '--', alpha = .20)
G += line([p1, p1 + v1], linestyle = '--', alpha = .20)
G+= arrow((0, 0), v1, color = 'red', arrowsize = 2)
G+= arrow((0, 0), v2, color = 'red', arrowsize = 2)
G+= text('v1', v1 + .2 * v1, color = 'red')
G+= text('v2', v2 + .2 * v2, color = 'red')
# Cvp
L = IntegerLattice(matrix([v1, v2]))
w = vector((wx, wy))
t = L.closest_vector(w)
G += point(w, color = 'purple', size = 30)
G+= text('w', w + .2 * v1, color = 'purple')
G += point(t, color = 'red', size = 30)
G+= text('t', t + .2 * v1, color = 'red')
G+= circle(center = w, radius=norm(t - w), color = 'purple', alpha = .5)
G.show(axes = False, figsize = (7, 7))
@interact
def draw_dual(v1x = input_box(label = "v1 x =", default = 1),
v1y = input_box(label = "v1 y =", default = 0),
v2x = input_box(label = "v2 x =", default = 0),
v2y = input_box(label = "v2 y =", default = 1),
box = 3, search = 6,
plot_lattice_points = True,
plot_lattice_lines = True,
plot_dual_points = True,
plot_dual_lines = True):
v1 = vector((v1x, v1y))
v2 = vector((v2x, v2y))
vecs = []
v1_, v2_ = matrix([v1,v2]).inverse().T
vecs_ = []
# Generate vectors
for i in range(-search,search):
for j in range(-search,search):
vecs.append(i*v1 + j*v2)
for i in range(-search,search):
for j in range(-search,search):
vecs_.append(i*v1_ + j*v2_)
# Plot stuff
G = Graphics()
for p1 in vecs:
x1, y1 = p1
if x1 > -box and x1 < box and y1 > -box and y1 < box:
if plot_lattice_points:
G += point(p1, color = 'green', size = 70)
if plot_lattice_lines:
G += line([p1, p1 + v2], linestyle = '--', alpha = .20, color = 'green')
G += line([p1, p1 + v1], linestyle = '--', alpha = .20, color = 'green')
if plot_lattice_lines:
G+= arrow((0, 0), v1, color = 'green', arrowsize = 2)
G+= arrow((0, 0), v2, color = 'green', arrowsize = 2)
G+= text('v1', v1 + .2 * v1, color = 'green')
G+= text('v2', v2 + .2 * v2, color = 'green')
# Dual
for p1 in vecs_:
x1, y1 = p1
if x1 > -box and x1 < box and y1 > -box and y1 < box:
if plot_dual_points:
G += point(p1, color = 'red', size = 25)
if plot_dual_lines:
G += line([p1, p1 + v2_], linestyle = '--', alpha = .20, color = 'red')
G += line([p1, p1 + v1_], linestyle = '--', alpha = .20, color = 'red')
if plot_dual_lines:
G+= arrow((0, 0), v1_, color = 'red', arrowsize = 2)
G+= arrow((0, 0), v2_, color = 'red', arrowsize = 2)
G+= text('v1\'', v1_ + .2 * v1, color = 'red')
G+= text('v2\'', v2_ + .2 * v2, color = 'red')
G.show(axes = False, figsize = (7, 7))
# I'm not sure this does what is supposed to do
# but the plots are nice
from sage.modules.free_module_integer import IntegerLattice
@interact
def draw_qary(v1x = input_box(label = "v1 x =", default = 1),
v1y = input_box(label = "v1 y =", default = 0),
v2x = input_box(label = "v2 x =", default = 0),
v2y = input_box(label = "v2 y =", default = 1),
q = input_box(label = "q =", default = 5),
box = 7, search = 6,
plot_lattice_points = True,
plot_lattice_lines = True,
plot_qary_points = True,
plot_qary_lines = True):
v1 = vector((v1x, v1y))
v2 = vector((v2x, v2y))
L = IntegerLattice(matrix([v1, v2]))
vecs = []
v1_ = v1.change_ring(Zmod(q))
v2_ = v2.change_ring(Zmod(q))
vecs_ = []
# Generate vectors
for i in range(-search,search):
for j in range(-search,search):
v = i*v1 + j*v2
vecs.append(v)
v = v.change_ring(Zmod(q)).change_ring(ZZ)
if v not in vecs_:
vecs_.append(v)
# Lattice
G = Graphics()
for p1 in vecs:
x1, y1 = p1
if x1 > -box and x1 < box and y1 > -box and y1 < box:
if plot_lattice_points:
G += point(p1, color = 'green', size = 70)
if plot_lattice_lines:
G += line([p1, p1 + v2], linestyle = '--', alpha = .20, color = 'green')
G += line([p1, p1 + v1], linestyle = '--', alpha = .20, color = 'green')
if plot_lattice_lines:
G+= arrow((0, 0), v1, color = 'green', arrowsize = 2)
G+= arrow((0, 0), v2, color = 'green', arrowsize = 2)
G+= text('v1', v1 + .2 * v1, color = 'green')
G+= text('v2', v2 + .2 * v2, color = 'green')
# qary
for p1 in vecs_:
p1 = p1
x1, y1 = p1
if x1 > -box and x1 < box and y1 > -box and y1 < box:
if plot_qary_points:
G += point(p1, color = 'red', size = 25)
if plot_qary_lines:
G += line([p1, p1 + v2_], linestyle = '--', alpha = .20, color = 'red')
G += line([p1, p1 + v1_], linestyle = '--', alpha = .20, color = 'red')
if plot_qary_lines:
G+= arrow((0, 0), v1_, color = 'purple', arrowsize = 2)
G+= arrow((0, 0), v2_, color = 'purple', arrowsize = 2)
G+= text('v1\'', v1_.change_ring(ZZ) + .2 * v1, color = 'purple')
G+= text('v2\'', v2_.change_ring(ZZ) + .2 * v2, color = 'purple')
G.show(axes = False, figsize = (10, 10))
# We can find the shortest vector using the LLL algorithm
M = matrix([[-1, 2], [-2, 3]])
B = M.LLL()
print(B[0])
# (0, -1)
# Or we can use the Integer Lattice class
L = IntegerLattice(M)
L.shortest_vector()
# (-1, 0)
M = matrix([[-1, 2], [-2, 3]])
L = IntegerLattice(M)
w = vector([1.8, 1.5])
L.closest_vector(w)
# (2.00000000000000, 2.00000000000000)
bi a chosen basis for L
B matrix whose ith row vectors is bi
bi∗ Gram-Schmidt orthogonalization of bi(without normalization)
Because we are going to need to calculate inverses for this attack, we must first make sure that these inverses exist in the first place:
The math behind the attack
We know that RSA goes as follows:
From the conditions above we also know that e1 and e2 are co-prime. Thus using Bezout's Theorem we can get:
Using this, we can derive the original message m :
NB: all the calculations are done mod n
In general, Bezout's Theorem gives a pair of positive and negative numbers. We just need to adapt this equation a little to make it work for us. In this case, let's assume y is the negative number:
Now to truly recover the plaintext, we are actually doing:
gcd(e1,e2)=1gcd(c2,n)=1
c=memodn
xe1+ye2=gcd(e1,e2)=1
C1x∗C2y=(me1)x∗(me2)y=me1x+e2y=m1=m
Lety=−aC2y=C2−a=(C2−1)a=(C2−1)−y
C1x×(C2−1)−ymodn
OpenSSL:
OpenSSL is a robust, commercial-grade, and full-featured toolkit for the Transport Layer Security (TLS) and Secure Sockets Layer (SSL) protocols. It is also a general-purpose cryptography library
The idea behind this attack is effectively finding common factors between pairings. Recall that, under general RSA encryption, we have:
and recall what modular arithmetic tells us about the relation between these terms, namely that:
This, rearranged, tells us that
What this means for our known pairings is that, given we know m,c and e, we can form the relationship:
Thus we can calculate for the value kN, though don't know either value individually - we want to somehow derive N.
Observe that any two pairings will equate to such a value, both with N as a factor. We can take the gcd of these two values, and it is probable that the resulting value will be our N value, such that:
However, this is only true for the case that
i.e., both k1and k2are coprime. In the case that they are not, i.e. gcd(k1,k2)=1, we have that
In such a case, we don't have sufficient information to completely recover the modulus, and require more plaintext-ciphertext pairs to be successful. In general, the more pairings you have, the more confident you can be the value you calculate is N. More specifically:
Thus:
Practical Notes
In reality, you're likely to only need two or three (plaintext, ciphertext) pairings (in the context of ctf challenges and exercises), and as such computations can be manual if needed, but shouldn't be too complex
As it's likely you'll be dealing with large numbers, overflows and precision errors may arise in code - using libraries like gmpy provide support for integers of (theoretically) infinite size, and some nice accompanying features too (like in-built gcd and efficient modular exponentiation)
These two statements are mathematically equivalent, but one is easier to implement in code:
Code Example
(Mi,Ci) for i∈[1,∞]
C=Me(modN)
a≡b(modN)a=b+kN for some k∈Z
a−b≡0(modN)a−b=kN
Ci−Mie≡0(modN)Ci−Mie=kiN
N=gcd(C1−M1e,C2−M2e)
gcd(k1,k2)=1
aN=gcd(C1−M1e,C2−M2e) s.t. 1=a∈Z
Pr(a=1)→0 as k→∞
N=k→∞limgcd(C1−M1e,C2−M2e,...,Ck−Mke)
gcd(a,b,c,d,...)=gcd(a,gcd(b,gcd(c,gcd(d,...))))
from Crypto.Util.number import getPrime, bytes_to_long
def generate_keys():
e = 0x10001 #public exponent e, we generally use this one by default
while True:
p = getPrime(512)
q = getPrime(512)
phi = (p - 1) * (q - 1) #Euler's totient
d = pow(e, -1, phi) #Private exponent d
if d != -1:
break
n = p * q
public_key = (n, e)
private_key = (n, d)
return public_key, private_key
def encrypt(plaintext: int, public_key) -> int:
n, e = public_key
return pow(plaintext, e, n) #plaintext ** e mod n
def decrypt(ciphertext: int, private_key) -> int:
n, d = private_key
return pow(ciphertext, d, n) #ciphertext ** d mod n
message = bytes_to_long(b"super_secret_message")
public_key, private_key = generate_keys()
ciphertext = encrypt(message, public_key)
plaintext = decrypt(ciphertext, private_key)
import gmpy2
"""
@param pairings
list: [(pt1, ct1), (pt2, ct2), ..., (ptk, ctk)]
@param e
int : encryption exponent
@return
int : recovered N
"""
def recover_n(pairings, e):
pt1, ct1 = pairings[0]
N = ct1 - pow(pt1, e)
# loop through and find common divisors
for pt,ct in pairings:
val = gmpy2.mpz(ct - pow(pt, e))
N = gmpy2.gcd(val, N)
return N
Let
, with
. Let
. Given
and
with
, the attacker can efficiently recover
.
Some observations on RSA
In order to better understand Wiener's Attack, it may be useful to take note of certain properties of RSA:
We may start by noting that the congruence ed≡1modϕ(n) can be written as the equality ed=kϕ(n)+1 for some value k, we may additionally note that ϕ(n)=(p−1)(q−1)=pq−p−q+1, since both p and q are much shorter than pq=n, we can say that ϕ(n)≈n.
Dividing the former equation by dϕ(n) gives us ϕ(n)e=dk+1, and using the latter approximation, we can write this as ne≈dk. Notice how the left-hand side of this equation is composed entirely of public information, this will become important later.
It is possible to quickly factor n by knowing n and ϕ(n). Consider the quadratic polynomial (x−q)(x−p), this polynomial will have the roots p and q. Expanding it gives us x2−(p+q)x+pq, and substituting for the variables we know we can write this as x2−(n−ϕ(n)+1)x+n. Applying the quadratic formula gives us p and q: p∧q=2a−b±b2−4ac, where a=1, b=n−ϕ(n)+1, and c=n.
Wiener's attack works by expanding ne to a continued fraction and iterating through the terms to check various approximations of dk. In order to make this checking process more efficient, we can make a few observations (this part is optional):
Since ϕ(n) is even, and e and d are both by definition coprime to ϕ(n), we know that d is odd.
Given the above equations and the values of e, n, d, and k, we can solve for ϕ(n) with the equation ϕ(n)=ked−1, thus we know that ed−1 has to be divisible by k.
If our is correct, the polynomial will have roots and , which we can verify by checking if .
The Attack
Suppose we have the public key (n,e), this attack will determine d
Convert the fraction ne into a continued fraction [a0;a1,a2,…,ak−2,ak−1,ak]
Iterate over each convergent in the continued fraction: 1a0,a0+a11,a0+a1+a211,…,a0+a1+ak−2+ak−11⋱1,
Check if the convergent is dk by doing the following:
Set the numerator to be and denominator to be
Check if is odd, if not, move on to the next convergent
Check if , if not, move on to the next convergent
Set and find the roots of the polynomial
If the roots of the polynomial are integers, then we've found . (If not, move on to the next convergent)
If all convergents have been tried, and none of them work, then the given RSA parameters are not vulnerable to Wiener's attack.
Here's a sage implementation to play around with:
//TODO: Proof of Wiener's theorem
Automation
The Python module owiener simplifies the scripting process of Wiener's attack:
Here is a Wiener's attack template:
d
314n
n
e
d≡e−1modϕ(n)
n=pq
q<p<2q
d<314n
n
e
ed≡1modϕ(n)
d
I- Introduction:
RSA is a public-key cryptosystem that is widely used in the world today to provide a secure transmission system to millions of communications, is one of the oldest such systems in existence. The acronymRSA comes from the surnames of Ron Rivest, Adi Shamir, and Leonard Adleman, who publicly described the algorithm in 1977. An equivalent system was developed secretly, in 1973 at GCHQ (the British signals intelligence agency), by the English mathematician Clifford Cocks. That system was declassified in 1997.
All public-key systems are based on the concept of trapdoor functions, functions that are simple to compute in one direction but computationally hard to reverse without knowledge of some special information called the trapdoor. In RSA, the trapdoor function is based on the hardness of factoring integers. The function involves the use of a public keyNto encrypt data, which is (supposed to be) encrypted in such a way that the function cannot be reversed without knowledge of the prime factorisation ofN, something that should be kept private. Except in certain cases, there exists no efficient algorithm for factoring huge integers.
Formalize the introduction and include a discussion of the security based on the hardness of factoring integers.
II- Arithmetic for RSA
Before starting to introducing you RSA, a few arithmetic notions need to be introduce to understand perfectly other steps.
III- Key generation
We pick two primes p and q
Using p and q, we calculate modulus n=p×q and its Euler's totient ϕ(n)=(p−1)×(q−1)
Now, choose the public exponentesuch as
By using the Extended Euclidean algorithm, we compute the invert of : which is our private exponent.
Public key:
Private key:
Now, chose a message that you convert into integers
We can encrypt this plaintext and receive a ciphertext
We can decrypt a ciphertext with
IV- Signature
A digital signature is a proof of the authenticity of a message, i.e. a proof that the message has not been tampered with. RSA allows us to sign messages by "encrypting" them using the private key, the result being a signature that anyone can verify by "decrypting" it with the public key and comparing it to the associated message. Any attempt to tamper with the message will result in it no longer matching the signature, and vice-versa. Futhermore, a signature can only be generated using the private key, making it a secure and efficient method of confirming the authenticity of messages.
Say Alice wants to send a message to Bob, but does not want Mallory, who has established herself as a middleman, to make changes to the message or swap it out entirely. Fortunately, Bob knows Alice's public key, and since e and d are inverses such that ed≡1modϕ(n), Alice can sign her message m by "encrypting" it with the private key such that s≡mdmodn, where s is the signature verifying that the message came from Alice. Alice can now send m and s to Bob, who is now able to check the authenticity of the message by checking if m≡semodn. If Mallory tries to change m, this congruence no longer holds, and since she does not have the private key, she is also unable to provide a maching sfor her tampered message.
V- Format
Intuitively: A secure encryption scheme will prevent an eavesdropper to learn the content of the message since the ciphertext is unintelligible. The security requirement will be formalized later.
Formal definition
We introduce some notation first: We will use M to denote the set of al possible message, K is the set of all possible keys and C is the set of ciphertexts.
A symmetric encryption scheme Eis a tuple of efficiently computable functions (KGen, Enc, Dec).:
\text{KGen}: \diamond \xrightarrow $ \mathcal K Selects a key at random from the key space.
Enc:M×K↦C. Encrypts the message m with the key k into a ciphertext c=Enc(m,k). Sometimes written as c=Enck(m)
Dec:C×K↦M×{⊥}. Decrypts the ciphertexts c with the key into the message or returns an error (). . Sometimes written as
ForE to be useful we need that Dec(Enc(m,k),k)=m;∀m,k. This is also called correctness.
After all what's the point of confidentially sending a nice Christmas card to your grand children if they wontbe able to read its content
Boneh-Durfee attack is an extension of Wiener's attack. That is, it also attacks on low private component dwith a further relaxed condition. If dsatisfies:
d<N0.292
Then we can use Boneh-Durfee attack to retrive d
this, using a graphical directed point of view, can be seen as:
{E,n}Pd<N0.292{d}
Consider for first, see that
As stated above, the RSA's totient function can be espressed as:
continuing with the equation, we see that
and if we decide to consider and , we will have:
At this point, finding is equivalent to find the 2 small solutions and to the congruence
now let and this will preserve the scomposed subtraction
consider (with any ), we deduct that must be really closed to because is in the same order of the length of (so ), we will get
Sage Implementation
Diffie-Hellman
Overview
We need to make some changes: separate the explanation from the code, add a subpart about the MITM and maybe to develop more the instructions
Let's say Alice and Bob want to exchange a secret over an insecure channel. In other words, anyone can read the messages they send, but the goal is to ensure that only Alice and Bob can calculate the secret key.
Diffie-Hellman key exchange provides a solution to this seemingly impossible task. Since code may be easier to understand than a detailed explanation, I'll provide it first:
Here's a brief explanation of the code:
We choose a prime and a generator
Alice picks a private key
Bob picks a private key
So anybody observing the messages sent between Alice and Bob would see , but they wouldn't be able to calculate the shared key .
This is because given and , it should be infeasible to calculate . If this sounds familiar, that's because it's the .
The original paper can be found . It uses the group of integers modulo a prime to perform the key exchange. In practice however, any group with a hard discrete log problem can be used.
AES
Advanced Encryption Standard
Introduction
The Advanced Encryption Standard most known as AES is one of the most used ciphers nowadays.
Created by Vinent Rijmen and Joan Daemen under the name Rijndael, it won the NIST competition that resulted in its standardization in 2001 to replace older algorithms such as DES (and its variant 3DES). In fact, it is six times faster than 3DES.
AES encrypts a block of 16 bytes only at a time, though ciphertexts tend to be much longer. To accomodate this, cipherexts are cut in blocks of 16 bytes using an operating mode [see future section on mode]. We only focus on the encryption of a single block.
The array of 16 bytesare arranged from up to bottom, column by column inmatrix. During the encryption, the state of this matrix changes and results in a 16-bytes ciphertextwhose output can be read following the same ordering:
A key is involved and three sizes are possible: 128, 192, or 256 bits. Depending of the size, there are a few differences which will be explained later. For now, it is sufficient to know that round keys are derived from this master key.
Our interest is to look at what goes inside the transformation between the plaintext and the ciphertext. Basically, there are four operations on the state matrix, each important for the security of AES:
AK: add round key;
SR: shift row;
SB: substitution box;
All these operations are executed a several number of times in what are called rounds to mix the plaintext enough. A look on the flow of an encryption is given in the figure below.
Two particular cases can be noticed:
the first round is preceded by an additional AK;
last round is missing MC.
The number of rounds NR is different depending on the master key length:
Rijndael Finite Field
A first time reader might skip this section and go directly to the description of the round transformations, then come back later (it is mostly useful to understand the construction of the operation MC and SB).
Each byte in AES is viewed as an element of a binary finite field of 256 elements, where it can always be represented as a polynomial of degree at most 7 with coefficients in. The construction of the finite field is made as the quotient ring, whereis an irreducible polynomial of degree 8 inso the ring becomes a field.
Round Transformations
This page gives a description of the four operations that compose a round of AES.
Each has been designed to satisfy criterias, one of them is that all must be invertible.
Add Round Key
The One Time Pad
Author: chuck_bartowski
Introduction
The One Time Pad (OTP) is a well known example of encryption schemes that provide "perfect secrecy". Informally, this means that observing a ciphertext does no give any information to the eavesdropper. A proof of this fact will be provided later. Crucially we will assume that the sender and the receiver have both access to a common source of random bits.
Introduction to Isogeny Cryptography
Making this section as a motivation to make sure this is part of the book. Something to work towards.
Page Plan
Describe that there is a drive towards post-quantum algorithms
from Crypto.Util.number import long_to_bytes
def wiener(e, n):
# Convert e/n into a continued fraction
cf = continued_fraction(e/n)
convergents = cf.convergents()
for kd in convergents:
k = kd.numerator()
d = kd.denominator()
# Check if k and d meet the requirements
if k == 0 or d%2 == 0 or e*d % k != 1:
continue
phi = (e*d - 1)/k
# Create the polynomial
x = PolynomialRing(RationalField(), 'x').gen()
f = x^2 - (n-phi+1)*x + n
roots = f.roots()
# Check if polynomial as two roots
if len(roots) != 2:
continue
# Check if roots of the polynomial are p and q
p,q = int(roots[0][0]), int(roots[1][0])
if p*q == n:
return d
return None
# Test to see if our attack works
if __name__ == '__main__':
n = 6727075990400738687345725133831068548505159909089226909308151105405617384093373931141833301653602476784414065504536979164089581789354173719785815972324079
e = 4805054278857670490961232238450763248932257077920876363791536503861155274352289134505009741863918247921515546177391127175463544741368225721957798416107743
c = 5928120944877154092488159606792758283490469364444892167942345801713373962617628757053412232636219967675256510422984948872954949616521392542703915478027634
d = wiener(e,n)
assert not d is None, "Wiener's attack failed :("
print(long_to_bytes(int(pow(c,d,n))).decode())
#!/usr/bin/env python3
import owiener
from Crypto.Util.number import long_to_bytes
#--------Data--------#
N = <N>
e = <e>
c = <c>
#--------Wiener's attack--------#
d = owiener.attack(e, N)
if d:
m = pow(c, d, N)
flag = long_to_bytes(m).decode()
print(flag)
else:
print("Wiener's Attack failed.")
We can check with SageMath that it is irreducible:
Matching Bytes as Finite Field Elements
A byte is composed of 8 bits and is matched to a polynomial as
For instance, take the byte 3a whose binary decomposition is and becomes the polynomial
Polynomial Reduction
Polynomials of degree 8 or more can always be reduced, using the fact that in the finite field, we have , so we have the relation
Why not ? In fact, that's also true, but the coefficient are in so the additive inverse of is itself.
In SageMath, this reduction can be produced in one of the following methods.
Method 1: Remainder of an Euclidean division by
Method 2: Image in the quotient ring
Method 3: Using the Finite Field class of SageMath directly.
On this page we use this last method. Also, this helper converts an element of the finite field to the hexadecimal representation of a byte, and could be useful in the examples:
Addition
The addition of two polynomials is done by adding the coefficients corresponding of each monomial:
And as the addition of the coefficients is in, it corresponds to the bitwise xor operation on the byte.
Multiplication
Multiplication of two polynomials is more complex (one example would be the , more efficient than the naive algorithm). For an implementation of AES, it is possible to only use the multiplication by , whose byte representation is 02.
Letan element and we consider the multiplication by:
All coefficients are shifted to a monomial one degree higher. Then, there are two cases:
Ifis, then we have a polynomial of degree at most 7 and we are done;
Ifis, we can replacebyduring the reduction phase:
This can be used to implement a very efficient multiplication bywith the byte representation:
A bitwise shiftleft operation: (b << 1) & 0xff;
Followed by a conditional addition with 1b if the top bit of is .
Here an example in SageMath (we use the finite field construction of method 3):
F2
F2[x]/f(x)
f
F2[x]
This is the only operation that involves a key. It is obvious that omitting it would mean no encryption.
Round keys are derived from the master key (see the Key Schedule section) and are all composed of 16 bytes.
We simply xor byte by byte the state by the bytes of the round key in the according position.
Its inverse is itself: if we xor again, we get back the original value of the state.
Mix Columns
A major goal of MC is the diffusion property: each byte has an impact on the whole column, so a modification propagates to other positions.
This operation mixes each column of the state independently from each other: each byte of the column is replaced by a (slightly different) combination of the four bytes of the column.
Let the quadruplet of elements of a column, the operation MC is done by multiplying with a matrix .
The calculations are performed in the finite field. If you are not familiar enough with the notions, you can skip to the next part and retain that this operation is also invertible using another matrix.
This matrix is circulant: each row is the same as the one above but is shifted by one column. So we can construct it in one line of SageMath (recall that the bytes 02 and 03 correspond respectively to and in the field):
Inverse of Mix Column
It is needed to reverse MC for the decryption process. Fortunately, there exists a matrix such that , the identity matrix.
We remark that the coefficient of the matrix are less friendly for the inverse operation as it involves polynomial of higher degree.
This means that the decryption is a bit slower.
Shift Rows
The goal of shifting rows is reinforce the diffusion property: the bytes of a column are shifted so they are all positioned on different columns.
Combined with MC, then a one byte modification will have an effect to the whole state after several rounds: this is the .
This operation shifts the rows of the state in the following manner:
The rows are shifted from top to bottom respectively by an offset of 0, 1, 2 or 3 columns to the left. Bytes that overflow on the left are put back to the right of the row.
The inverse is almost the same: the rows are shifted to the right instead by the same offsets and exceeding bytes are put back to the left.
Small exercise: to what extent would be the impact on the security of AES if no shifting were present?
Substitution Box
Last, but not least, the SB design criterias is to bring the confusion property to make correlation between a plaintext and a ciphertext as small as possible.
The precedent operations shuffle the plaintext in such a way that any modification of a byte has an impact to the whole state after several rounds. Though, this is not enough as those operations are linear: it means that the ciphertext could be expressed as linear equations from the plaintext and the master key. From a known couple plaintext/ciphertext it would be easy to solve the system and find the key.
The substitution box is the operation that breaks the linearity: each byte of the state is replaced by another following the table below.
If 3b is the input, its output is on row 30 and column 0b and is the byte e2.
Let sbox the name of this table, then for any bytes b1 and b2, we have
which is the desired property.
Though, this is not enough and the design of the sbox is made to include a sufficient algebraic complexity.
The construction of the sbox table is done in two steps:
An elementis replaced by ( has no inverse and is mapped to );
An affine transformation on the coefficients of :
The table we gave above has been construted with SageMath and applying the two steps:
The inverse of the table is simple to produce: we only need to reverse the match between an input and its output.
Exercise: write the inverse of the substitution box in SageMath using the inverse of the affine transformation.
XOR as a One-Time Pad
XOR(addition modulo 2) can be used as an encryption scheme as follows: The message space is (i.e.: length n bit strings), the key space is and the ciphertext space is also
Encryption:
Decryption:
The correctness of the schemes is easily verifiable. If the encryption produces , then the decryption produces .
In the Python snippet below with use to os module to generate random bits.
As seen above the receiver with access to the same key can recover the message.
Generalized One-Time Pad
Although XOR is commonly used for the OTP, OTP can be made out of more general objects. If fact We can define an OTP if the message and the keys are objects from a set with a group like structure. (see GroupTheorySection #TODO)
The incredible fact that paths within isogeny graphs commute (with the help of torsion points)
Supersingular isogeny graphs are regular Ramanujan graphs
Using paths through these graphs has spawned a whole bunch of protocols
SIKE / BIKE / ...
Hashes
First we will look at the fundementals that allow these protocols to be expected as good candidates for post-quantum
Then we look at these protocols in more detail. Hopefully with SageMath implementations for each
References I plan to use
Introduction by Craig Costello
Mathematics of Isogeny Based Cryptography by Luca De Feo
Prerequisites: in this section we assume the reader is somewhat familiar with elliptic curves and begin by considering morphisms (maps) between elliptic curves.
Isogeny and Ramanujan Graphs
I (Jack) know nothing about this. At all. But it will need to be talked about.
Humans are fascinated with symmetries. The guiding star of theoretical physics is the study of dualities. How much one thing can be said to be another leads to strange and beautiful links between areas of mathematics that appear to be totally distinct.
A cruical piece of building this understanding is how one can map between objects which share structure. When we learn about topology, we are given the fun: "A doughnut is the same as a mug"; a statement which says within topology, we identify objects related by continuous functions.
Elliptic curves are beautiful mathematical objects. The fact that a geometric comes hand-in-hand with a algebraic group law is, to me, incredible. The study of isogenies is the study of maps (morphisms) between elliptic curves which preserves the origin. This condition is enough to preserve the group scheme of the elliptic curve.
In short, isogenies allow us to map between curves preserving their geometric properties (as projective varieties) and algebraic properties (the group associated with point addition).
Isogenies of Elliptic Curves
Definition: We say an isogeny between elliptic curves defined over a field is a surjective morphism of curves which includes a group homomorphism
References
Starting vertex (Bröker's algorithm).
Isogeny Volcanos: Sutherland might be a good source .
Supersingular isogeny graphs
Size, everything is defined over GF(p^2). (*as long as the degree divides (p+1)^2 or (p-1)^2).
Random walks are probably the best motivation to define Ramanujanness, and are directly applicable to cryptography. A (perhaps too large) source is Hoory-Linial-Wigderson.
Motivation
Breaking a hash function (insert story)
The birthday paradox
*insert story / introduction about why it's called a paradox + use*
Birthday version
Question 1
What is the probability that 1 person has the same birthday as you?
Solution
Let be the event that someone has the same birthday as you and be the complementary event
The events are mutually exclusive =>
Let be the events that person does not have your birthday
Then
Reminder: if are independent events
Question 2
What is the probability that 2 out of people in a room share the same birthday?
Suppose the birthdays are distributed independently and uniformly
Solution
Let be the event that 2 people have the same birthday, let be the complementary event (no 2 people have the same birthday)
Event 1 = Person 1 is born =>
Event 2 = Person 2 is born on a different day than Person 1 =>
General case
Question 1
Instead of days we have
Question 2
Instead of days we have
Code examples
An useful approximation
From the Taylor approximation we know for
Apply for each event:
If we want to solve for knowing we take the =>
Finding a collision
Let be a hash function with
Let's denote
Algorithm
1. Choose random distinct messages in
2. Compute for
3. Look for If not found go to step 1
Example:
Consider the following hash function:
We make the following function to find the hashes:
We use it as follows:
Eliminating Storage Requirements with Pollard's Rho
While the above algorithm works to find a hash collision in time , it also requires storing hash values. As such, it represents a classic time-space tradeoff over the naive approach, which involves randomly selecting pairs of inputs until they hash to the same value. While the naive approach does not require any additional storage, it does have runtime .
However, there is a better approach combining the best of both worlds: constant storage requirements and runtime. This approach is based on Pollard's Rho algorithm, which is better-known for its application to solving discrete logarithms. The core insight behind the algorithm is that by the Birthday Paradox, we expect to encounter a hash collision after trying random inputs. However, it is possible to detect whether a collision has occurred without needing to store all of the inputs and hashes if the inputs are chosen in a clever way.
This is done by choosing the next input based on the hash of the previous input, according to the following sequence:
Where is our hash function and is a "sufficiently random" function which takes a hash value and produces a new. We define the composition of the functions to be.
By the Birthday Paradox, we expect that the sequence will have a collision (where for two distinct values ) after values. But once this occurs, then the sequence will begin to cycle, because .
Therefore, we can detect that a collision has occurred by using standard cycle-detection algorithms, such as !
And finally, we can locate the first place in the sequence where the collision occurred, which will let us determine what the colliding inputs to the hash function are. This is done by determining how many iterations apart the colliding inputs are, and then stepping together one iteration at a time until the collision occurs.
For Floyd's tortoise and hare, this is done by noting that when we found our collision after iterations, we were comparing . And because the sequence is cyclic, if the first colliding input is , then it collides with. So we define the new sequence , and step through the and sequences together until we find our collision!
This is implemented in the following code snippet.
Finally, there is a third algorithm for finding hash collisions in time, namely the based on Distinguished Points. While it does have additional storage requirements over Pollard's Rho, the main advantage of this algorithm is that it parallelizes extremely well, achieving runtime when run on processors.
Resources
- wiki entry
- wiki entry
- vsauce2 video
Introduction / overview
Authors: Zademn
Reviewed by:
Introduction
Another desired propriety of our cryptographic protocols is data / message integrity. This propriety assures that during a data transfer the data has not been modified.
Suppose Alice has a new favourite game and wants to send it to Bob. How can Bob be sure that the file he receives is the same as the one Alice intended to send? One would say to run the game and see. But what if the game is a malware? What if there are changes that are undetectable to the human eye?
# we construct the matrix
# (we use the finite field F constructed in the previous page)
M = Matrix.circulant([x, x + 1, 1, 1])
M
# [ x x + 1 1 1]
# [ 1 x x + 1 1]
# [ 1 1 x x + 1]
# [x + 1 1 1 x]
# We multiply a column
col1 = vector([F.random_element() for i in range(4)])
col1
# (x^6 + x + 1, x^7 + x^4 + x^2, x^6 + x^4 + x^3 + x^2, x^7 + x^6 + x^4 + x^3 + x^2)
col2 = M*col1
col2
# (x^7 + x^5 + 1, x^6 + x^3, x^4, x^7 + x^5 + x^3 + x^2 + x)
N = M^-1
N
# [x^3 + x^2 + x x^3 + x + 1 x^3 + x^2 + 1 x^3 + 1]
# [ x^3 + 1 x^3 + x^2 + x x^3 + x + 1 x^3 + x^2 + 1]
# [x^3 + x^2 + 1 x^3 + 1 x^3 + x^2 + x x^3 + x + 1]
# [ x^3 + x + 1 x^3 + x^2 + 1 x^3 + 1 x^3 + x^2 + x]
# hexadecimal representation
for row in N:
print([F_to_hex(a) for a in row])
# ['e', 'b', 'd', '9']
# ['9', 'e', 'b', 'd']
# ['d', '9', 'e', 'b']
# ['b', 'd', '9', 'e']
col3 = N*col2
col3 == col1
# True
def construct_sbox():
mat = Matrix.circulant(vector(GF(2), [1,0,0,0,1,1,1,1]))
sbox = []
for a in range(256):
# convert a byte value to field element
b = sum(((a >> i) & 1)*x^i for i in range(8))
# first step: map to inverse
if b != 0:
b = b^-1
# second step:
# affine transformation using a vector space over GF(2)
b = mat*vector(b) + vector(GF(2), [1, 1, 0, 0, 0, 1, 1, 0])
# convert the vector as an integer in [0, 255]
sbox.append(sum(ZZ(b[i]) << i for i in range(8)))
return sbox
sbox = construct_sbox()
for i in range(16):
print([f'{a:02x}' for a in sbox[16*i : 16*(i + 1)]])
# ['63', '7c', '77', '7b', 'f2', '6b', '6f', 'c5', '30', '01', '67', '2b', 'fe', 'd7', 'ab', '76']
# ['ca', '82', 'c9', '7d', 'fa', '59', '47', 'f0', 'ad', 'd4', 'a2', 'af', '9c', 'a4', '72', 'c0']
# ['b7', 'fd', '93', '26', '36', '3f', 'f7', 'cc', '34', 'a5', 'e5', 'f1', '71', 'd8', '31', '15']
# ['04', 'c7', '23', 'c3', '18', '96', '05', '9a', '07', '12', '80', 'e2', 'eb', '27', 'b2', '75']
# ['09', '83', '2c', '1a', '1b', '6e', '5a', 'a0', '52', '3b', 'd6', 'b3', '29', 'e3', '2f', '84']
# ['53', 'd1', '00', 'ed', '20', 'fc', 'b1', '5b', '6a', 'cb', 'be', '39', '4a', '4c', '58', 'cf']
# ['d0', 'ef', 'aa', 'fb', '43', '4d', '33', '85', '45', 'f9', '02', '7f', '50', '3c', '9f', 'a8']
# ['51', 'a3', '40', '8f', '92', '9d', '38', 'f5', 'bc', 'b6', 'da', '21', '10', 'ff', 'f3', 'd2']
# ['cd', '0c', '13', 'ec', '5f', '97', '44', '17', 'c4', 'a7', '7e', '3d', '64', '5d', '19', '73']
# ['60', '81', '4f', 'dc', '22', '2a', '90', '88', '46', 'ee', 'b8', '14', 'de', '5e', '0b', 'db']
# ['e0', '32', '3a', '0a', '49', '06', '24', '5c', 'c2', 'd3', 'ac', '62', '91', '95', 'e4', '79']
# ['e7', 'c8', '37', '6d', '8d', 'd5', '4e', 'a9', '6c', '56', 'f4', 'ea', '65', '7a', 'ae', '08']
# ['ba', '78', '25', '2e', '1c', 'a6', 'b4', 'c6', 'e8', 'dd', '74', '1f', '4b', 'bd', '8b', '8a']
# ['70', '3e', 'b5', '66', '48', '03', 'f6', '0e', '61', '35', '57', 'b9', '86', 'c1', '1d', '9e']
# ['e1', 'f8', '98', '11', '69', 'd9', '8e', '94', '9b', '1e', '87', 'e9', 'ce', '55', '28', 'df']
# ['8c', 'a1', '89', '0d', 'bf', 'e6', '42', '68', '41', '99', '2d', '0f', 'b0', '54', 'bb', '16']
import hashlib
import random
from Crypto.Util.number import long_to_bytes, bytes_to_long
def small_hash(m, hash_bits):
'''
Arguments
m: bytes -- input
hash_bits: int -- number of bits of the hash
Returns:
{bytes} - hash of the message of dimension `hash_bits`
'''
assert hash_bits > 0, "no negative number of bits"
mask = (1 << hash_bits) - 1 # Mask of bits
t = hashlib.sha256(m).digest() # the hash in bytes
t = bytes_to_long(t)
t = t & mask # get the last 12 bits
return long_to_bytes(t)
def small_hash_colision(M_bits, T_bits):
'''
Arguments
M_bits: int -- dimension of the message space
T_bits: int -- dimension of the hash space
Returns:
{(bytes, bytes, bytes)} -- message1, message2, hash
or
{(b'', b'', b'')} -- if no collision found
'''
N = 1<<T_bits
print('Hash size: ', N)
# This is `s`
num_samples = 1 * isqrt(N)
num_samples += num_samples//5 + 1 # num_samples = 1.2 * isqrt(N) + 1
print(f'Making a list of {num_samples} hashes')
print(f'Probability of finding a collision is {same_birthday(num_samples, N)}')
m_list = []
t_list = []
# Make a list of hashes
for i in range(num_samples):
m = random.getrandbits(M_bits) # Get random message
#m = random.randint(0, M_bits-1)
m = long_to_bytes(m)
t = small_hash(m, T_bits) # Hash it
if m not in m_list:
m_list.append(m)
t_list.append(t)
# Check for collisionn
for i in range(len(t_list)):
for j in range(i+1, len(t_list)):
if t_list[i] == t_list[j]:
print('Collision found!')
return m_list[i], m_list[j], t_list[i]
else:
print('Collision not found :(')
return b"", b"", b""
M_bits = 30
T_bits = 20
m1, m2, t = small_hash_colision(M_bits, T_bits)
print(m1, m2, t)
print(small_hash(m1, T_bits) == small_hash(m2, T_bits))
# Hash size: 1048576
# Making a list of 1229 hashes
# Probability of finding a collision is 0.513213460854798
# Collision found!
# b'!\xafB\xc5' b'4F\xb6w' b'\x01y\xf7'
# True
# TODO:
# have the two hash functions used in this chapter be the same
from Crypto.Hash import SHA256
from Crypto.Util.number import bytes_to_long, long_to_bytes
from tqdm.autonotebook import tqdm
# bits in hash output
n = 30
# H
def my_hash(x):
x = bytes(x, 'ascii')
h = SHA256.new()
h.update(x)
y = h.digest()
y = bytes_to_long(y)
y = y % (1<<n)
y = int(y)
return y
# g
def get_message(r):
x = "Crypto{" + str(r) + "}"
return x
# f
def f(r):
return my_hash(get_message(r))
"""
initialization
This routine will find a hash collision in sqrt time with constant space.
"""
seed = 0
x0 = get_message(seed)
x = x0
y = f(x)
"""
detect collision
using Floyd / tortoise and hare cycle finding algorithm
expected number of iterations is ~ sqrt(pi/2) * 2^(n/2),
we run for up to 4 * 2^(n/2) iterations
"""
for i in tqdm(range(4 << (n//2))):
if f(x) == f(y):
break
x = f(x)
y = f(y)
y = f(y)
"""
locate collision
"""
x = x0
y = f(y)
for j in tqdm(range(i)):
if f(x) == f(y):
break
x = f(x)
y = f(y)
m1 = get_message(x)
m2 = get_message(y)
assert my_hash(m1) == f(x)
assert my_hash(m2) == f(y)
print("[+] seeds for messages: {}, {}".format(x, y))
print("[+] messages: {}, {}".format(m1, m2))
print("[+] collided hashes of messages: {}, {}".format(my_hash(m1), my_hash(m2)))
# 31% 40391/131072 [00:03<00:08, 10666.20it/s]
# 30% 12032/40391 [00:00<00:02, 13112.15it/s]
#
# [+] seeds for messages: 404842900, 254017312
# [+] messages: Crypto{404842900}, Crypto{254017312}
# [+] collided hashes of messages: 1022927209, 1022927209
Hashes are efficient algorithms to check if two files are the same based on the data they contain. The slightest change (a single bit) would change the hash completely.
On the internet, when you download, files you often see a number near the download button called the hash of that file. If you download that file, recalculate the hash locally and obtain the same hash you can be sure that the data you downloaded is the intended one.
Another use for hashes is storing passwords. We don't want to store plaintext passwords because in case of a breach the attacker will know our password. If we hash them he will have to reverse the hash (or find a collision) to use our password. Luckily the hashes are very hard to reverse and collision resistant by definition and construction.
Note that hashes need a secure channel for communication. Alice must have a secure way to send her hash to Bob. If Eve intercepts Alice's message and hash she can impersonate Alice by changing the file, computing the hash and sending them to Bob. Hashes do not provide authenticity.
Definitions and Formalism
Definition - Hash
A hash is an efficient deterministic function that takes an arbitrary length input and produces a fixed length output (digest, hash). Let H:M⟶T be a function where
M = message space
T = digest space
Desired proprieties
Deterministic
Fast to compute
Small changes change the hash completely
Preimage, second preimage and collision resistance (Explained below)
How to use a hash:
Suppose you want to check if Alice and Bob have the same version of some file (File integrity)
They compute H(a),H(b)
They check if H(a)=H(b)
Figure 1.
Proprieties
Preimage Image Resistance
Second Preimage resistance
Resistant to collisions
1. Preimage Resistance
The hash function must be a one way function. Given t∈T find m∈M s.t H(m)=t
Intuition
It should be unfeasible to reverse a hash function (O(2l) time where l is the number of output bits)
This propriety prevents an attacker to find the original message from a hash
2. Second Preimage Resistance
Given m it should be hard to find m′=m with H(m′)=H(m)
Attack game
An adversary A is given a message m and outputs a message m′=m.
A wins the game if he finds H(m)=H(m′)
His advantage is Pr[A finds a second preimage] where Pr(⋅)is a probability
Figure 2. Security game - second preimage resistance
In practice a hash function with l bits output should need 2l queries before one can find a second preimage
This propriety prevents an attacker to substitute a message with another and get the same hash
3. Hash Collisions
Intuition
A hash collision happens when we have two different messages that have the same hash
Why do we care about hash collisions?
Since hashes are used to fastly verify a message integrity if two messages have the same hash then we can replace one with another => We can play with data
Now, we want to hash big files and big messages so ∣M∣>>∣T∣ => It would appear that hash collisions are possible
Natural collisions are normal to happen and we consider them improbable if T is big enough (SHA256⇒T={0,1}256)
Yet, we don't want hash collisions to be computable
We don't want an attacker to be able to craft collisions or find collisions given a message
Let's throw some definitions
Attack game
An adversary A outputs two messages m0=m1
A wins the game if he finds H(m0)=H(m1)
His advantage is Pr[Adversary finds a collision]
Figure 3. Security game - Collision resistance
Security
A hash function H is collision resistant if for all efficient and explicit adversaries the advantage is negligible
Intuition
We know hash collisions exist (therefore an efficient adversary must exist) and that is easy to prove therefore we request an explicit algorithm that finds these collisions
This propriety makes it difficult for an attacker to find 2 input values with the same hash
Difference from 2nd preimage
There is a fundamental difference in how hard it is to break collision resistance and second-preimage resistance.
Breaking collision-resistance is like inviting more people into the room until the room contains 2 people with the same birthday.
Breaking second-preimage resistance is like inviting more people into the room until the room contains another person with your birthday.
One of these fundamentally takes longer than the other
Implications
Lemma 1
Assuming a function H is preimage resistant for every element of the range of H is a weaker assumption than assuming it is either collision resistant or second preimage resistant.