Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jvdsn
GitHub Repository: jvdsn/crypto-attacks
Path: blob/master/shared/lattice.py
2587 views
1
import logging
2
3
4
def shortest_vectors(B):
5
"""
6
Computes the shortest non-zero vectors in a lattice.
7
:param B: the basis of the lattice
8
:return: a generator generating the shortest non-zero vectors
9
"""
10
logging.debug(f"Computing shortest vectors in {B.nrows()} x {B.ncols()} matrix...")
11
B = B.LLL()
12
13
for row in B.rows():
14
if not row.is_zero():
15
yield row
16
17
18
# Babai's Nearest Plane Algorithm from "Lecture 3: CVP Algorithm" by Oded Regev.
19
def _closest_vectors_babai(B, t):
20
B = B.LLL()
21
22
for G in B.gram_schmidt():
23
b = t
24
for j in reversed(range(B.nrows())):
25
b -= round((b * G[j]) / (G[j] * G[j])) * B[j]
26
27
yield t - b
28
29
30
def _closest_vectors_embedding(B, t):
31
B_ = B.new_matrix(B.nrows() + 1, B.ncols() + 1)
32
for row in range(B.nrows()):
33
for col in range(B.ncols()):
34
B_[row, col] = B[row, col]
35
36
for col in range(B.ncols()):
37
B_[B.nrows(), col] = t[col]
38
39
B_[B.nrows(), B.ncols()] = 1
40
yield from shortest_vectors(B_)
41
42
43
def closest_vectors(B, t, algorithm="embedding"):
44
"""
45
Computes the closest vectors in a lattice to a target vector.
46
:param B: the basis of the lattice
47
:param t: the target vector
48
:param algorithm: the algorithm to use, can be "babai" or "embedding" (default: "embedding")
49
:return: a generator generating the shortest non-zero vectors
50
"""
51
logging.debug(f"Computing closest vectors in {B.nrows()} x {B.ncols()} matrix...")
52
if algorithm == "babai":
53
yield from _closest_vectors_babai(B, t)
54
elif algorithm == "embedding":
55
yield from _closest_vectors_embedding(B, t)
56
57