def main_cleanbkz_mpi_master(filename, bs, cores): try: with open(filename, "rb") as f: mat = pickle.load(f) #print "len(mat)", len(mat) #if (len(mat) > 1): # mat = mat[0] if isinstance(mat, IntegerMatrix): Ainput = mat else: Ainput = IntegerMatrix.from_matrix(mat) except: Ainput = IntegerMatrix.from_file(filename) Ainput_M = GSO.Mat(Ainput, float_type='double') Ainput_M.update_gso() r = [Ainput_M.get_r(i, i) for i in range(0, Ainput.nrows)] L_Ainput_M = LLL.Reduction(Ainput_M) L_Ainput_M() print r A = IntegerMatrix.from_matrix(L_Ainput_M.M.B, int_type="long") cleanbkz_mpi = CLEANBKZ_MPI(A, cores) #cleanbkz_mpi = BKZ2(A) cleanbkz_mpi.lll_obj() cleanbkz_mpi.M.update_gso() r = [ log(cleanbkz_mpi.M.get_r(i, i)) for i in range(0, cleanbkz_mpi.A.nrows) ] print "# starting r " print r params = BKZ.Param( block_size=bs, max_loops=5000, min_success_probability=.01, flags=BKZ.BOUNDED_LLL, #|BKZ.DUMP_GSO, dump_gso_filename="gso_output.file", strategies="default.json") cleanbkz_mpi(params=params, min_row=0) #print "# done. found sv", cleanbkz_mpi.M.B[0] # done send last end signal for i in range(1, size): comm.send(1, i, tag=999) # *** changed to send cleanbkz_mpi.M.update_gso() r2 = [ log(cleanbkz_mpi.M.get_r(i, i)) for i in range(0, cleanbkz_mpi.A.nrows) ] print cleanbkz_mpi.A[0] print "# ending r" print r2 return
def main_pruning(filename, bs, cores): try: with open(filename, "rb") as f: mat = pickle.load(f) #print "len(mat)", len(mat) #if (len(mat) > 1): # mat = mat[0] if isinstance(mat, IntegerMatrix): Ainput = mat else: Ainput = IntegerMatrix.from_matrix(mat) except: Ainput = IntegerMatrix.from_file(filename) Ainput_M = GSO.Mat(Ainput, float_type='double') Ainput_M.update_gso() r = [Ainput_M.get_r(i, i) for i in range(0, Ainput.nrows)] L_Ainput_M = LLL.Reduction(Ainput_M) L_Ainput_M() #print r A = IntegerMatrix.from_matrix(L_Ainput_M.M.B, int_type="long") M = GSO.Mat(A, float_type="double") bkzobj = BKZ2(M) bkzobj.M.update_gso() block_size = bs r = [M.get_r(i, i) for i in range(0, block_size)] radius = r[0] * 0.99 preproc_cost = 5000**(rank + 1) pr0 = Pruning.run(radius, NPS[block_size] * preproc_cost, [r], 0.1, metric="probability", float_type="double", flags=Pruning.GRADIENT | Pruning.NELDER_MEAD) print pr0.coefficients """ pruning = prune(radius, NPS[block_size] * preproc_cost, [r], 0.01, metric="probability", float_type="double", flags=Pruning.GRADIENT|Pruning.NELDER_MEAD) cost = sum(pruning.detailed_cost) / NPS[block_size] print "# [rank %d] cost %.1f, precost %.1f " % (rank, cost, preproc_cost) """ pr0_linear = pr0.LinearPruningParams(block_size, block_size - 2) print pr0_linear.coefficients return
def test5(): from fpylll import CVP, GSO, IntegerMatrix # todo: tests with builtin CVP global DEBUG DEBUG = True n = 15 q = 4201 # n = 31 d = 10 np.random.seed(1337) V1 = [[np.random.randint(q) for _ in range(n)] for _ in range(n - 1)] V2 = [[np.random.randint(q) for _ in range(n)] for _ in range(1000)] v1, v2 = closest_pairs(V1, V2, n, d) print(v1) print('closest to v1:', v2) B = IntegerMatrix.from_matrix(V1) # M = GSO.Mat(B) # M.update_gso() # res = M.babai(V2[0]) res = CVP.closest_vector(B, v2.tolist()) print('asd') print(res)
def load_matrix_file(filepath, randomize=False, seed=None): """ Load matrix from file, LLL reduce (and randomize). :param filepath: Load matrix from this file :param randomize: Randomize the basis :param seed: Seed for randomization :returns: lattice basis and BKZ object """ A = IntegerMatrix.from_file(filepath) A = LLL.reduction(A) A = IntegerMatrix.from_matrix(A, int_type="long") M = GSO.Mat(A, float_type="double", flags=GSO.ROW_EXPO) bkz = BKZReduction(M) if seed is not None: FPLLL.set_random_seed(seed) if randomize: bkz.randomize_block(0, A.nrows, density=A.ncols / 4) LLL.reduction(A) bkz = BKZReduction(A) LLL.reduction(A) bkz.lll_obj() # to initialize bkz.M etc return A, bkz
def babai_nearest_plane(A, w, **kwds): """Return lattice vector close to `v` using Babai's nearest plane algorithm. :param A: **reduced** basis, an instance of `list` or `IntegerMatrix` :param w: a tuple-like object :param int_type: (default: 'mpz') an element of `fpylll.config.int_types` :param float_type: (default: 'mpfr') an element of `fpylll.config.float_types` :param int_gram: See docs of `GSO.MatGSO` :param row_expo: See docs of `GSO.MatGSO` """ int_type = kwds.get('int_type', 'mpz') if isinstance(A, list): A = IntegerMatrix.from_matrix(A, int_type=int_type) elif not isinstance(A, IntegerMatrix): raise TypeError("Matrix `A` type '%s' unknown." % type(A)) float_type = kwds.get('float_type', 'mpfr') flags = GSO.DEFAULT if kwds.get('int_gram', False): flags |= GSO.INT_GRAM elif kwds.get('row_expo', False): flags |= GSO.ROW_EXPO M = GSO.Mat(A, flags=flags, float_type=float_type, update=True) v = M.babai(w, gso=True) return v
def run_BKZ(A, block_size=2, **kwds): u"""run BKZ reduction for a given matrix :param A: Integer matrix, represent in `list` :param int_type: (default: 'mpz') an element of `fpylll.config.int_types` :param block_size: (default: 2) an integer from 1 to ``nrows`` :param delta: (default: 0.99) LLL parameter `0.25 < δ ≤ 1` :param verbose: (default: `False`) print verbose outputs :param float_type: an element of `fpylll.config.float_types` or `None` :param precision: bit precision to use if `float_type` is 'mpfr' For more params, see docs of `fpylll.BKZ.Param` :returns: reduced matrix ``B``, represent in `list` """ int_type = kwds.get('int_type', 'mpz') float_type = kwds.get('float_type', None) precision = kwds.get('precision', 0) kwds['delta'] = kwds.get('delta', 0.99) kwds["strategies"] = kwds.get('strategies', BKZ.DEFAULT_STRATEGY) kwds['flags'] = BKZ.DEFAULT if kwds.get('verbose', False): kwds['flags'] |= BKZ.VERBOSE if kwds.get("auto_abort", False): kwds["flags"] |= BKZ.AUTO_ABORT A = IntegerMatrix.from_matrix(A, int_type=int_type) BKZ.reduction(A, BKZ.Param(block_size=block_size, **kwds), float_type=float_type, precision=precision) B = [[A[i, j] for j in range(A.ncols)] for i in range(A.nrows)] return B
def run_LLL(A, delta=0.99, eta=0.501, **kwds): u"""run LLL reduction for a given matrix :param A: Integer matrix, represent in `list` :param delta: (default: 0.99) LLL parameter `0.25 < δ ≤ 1` :param eta: (default: 0.501) LLL parameter `0 ≤ η < √δ` :param int_type: (default: 'mpz') an element of `fpylll.config.int_types` :param method: one of 'wrapper', 'proved', 'heuristic', 'fast' or `None` :param float_type: an element of `fpylll.config.float_types` or `None` :param precision: bit precision to use if `float_type` is 'mpfr' :param verbose: (default: `False`) print verbose outputs :param use_siegel: (default: `False`) use Siegel's condition instead of Lovász's condition :param early_red: (default: `False`) perform early reduction :returns: reduced matrix ``B``, represent in `list` """ kwds['delta'] = delta kwds['eta'] = eta int_type = kwds.pop('int_type', 'mpz') kwds['flags'] = LLL.DEFAULT if kwds.pop('verbose', False): kwds['flags'] |= LLL.VERBOSE if kwds.pop('use_siegel', False): kwds['flags'] |= LLL.SIEGEL if kwds.pop('early_red', False): kwds['flags'] |= LLL.EARLY_RED A = IntegerMatrix.from_matrix(A, int_type=int_type) LLL.reduction(A, **kwds) B = [[A[i, j] for j in range(A.ncols)] for i in range(A.nrows)] return B
def test_ntru_gsa(n): # read from file filename = 'lwe_n'+str(n)+'.txt' data = open(filename, 'r').readlines() q = int(data[0]) B = eval(",".join([s_.replace('\n','').replace(" ", ", ") for s_ in data[1:n+1]])) B = IntegerMatrix.from_matrix(B) c = eval(data[n+1].replace(" ", ',')) beta, nsamples, prep_rt, GSA = find_beta(n, q, n) print('beta, nsamples:', beta, nsamples) print('GSA predicted:') print(GSA) print('beta, nsamples: ', beta, nsamples) Basis = primal_lattice_basis(B, c, q, nsamples) g6k = Siever(Basis) d = g6k.full_n g6k.lll(0, g6k.full_n) print(g6k.MatGSO) slope = basis_quality(g6k.M)["/"] print("Intial Slope = %.5f\n" % slope) print('GSA input:') print([g6k.M.get_r(i, i) for i in range(d)]) print('d:', d) target_norm = ceil( (2./3)*d + 1) + 1 print("target_norm:", target_norm) # # Preprocessing # if beta < 50: print("Starting a fpylll BKZ-%d tour. " % (beta)) sys.stdout.flush() bkz = BKZReduction(g6k.M) par = fplll_bkz.Param(beta, strategies=fplll_bkz.DEFAULT_STRATEGY, max_loops=1) bkz(par) else: print("Starting a pnjBKZ-%d tour. " % (beta)) pump_n_jump_bkz_tour(g6k, tracer, beta, jump=jump, verbose=verbose, extra_dim4free=extra_dim4free, dim4free_fun=dim4free_fun, goal_r0=target_norm, pump_params=pump_params) #T_BKZ = time.time() - T0_BKZ print('GSA output:') print([g6k.M.get_r(i, i) for i in range(d)]) return 1
def read_ntru_from_file(filename): if not os.path.isfile(filename): raise ValueError ('file ', filename, 'is not found') data = open(filename, "r").readlines() q = int(data[0]) H = eval(",".join([s_.replace('\n','').replace(" ", ", ") for s_ in data[1 :]])) H = IntegerMatrix.from_matrix(H) return H, q
def run_DBKZ(A, block_size=2, verbose=False): """ """ A = IntegerMatrix.from_matrix(A) _ = DBKZ(A)(block_size=block_size) # minimal implementation B = [[A[i, j] for j in range(A.ncols)] for i in range(A.nrows)] return B
def run_BKZ2(A, block_size=2, verbose=False): """ """ flags = BKZ.DEFAULT | BKZ.AUTO_ABORT if verbose: flags |= BKZ.VERBOSE A = IntegerMatrix.from_matrix(A) _ = BKZ2(A)(BKZ.EasyParam(block_size=block_size, flags=flags)) B = [[A[i, j] for j in range(A.ncols)] for i in range(A.nrows)] return B
def run_instance(L, block_size, tours, evec): from fpylll import BKZ, LLL, GSO, IntegerMatrix from fpylll.algorithms.bkz2 import BKZReduction as BKZ2 from sage.all import e A = IntegerMatrix.from_matrix(L) block_size = ZZ(block_size) par = BKZ.Param(block_size=block_size, strategies=BKZ.DEFAULT_STRATEGY, flags=BKZ.VERBOSE) block_size = ZZ(block_size) delta_0 = (block_size / (2 * pi * e) * (pi * block_size)**(1 / block_size))**(1 / (2 * block_size - 1)) n = ZZ(L.nrows()) alpha = delta_0**(-2 * n / (n - 1)) if len(evec) == n - 1: evec = vector(list(evec) + [1]) LLL.reduction(A) M = GSO.Mat(A) M.update_gso() vol = sqrt(prod([RR(M.get_r(i, i)) for i in range(n)])) norms = [ map(lambda x: RR(log(x, 2)), [(alpha**i * delta_0**n * vol**(1 / n))**2 for i in range(n)]) ] def proj(v, i): return v - vector(RR, M.to_canonical(list(M.from_canonical(v, 0, i)))) # norms += [map(lambda x: RR(log(x,2)), # [(stddev*sqrt(n-i))**2 for i in range(n)])] norms += [ map(lambda x: RR(log(x, 2)), [proj(evec, i).norm()**2 for i in range(1, n - 1)]) ] norms += [[log(RR(M.get_r(i, i)), 2) for i in range(n)]] bkz = BKZ2(M) for i in range(tours): bkz.tour(par) norms += [[log(M.get_r(i, i), 2) for i in range(n)]] return A.to_matrix(matrix(ZZ, n, n)), norms
def load_challenge_and_randomize(n): A_pre = IntegerMatrix.from_file("svpchallenge/svpchallengedim%dseed0.txt" % n) LLL.reduction(A_pre) A = IntegerMatrix.from_matrix(A_pre, int_type="long") params = fplll_bkz.Param(block_size=n, max_loops=1, strategies=fplll_bkz.DEFAULT_STRATEGY, flags=fplll_bkz.GH_BND, min_success_probability=.8) bkz = BKZReduction(A) bkz.lll_obj() bkz.randomize_block(0, n, density=n / 4) bkz.lll_obj() return A, bkz
def svpchallenge_test (): dim = 60 A_pre = IntegerMatrix.from_file("svpchallenge/svpchallengedim%dseed0.txt"%dim) print "# input dim: ", dim print "# nrows: ", A_pre.nrows ASVP_START = time() LLL.reduction(A_pre) A = IntegerMatrix.from_matrix(A_pre, int_type="long") bkz = BKZReduction(A) bkz.lll_obj() r = [bkz.M.get_r(i, i) for i in range(dim)] goal = (1.05)**2 * gaussian_heuristic(r) params = fplll_bkz.Param(block_size=20, max_loops=1, min_success_probability=.01) bkz(params=params) print " done BKZ yes"
def test_lll_lll(): for m, n in dimensions: A = make_integer_matrix(m, n) for int_type in int_types: AA = IntegerMatrix.from_matrix(A, int_type=int_type) b00 = [] for float_type in float_types: B = copy(AA) M = GSO.Mat(B, float_type=float_type) lll = LLL.Reduction(M) lll() if (m, n) == (0, 0): continue b00.append(B[0, 0]) for i in range(1, len(b00)): assert b00[0] == b00[i]
def svpchallenge_par3(bs_diff=10, cores=2, start_dim=80, end_dim=80+2, BS_RANDOM_RANGE = 10): for dim in range(start_dim, start_dim+2, 2): A_pre = IntegerMatrix.from_file("svpchallenge/svpchallengedim%dseed0.txt"%dim) print "# input dim: ", dim print "# nrows: ", A_pre.nrows ASVP_START = time() LLL.reduction(A_pre) A = IntegerMatrix.from_matrix(A_pre, int_type="long") bkz = BKZReduction(A) bkz.lll_obj() r = [bkz.M.get_r(i, i) for i in range(dim)] goal = (1.05)**2 * gaussian_heuristic(r) bs_ulim = dim - bs_diff interacting_parrallel_asvp(A, bs_ulim, goal, cores, BS_RANDOM_RANGE) ASVP_TIME = time() - ASVP_START print ("\nSUMMARY", {"input dim": dim, "bs_range": (bs_ulim - BS_RANDOM_RANGE, bs_ulim), "time": ASVP_TIME})
def solve_cvp(A, w, int_type='mpz', method='proved', verbose=False): """fplll closest_vector :param A: **reduced** basis, an instance of `list` or `IntegerMatrix` :param w: a tuple-like object :param int_type: (default: 'mpz') an element of `fpylll.config.int_types` :param method: (default: 'proved') One of "fast" or "proved" :param verbose: (default: `False`) print verbose outputs """ if isinstance(A, list): A = IntegerMatrix.from_matrix(A, int_type=int_type) elif not isinstance(A, IntegerMatrix): raise TypeError("Matrix `A` type '%s' unknown." % type(A)) flags = CVP.VERBOSE if verbose else CVP.DEFAULT v = CVP.closest_vector(A, w, method=method, flags=flags) return v
def load_lwe_challenge(n=40, alpha=0.005): """ Load LWE challenge from file or website. :param n: LWE dimension :param alpha: the *standard deviation* of the secret is alpha*q """ alpha = int(round(alpha * 1000)) start = "lwechallenge" if not os.path.isdir(start): os.mkdir(start) end = "{n:03d}-{alpha:03d}-challenge.txt".format(n=n, alpha=alpha) filename = os.path.join(start, end) if not os.path.isfile(filename): url = ("https://www.latticechallenge.org/lwe_challenge/challenges/" "LWE_{n:d}_{alpha:03d}.txt") url = url.format(n=n, alpha=alpha) r = requests.get(url) m = "Cannot retrieve challenge; server response was: '%s'. \n URL was: %s" % ( r.reason, url) if not r.status_code == 200: raise ValueError(m) fn = open(filename, "w") fn.write(r.text) fn.close() data = open(filename, "r").readlines() n, m, q = map(lambda x: int(x), [data[0], data[1], data[2]]) c_index = 3 if data[3].startswith("[") else 4 A = eval(",".join([s_.replace(" ", ", ") for s_ in data[c_index + 1:]])) A = IntegerMatrix.from_matrix(A) c = tuple(eval(data[c_index].replace(" ", ", "))) return A, c, q
def solve_svp(A, **kwds): """fplll shortest_vector :param A: an instance of `list` or `IntegerMatrix` :param int_type: (default: 'mpz') an element of `fpylll.config.int_types` :param method: (default: 'fast') One of "fast" or "proved" :param pruning: (default: `True`) If ``True`` pruning parameters are computed by this function :param preprocess: (default: `True`) Blocksize used for preprocessing; if ``True`` a block size is picked :param max_aux_solutions: maximum number of additional short-ish solutions to return :param verbose: (default: `False`) print verbose outputs """ int_type = kwds.get('int_type', 'mpz') if isinstance(A, list): A = IntegerMatrix.from_matrix(A, int_type=int_type) elif not isinstance(A, IntegerMatrix): raise TypeError("Matrix `A` type '%s' unknown." % type(A)) kwds['flags'] = SVP.VERBOSE if verbose else SVP.DEFAULT v = SVP.shortest_vector(A, **kwds) return v
def mpi_svpchallenge_par3(bs_diff=10, cores=2, start_dim=80, end_dim=80 + 2, BS_RANDOM_RANGE=10): dim = start_dim A_pre = IntegerMatrix.from_file( "/home/shi/suite/sb_fpylll/bench/svpchallenge/svpchallengedim%dseed0.txt" % dim) if (rank == 0): print "# input dim: ", dim print "# nrows: ", A_pre.nrows ASVP_START = time() LLL.reduction(A_pre) A = IntegerMatrix.from_matrix(A_pre, int_type="long") bkz = BKZReduction(A) bkz.lll_obj() r = [bkz.M.get_r(i, i) for i in range(dim)] goal = (1.05)**2 * gaussian_heuristic(r) bs_ulim = dim - bs_diff mpi_interacting_parrallel_asvp(A, bs_ulim, goal, cores, BS_RANDOM_RANGE) ASVP_TIME = time() - ASVP_START # done send signal comm.send(99, dest=0, tag=0) comm.send(rank, dest=0, tag=1) if (rank == 0): print( "\nSUMMARY", { "input dim": dim, "bs_range": (bs_ulim - BS_RANDOM_RANGE, bs_ulim), "time": ASVP_TIME }) return
def shortest_vector(self, update_reduced_basis=True, algorithm="fplll", *args, **kwds): r""" Return a shortest vector. INPUT: - ``update_reduced_basis`` -- (default: ``True``) set this flag if the found vector should be used to improve the basis - ``algorithm`` -- (default: ``"fplll"``) either ``"fplll"`` or ``"pari"`` - ``*args`` -- passed through to underlying implementation - ``**kwds`` -- passed through to underlying implementation OUTPUT: A shortest non-zero vector for this lattice. EXAMPLES:: sage: from sage.modules.free_module_integer import IntegerLattice sage: A = sage.crypto.gen_lattice(type='random', n=1, m=30, q=2^40, seed=42) sage: L = IntegerLattice(A, lll_reduce=False) sage: min(v.norm().n() for v in L.reduced_basis) 6.03890756700000e10 sage: L.shortest_vector().norm().n() 3.74165738677394 sage: L = IntegerLattice(A, lll_reduce=False) sage: min(v.norm().n() for v in L.reduced_basis) 6.03890756700000e10 sage: L.shortest_vector(algorithm="pari").norm().n() 3.74165738677394 sage: L = IntegerLattice(A, lll_reduce=True) sage: L.shortest_vector(algorithm="pari").norm().n() 3.74165738677394 """ if algorithm == "pari": if self._basis_is_LLL_reduced: B = self.basis_matrix().change_ring(ZZ) qf = self.gram_matrix() else: B = self.reduced_basis.LLL() qf = B * B.transpose() count, length, vectors = qf.__pari__().qfminim() v = vectors.sage().columns()[0] w = v * B elif algorithm == "fplll": from fpylll import IntegerMatrix, SVP L = IntegerMatrix.from_matrix(self.reduced_basis) w = vector(ZZ, SVP.shortest_vector(L, *args, **kwds)) else: raise ValueError("algorithm '{}' unknown".format(algorithm)) if update_reduced_basis: self.update_reduced_basis(w) return w
def silke(A, c, beta, h, m=None, scale=1, float_type="double"): """ :param A: LWE matrix :param c: LWE vector :param beta: BKW block size :param m: number of samples to consider :param scale: scale rhs of lattice by this factor """ from fpylll import BKZ, IntegerMatrix, LLL, GSO from fpylll.algorithms.bkz2 import BKZReduction as BKZ2 if m is None: m = A.nrows() L = dual_instance1(A, scale=scale) L = IntegerMatrix.from_matrix(L) L = LLL.reduction(L, flags=LLL.VERBOSE) M = GSO.Mat(L, float_type=float_type) bkz = BKZ2(M) t = 0.0 param = BKZ.Param(block_size=beta, strategies=BKZ.DEFAULT_STRATEGY, auto_abort=True, max_loops=16, flags=BKZ.VERBOSE | BKZ.AUTO_ABORT | BKZ.MAX_LOOPS) bkz(param) t += bkz.stats.total_time H = copy(L) import pickle pickle.dump(L, open("L-%d-%d.sobj" % (L.nrows, beta), "wb")) E = [] Y = set() V = set() y_i = vector(ZZ, tuple(L[0])) Y.add(tuple(y_i)) E.append(apply_short1(y_i, A, c, scale=scale)[1]) v = L[0].norm() v_ = v / sqrt(L.ncols) v_r = 3.2 * sqrt(L.ncols - A.ncols()) * v_ / scale v_l = sqrt(h) * v_ fmt = u"{\"t\": %5.1fs, \"log(sigma)\": %5.1f, \"log(|y|)\": %5.1f, \"log(E[sigma]):\" %5.1f}" print print fmt % (t, log(abs(E[-1]), 2), log(L[0].norm(), 2), log(sqrt(v_r**2 + v_l**2), 2)) print for i in range(m): t = cputime() M = GSO.Mat(L, float_type=float_type) bkz = BKZ2(M) t = cputime() bkz.randomize_block(0, L.nrows, stats=None, density=3) LLL.reduction(L) y_i = vector(ZZ, tuple(L[0])) l_n = L[0].norm() if L[0].norm() > H[0].norm(): L = copy(H) t = cputime(t) Y.add(tuple(y_i)) V.add(y_i.norm()) E.append(apply_short1(y_i, A, c, scale=scale)[1]) if len(V) >= 2: fmt = u"{\"i\": %4d, \"t\": %5.1fs, \"log(|e_i|)\": %5.1f, \"log(|y_i|)\": %5.1f," fmt += u"\"log(sigma)\": (%5.1f,%5.1f), \"log(|y|)\": (%5.1f,%5.1f), |Y|: %5d}" print fmt % (i + 2, t, log(abs(E[-1]), 2), log( l_n, 2), log_mean(E), log_var(E), log_mean(V), log_var(V), len(Y)) return E
def shortest_vector(self, update_reduced_basis=True, algorithm="fplll", *args, **kwds): r""" Return a shortest vector. INPUT: - ``update_reduced_basis`` -- (default: ``True``) set this flag if the found vector should be used to improve the basis - ``algorithm`` -- (default: ``"fplll"``) either ``"fplll"`` or ``"pari"`` - ``*args`` -- passed through to underlying implementation - ``**kwds`` -- passed through to underlying implementation OUTPUT: A shortest non-zero vector for this lattice. EXAMPLES:: sage: from sage.modules.free_module_integer import IntegerLattice sage: A = sage.crypto.gen_lattice(type='random', n=1, m=30, q=2^40, seed=42) sage: L = IntegerLattice(A, lll_reduce=False) sage: min(v.norm().n() for v in L.reduced_basis) 6.03890756700000e10 sage: L.shortest_vector().norm().n() 3.74165738677394 sage: L = IntegerLattice(A, lll_reduce=False) sage: min(v.norm().n() for v in L.reduced_basis) 6.03890756700000e10 sage: L.shortest_vector(algorithm="pari").norm().n() 3.74165738677394 sage: L = IntegerLattice(A, lll_reduce=True) sage: L.shortest_vector(algorithm="pari").norm().n() 3.74165738677394 """ if algorithm == "pari": if self._basis_is_LLL_reduced: B = self.basis_matrix().change_ring(ZZ) qf = self.gram_matrix() else: B = self.reduced_basis.LLL() qf = B*B.transpose() count, length, vectors = qf._pari_().qfminim() v = vectors.python().columns()[0] w = v*B elif algorithm == "fplll": from fpylll import IntegerMatrix, SVP L = IntegerMatrix.from_matrix(self.reduced_basis) w = vector(ZZ, SVP.shortest_vector(L, *args, **kwds)) else: raise ValueError("algorithm '{}' unknown".format(algorithm)) if update_reduced_basis: self.update_reduced_basis(w) return w
def dim_error_tradeoff(A, c, u, beta, h, k, alpha=None, tau=None, float_type="mpfr", use_lll=True): """ :param A: LWE matrix :param c: LWE vector :param u: Uniform vector :param beta: BKW block size :param h: Hamming weight of secret :param k: LWE dim after tradeoff :param tau: number of new samples to generate :param use_lll: If True, run BKZ only once and then run LLL If False, run BKZ iteratively * secret vector s is used to see the error term of new LWE(-like) samples. """ from fpylll import BKZ, IntegerMatrix, LLL, GSO from fpylll.algorithms.bkz2 import BKZReduction as BKZ2 n = A.ncols() q = A.base_ring().order() K = GF(q, proof=False) if alpha is None: alpha = 8 / q if tau is None: tau = 30 m = A.nrows() / n scale = round(alpha * q * sqrt(m) / sqrt(2 * pi * h)) scale = ZZ(scale) count = 0 A_k = matrix(ZZ, 1, k) c_k = [] u_k = [] length = 0 while count < tau: r = count * m T = A.matrix_from_rows([i + r for i in range(m)]) ct = c[r:r + m] ut = u[r:r + m] T1 = T.matrix_from_columns([i for i in range(n - k)]) L = dual_instance1(T1, scale=scale) L = IntegerMatrix.from_matrix(L) L = LLL.reduction(L) M = GSO.Mat(L, float_type=float_type) bkz = BKZ2(M) param = BKZ.Param(block_size=beta, strategies=BKZ.DEFAULT_STRATEGY, auto_abort=True, max_loops=16, flags=BKZ.AUTO_ABORT | BKZ.MAX_LOOPS) bkz(param) H = copy(L) y = vector(ZZ, tuple(L[0])) length += y.norm() T2 = T.matrix_from_columns([n - k + i for i in range(k)]) A_kt, c_kt, u_kt = apply_short1(y, T2, ct, ut, scale=scale) if r == 0: A_k[0] = A_kt else: A_k = A_k.stack(A_kt) c_k.append(c_kt) u_k.append(u_kt) count += 1 length = float(length / tau) A_k = A_k.change_ring(K) c_k = vector(K, c_k) u_k = vector(K, u_k) B = float(2 + 1 / sqrt(2 * pi)) * (alpha * q) B = B * B * m / (m + n) B = sqrt(B) * length / scale print '(A_k, c_k) is k-dim LWE samples (with secret s[-k:]) / (A_k, u_k) is uniform samples. ' return A_k, c_k, u_k, B
print "Finished !" print_basis_stats(bkz.M, n) return trials START = time() for dim in range(start_dim, 130, 2): for r in range(repeat): A_pre = IntegerMatrix.from_file( "svpchallenge/svpchallengedim%dseed0.txt" % dim) print "---------------------", A_pre.nrows ASVP_START = time() LLL.reduction(A_pre) # bs = int(floor(dim * bs_rat)) A = IntegerMatrix.from_matrix(A_pre, int_type="long") trials = asvp(A, bs, gh_factor=(1.05**2)) ASVP_TIME = time() - ASVP_START print "\n\n Challenge %d Solved" % dim print A[0] print "SUMMARY", { "dim": dim, "bs": bs, "time": ASVP_TIME, "trials": trials }
def silke(A, c, beta, h, m=None, scale=1, float_type="double"): """ :param A: LWE matrix :param c: LWE vector :param beta: BKW block size :param m: number of samples to consider :param scale: scale rhs of lattice by this factor """ from fpylll import BKZ, IntegerMatrix, LLL, GSO from fpylll.algorithms.bkz2 import BKZReduction as BKZ2 if m is None: m = A.nrows() L = dual_instance1(A, scale=scale) L = IntegerMatrix.from_matrix(L) L = LLL.reduction(L, flags=LLL.VERBOSE) M = GSO.Mat(L, float_type=float_type) bkz = BKZ2(M) t = 0.0 param = BKZ.Param(block_size=beta, strategies=BKZ.DEFAULT_STRATEGY, auto_abort=True, max_loops=16, flags=BKZ.VERBOSE|BKZ.AUTO_ABORT|BKZ.MAX_LOOPS) bkz(param) t += bkz.stats.total_time H = copy(L) import pickle pickle.dump(L, open("L-%d-%d.sobj"%(L.nrows, beta), "wb")) E = [] Y = set() V = set() y_i = vector(ZZ, tuple(L[0])) Y.add(tuple(y_i)) E.append(apply_short1(y_i, A, c, scale=scale)[1]) v = L[0].norm() v_ = v/sqrt(L.ncols) v_r = 3.2*sqrt(L.ncols - A.ncols())*v_/scale v_l = sqrt(h)*v_ fmt = u"{\"t\": %5.1fs, \"log(sigma)\": %5.1f, \"log(|y|)\": %5.1f, \"log(E[sigma]):\" %5.1f}" print print fmt%(t, log(abs(E[-1]), 2), log(L[0].norm(), 2), log(sqrt(v_r**2 + v_l**2), 2)) print for i in range(m): t = cputime() M = GSO.Mat(L, float_type=float_type) bkz = BKZ2(M) t = cputime() bkz.randomize_block(0, L.nrows, stats=None, density=3) LLL.reduction(L) y_i = vector(ZZ, tuple(L[0])) l_n = L[0].norm() if L[0].norm() > H[0].norm(): L = copy(H) t = cputime(t) Y.add(tuple(y_i)) V.add(y_i.norm()) E.append(apply_short1(y_i, A, c, scale=scale)[1]) if len(V) >= 2: fmt = u"{\"i\": %4d, \"t\": %5.1fs, \"log(|e_i|)\": %5.1f, \"log(|y_i|)\": %5.1f," fmt += u"\"log(sigma)\": (%5.1f,%5.1f), \"log(|y|)\": (%5.1f,%5.1f), |Y|: %5d}" print fmt%(i+2, t, log(abs(E[-1]), 2), log(l_n, 2), log_mean(E), log_var(E), log_mean(V), log_var(V), len(Y)) return E