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 solve_hnp(samples): d = len(samples) q = order B = IntegerMatrix(d + 2, d + 2) for i in range(d): t, u, v = samples[i] scale = q / v B[i, i] = q * scale B[d, i] = t * scale B[d + 1, i] = u * scale B[d, d] = 1 B[d + 1, d + 1] = q M = GSO.Mat(B) L_red = LLL.Reduction(M) bkzparam = BKZ.Param(block_size=20) B_red = BKZ.Reduction(M, L_red, bkzparam) B_red() if B[1, d + 1] > 0: x = -1 * B[1, d] else: x = B[1, d] if x < 0: x += q private_value = 834818473318008049647448379209460658614088501345180055220225408308906924726 print x == private_value priv = ec.derive_private_key(x, pub.curve, OSSL) original = ec.derive_private_key(private_value, pub.curve, OSSL) return priv, original
def test_bkz_gram_bkz_coherence(): """ Test if BKZ is coherent if it is given a matrix A or its associated Gram matrix A*A^T We should have Gram(BKZ_basis(A)) = BKZ_Gram(Gram(A)). """ for m, n in dimensions: if m < 2 or n < 2: continue for float_type in float_types: A = make_integer_matrix(m, n) G = tools.compute_gram(A) GSO_A = GSO.Mat(A, float_type=float_type) GSO_G = GSO.Mat(G, float_type=float_type, gram=True) lll_obj_a = LLL.Reduction(GSO_A) lll_obj_g = LLL.Reduction(GSO_G) param = BKZ.Param(block_size=min(m, 40), strategies=BKZ.DEFAULT_STRATEGY) bkz_a = BKZ.Reduction(GSO_A, lll_obj_a, param) bkz_g = BKZ.Reduction(GSO_G, lll_obj_g, param) bkz_a() bkz_g() G_updated = tools.compute_gram(A) for i in range(m): for j in range(i + 1): assert G_updated[i, j] == G[i, j]
def reduce_lattice(self, lattice, block_size): if block_size is None: self.log("Start LLL.") return LLL.reduction(lattice) else: self.log("Start BKZ-{}.".format(block_size)) return BKZ.reduction(lattice, BKZ.Param(block_size=block_size, strategies=BKZ.DEFAULT_STRATEGY, auto_abort=True))
def test_bkz_init(): for m, n in dimensions: A = make_integer_matrix(m, n) for float_type in float_types: M = GSO.Mat(copy(A), float_type=float_type) lll_obj = LLL.Reduction(M) param = BKZ.Param(block_size=3, strategies=BKZ.DEFAULT_STRATEGY) bkz = BKZ.Reduction(M, lll_obj, param) del bkz
def reduce_lattice(self, lattice, block_size): """Reduce the lattice, either using *LLL* if `block_size` is `None` or *BKZ* with the given `block_size`.""" if block_size is None: self.log("Start LLL.") return LLL.reduction(lattice) else: self.log("Start BKZ-{}.".format(block_size)) return BKZ.reduction( lattice, BKZ.Param(block_size=block_size, strategies=BKZ.DEFAULT_STRATEGY, auto_abort=True))
def test_linear_pruning(): A = IntegerMatrix.random(25, "qary", k=15, q=127) block_size = 10 preprocessing = 3 strategies = [Strategy(i) for i in range(5)] for b in range(5, block_size + 1): strategies.append( Strategy(b, [preprocessing], [Pruning.LinearPruning(b, 2)])) param = BKZ.Param(block_size=block_size, strategies=strategies) BKZ.reduction(A, param)
def __call__(cls, M, predicate, block_size, invalidate_cache=lambda: None, max_loops=8, threads=1, **kwds): bkz = BKZ2(M) if block_size > STRATEGIES_MAX_DIM: warnings.warn( "reducing block size to {max}".format(max=STRATEGIES_MAX_DIM)) block_size = STRATEGIES_MAX_DIM FPLLL.set_threads(threads) params = BKZ.EasyParam(block_size=block_size, **kwds) auto_abort = BKZ.AutoAbort(M, M.d) tracer = BKZTreeTracer(bkz, root_label="bkz_enum", start_clocks=True) found, ntests, solution = False, 0, None for tour in range(max_loops): bkz.tour(params) if auto_abort.test_abort(): break invalidate_cache() with tracer.context("check"): for i, v in enumerate(bkz.M.B): ntests += 1 if predicate(v, standard_basis=True): found = True solution = tuple([int(v_) for v_ in v]) break if found: break FPLLL.set_threads(1) tracer.exit() b0, b0e = bkz.M.get_r_exp(0, 0) return USVPPredSolverResults( success=found, solution=solution, ntests=ntests, b0=b0**(0.5) * 2**(b0e / 2.0), cputime=tracer.trace.data["cputime"], walltime=tracer.trace.data["walltime"], data=tracer.trace, )
def test_simple_bkz_reduction(block_size=10): for n in dimensions: set_random_seed(n) A = make_integer_matrix(n) LLL.reduction(A) B = copy(A) BKZ.reduction(B, BKZ.Param(block_size=block_size)) C = copy(A) SimpleBKZ(C)(block_size=block_size) assert abs(C[0].norm() - B[0].norm()) < 0.1 assert abs(C[0].norm() < A[0].norm())
def test_simple_bkz_reduction(block_size=10): for n in dimensions: FPLLL.set_random_seed(n) A = make_integer_matrix(n) LLL.reduction(A) B = copy(A) BKZ.reduction(B, BKZ.Param(block_size=block_size)) C = copy(A) SimpleBKZ(C)(block_size=block_size) assert abs(C[0].norm() - B[0].norm()) < 0.1 assert abs(C[0].norm() < A[0].norm())
def findPrivateKey_HNP(M, curve, pubkey_point, block_size=25): Mred = BKZ.reduction(M, BKZ.Param(block_size=block_size)) for i in range(Mred.nrows): row = Mred[i] guess = row[-2] % curve.q if guess == 0: continue Q = curve.single_mul(guess, curve.base) if Q[0] == pubkey_point[0]: if Q[1] == pubkey_point[1]: return guess else: return curve.q - guess return -1
def test_bkz_bkz(): for m, n in dimensions: if m < 2 or n < 2: continue A = make_integer_matrix(m, n) b00 = [] for float_type in float_types: B = copy(A) M = GSO.Mat(B, float_type=float_type) lll_obj = LLL.Reduction(M) param = BKZ.Param(block_size=min(m, 40), strategies="default.json") bkz = BKZ.Reduction(M, lll_obj, param) bkz() b00.append(B[0, 0]) for i in range(1, len(b00)): assert b00[0] == b00[i]
def full_sieve_kernel(arg0, params=None, seed=None): # Pool.map only supports a single parameter if params is None and seed is None: n, params, seed = arg0 else: n = arg0 pump_params = pop_prefixed_params("pump", params) workout_params = pop_prefixed_params("workout", params) verbose = params.pop("verbose") load_matrix = params.pop("load_matrix") pre_bkz = params.pop("pre_bkz") trace = params.pop("trace") reserved_n = n params = params.new(reserved_n=reserved_n, otf_lift=False) if load_matrix is None: A, bkz = load_svpchallenge_and_randomize(n, s=0, seed=seed) if verbose: print("Loaded challenge dim %d" % n) if pre_bkz is not None: par = BKZ_FPYLLL.Param(pre_bkz, strategies=BKZ_FPYLLL.DEFAULT_STRATEGY, max_loops=1) bkz(par) else: A, _ = load_matrix_file(load_matrix, doLLL=False, high_prec=False) if verbose: print("Loaded file '%s'" % load_matrix) g6k = Siever(A, params, seed=seed) if trace: tracer = SieveTreeTracer(g6k, root_label=("full-sieve", n), start_clocks=True) else: tracer = dummy_tracer # Actually runs a workout with very large decrements, so that the basis is kind-of reduced # for the final full-sieve workout(g6k, tracer, 0, n, dim4free_min=0, dim4free_dec=15, pump_params=pump_params, verbose=verbose, **workout_params) g6k.output_bench() tracer.exit() if hasattr(tracer, "trace"): return tracer.trace else: return None
def __call__(self, params, min_row=0, max_row=-1): """Run the BKZ algorithm with parameters `param`. :param params: BKZ parameters :param min_row: start processing in this row :param max_row: stop processing in this row (exclusive) """ tracer = BKZTreeTracer(self, verbosity=params.flags & BKZ.VERBOSE, start_clocks=True) if params.flags & BKZ.AUTO_ABORT: auto_abort = BKZ.AutoAbort(self.M, self.A.nrows) cputime_start = time.clock() with tracer.context("lll"): self.lll_obj() i = 0 while True: with tracer.context("tour", i): clean = self.tour(params, min_row, max_row, tracer) i += 1 if clean or params.block_size >= self.A.nrows: break if (params.flags & BKZ.AUTO_ABORT) and auto_abort.test_abort(): break if (params.flags & BKZ.MAX_LOOPS) and i >= params.max_loops: break if (params.flags & BKZ.MAX_TIME) and time.clock() - cputime_start >= params.max_time: break tracer.exit() self.trace = tracer.trace return clean
def main(n=150, block_size=60, float_type="d", logq=40, verbose=False, seed=0xdeadbeef): print "= n: %3d, β: %2d, bits: %3d, float_type: %s, seed: 0x%08x =" % ( n, block_size, logq, float_type, seed) print set_random_seed(seed) A = IntegerMatrix.random(n, "qary", k=n // 2, bits=logq) A = LLL.reduction(A) params = BKZ.Param(block_size=block_size, max_loops=4, strategies=BKZ.DEFAULT_STRATEGY, flags=BKZ.MAX_LOOPS | BKZ.VERBOSE) bkz = BKZReduction(GSO.Mat(copy.copy(A), float_type=float_type)) bkz(params) print bkz.trace bkz2 = BKZ2(GSO.Mat(copy.copy(A), float_type=float_type)) bkz2(params) print bkz2.trace if verbose: print print bkz.trace.report()
def svp_improve_trial(filename, bs): A, _ = pickle.load(open(filename, 'rb')) n = A.nrows bkz = BKZReduction(A) BKZ_START = time() bkz.lll_obj() r = [bkz.M.get_r(i, i) for i in range(n)] print "*********************************************************" print "# Run with BS = %d" % bs print "# [ File", filename, "]", "before BKZ", print_basis_stats(bkz.M, n) gh = gaussian_heuristic(r) llbs = [] for lbs in range(30, bs - 10, 2) + [bs]: llbs.append(lbs) params = fplll_bkz.Param(block_size=lbs, max_loops=1, min_success_probability=.01) bkz(params=params) bkz.lll_obj() print "# progressive block_sizes = ", llbs r = [bkz.M.get_r(i, i) for i in range(n)] BKZ_TIME = time() - BKZ_START print "# [ File", filename, "]", "after BKZ", print ("BKZ-[%d .. %d] ... \t\t "%(30, bs)), print_basis_stats(bkz.M, n) print ("# [BKZ] TIME = %.2f"%BKZ_TIME) success = enum_trial(bkz, BKZ_TIME, r[0]*.99) print pickle.dump((A, success), open(filename, 'wb')) return success
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 tour(self, params, min_row=0, max_row=-1, tracer=dummy_tracer): if isinstance(params, int): params = BKZ.Param(block_size=params, **self.kwds) return self.base.tour(self, params, min_row=min_row, max_row=max_row, tracer=tracer)
def test_bkz_call(block_size=10): params = fplll_bkz.Param(block_size=block_size, flags=fplll_bkz.VERBOSE|fplll_bkz.GH_BND) for cls in (BKZ, BKZ2): for n in dimensions: set_random_seed(n) A = make_integer_matrix(n) B = copy(A) cls(B)(params=params)
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 preprocess( r, preproc_block_size, strategies, costs, max_loops=1, bkz_simulate=bkz_simulate_fplll, ): """ Simulate preprocessing algorithm. :param r: squared Gram-Schmidt norms :param block_size: preprocessing block size :param strategies: strategies computed so far to establish recursive preprocessing :param costs: enumeration cost per dimension :param max_loops: number of loops to run during preprocessing (FPyLLL uses 1) :returns: new basis shape and preprocessing cost """ d = len(r) for _ in range(max_loops): for preproc_block_size_ in _block_sizes(preproc_block_size, strategies): r = bkz_simulate( r, BKZ.EasyParam(preproc_block_size_, strategies=strategies, max_loops=1), )[0] r = bkz_simulate( r, BKZ.EasyParam(preproc_block_size, strategies=strategies, max_loops=1), )[0] # we first run LLL cost = lll_cost(d) # And then roughly d x preprocessing, recursive calls are included in total cost for kappa in range(d - 3): cost += (max_loops * costs[min(d - kappa, preproc_block_size)]["total cost"]) return r, cost
def svp_reduction_mpi_trial_old(self, As, kappa, block_size, bs, queue, filename): verbose = 0 # setup gso n = As.nrows M = GSO.Mat(As, float_type=TYPE) bkz_sub = BKZ2_SUB(M) bkz_sub.M.update_gso() # sanity check if (bs <= 4): #queue.put(As) #queue.put(False) #norm = bkz_sub.M.get_r(kappa, kappa) #queue.put(norm) return # do lll bkz_sub.lll_obj(kappa, kappa, kappa + block_size) # preprocessing BKZ_START = time() bkz_sub.M.update_gso() for lbs in range(30, bs, 2) + [bs]: params = fplll_bkz.Param(block_size=lbs, max_loops=10, min_success_probability=.5, flags=BKZ.BOUNDED_LLL) # bounded LLL is important bkz_sub (params, kappa, kappa + block_size) bkz_sub.lll_obj (kappa, kappa, kappa + block_size) bkz_sub.M.update_gso() BKZ_TIME = time() - BKZ_START if (verbose): #print "# BKZ-%d, proc %s, time %.2f" %(bs, os.getpid(), BKZ_TIME) ENUM_START = time() r = bkz_sub.M.get_r(kappa, kappa) success, length, prune_time, enum_time, estimate_cost = self.svp_reduction_mpi_trial_enum (bkz_sub, BKZ_TIME, r*.99, kappa, block_size) if (verbose): ENUM_TIME = time() - ENUM_START print "# [rank %d] BKZ-%d trial: Tbkz %.1f, Tsvp %.1f, (prune %.1f, enum %.1f, est. %.1f), norm %d" %(rank, bs, BKZ_TIME, ENUM_TIME, prune_time, enum_time, estimate_cost, length) bkz_sub.M.update_gso() norm = bkz_sub.M.get_r(kappa, kappa) """ queue.put(success) queue.put(norm) mat = [[0 for _ in range(As.ncols)] for _ in range(block_size)] As[kappa:kappa+block_size].to_matrix(mat) for i in range(block_size): queue.put(mat[i]) """ pickle.dump((As, norm, success), open(filename, 'wb')) del bkz_sub del M return
def svp_kernel(arg0, params=None, seed=None): # Pool.map only supports a single parameter if params is None and seed is None: n, params, seed = arg0 else: n = arg0 params = copy.copy(params) challenge_seed = params.pop("challenge_seed") alg = params.pop("svp/alg") workout_params = pop_prefixed_params("workout/", params) pump_params = pop_prefixed_params("pump/", params) goal_r0 = 1.001 * load_svpchallenge_norm(n, s=challenge_seed) A, bkz = load_svpchallenge_and_randomize(n, s=challenge_seed, seed=seed) g6k = Siever(A, params, seed=seed) tracer = SieveTreeTracer(g6k, root_label=("svp-exact", n), start_clocks=True) if alg == "enum": assert len(workout_params) + len(pump_params) == 0 bkz_params = fplll_bkz.Param( block_size=n, max_loops=1, strategies=fplll_bkz.DEFAULT_STRATEGY, flags=fplll_bkz.GH_BND, ) svp_enum(bkz, bkz_params, goal_r0) flast = 0 elif alg == "duc18": assert len(workout_params) + len(pump_params) == 0 flast = ducas18(g6k, tracer, goal=goal_r0) elif alg == "workout": flast = workout(g6k, tracer, 0, n, goal_r0=goal_r0, pump_params=pump_params, **workout_params) else: raise ValueError("Unrecognized algorithm for SVP") r0 = bkz.M.get_r(0, 0) if alg == "enum" else g6k.M.get_r(0, 0) if r0 > goal_r0: raise ValueError("Did not reach the goal") if 1.002 * r0 < goal_r0: raise ValueError( "Found a vector shorter than the goal for n=%d s=%d." % (n, challenge_seed)) tracer.exit() stat = tracer.trace stat.data["flast"] = flast return stat
def reduce_lattice(self, lattice, block_size): if block_size is None: self.log("Start LLL.") return LLL.reduction(lattice) else: if self.sieve: #self.log("Start sieving(BKZ-{}).".format(block_size)) #g6k = Siever(lattice) #tracer = SieveTreeTracer(g6k, root_label=("bkz", block_size), start_clocks=True) #for _ in range(3): # BKZ_Sieve(g6k, tracer, block_size) return lattice else: self.log("Start BKZ-{}.".format(block_size)) return BKZ.reduction( lattice, BKZ.Param(block_size=block_size, strategies=BKZ.DEFAULT_STRATEGY, auto_abort=True))
def __call__(cls, M, predicate, block_size, invalidate_cache=lambda: None, threads=1, max_loops=8, **kwds): params = SieverParams(threads=threads) g6k = Siever(M, params) tracer = SieveTreeTracer(g6k, root_label="bkz-sieve", start_clocks=True) for b in range(20, block_size + 1, 10): pump_n_jump_bkz_tour(g6k, tracer, b, pump_params={"down_sieve": True}) auto_abort = BKZ.AutoAbort(M, M.d) found, ntests, solution = False, 0, None for tour in range(max_loops): pump_n_jump_bkz_tour(g6k, tracer, block_size, pump_params={"down_sieve": True}) invalidate_cache() if auto_abort.test_abort(): break with tracer.context("check"): for i, v in enumerate(M.B): ntests += 1 if predicate(v, standard_basis=True): solution = tuple([int(v_) for v_ in v]) found = True break if found: break tracer.exit() b0, b0e = M.get_r_exp(0, 0) return USVPPredSolverResults( success=found, ntests=ntests, solution=solution, b0=b0**(0.5) * 2**(b0e / 2.0), cputime=tracer.trace.data["cputime"], walltime=tracer.trace.data["walltime"], data=tracer.trace, )
def estimate(cls, M, squared_target_norm, target_prob=None): """ :param M: either a GSO object or a tuple containing the ln of the squared volume and the dimension :param squared_target_norm: the squared norm of the embedded target vector. :returns: cost in CPU cycles, None """ cost, data = usvp_pred_bkz_enum_solve.estimate(M, squared_target_norm) if cost: return cost, data if target_prob is None: target_prob = cls.DEFAULT_TARGET_PROB try: (log_vol, d) = M log_vol = log_vol / log(2.0) except TypeError: try: M.update_gso() except AttributeError: M = GSO.Mat(M) M.update_gso() d = M.d log_vol = M.get_log_det(0, d) / log(2.0) preproc_cost = 8 * float(d**3) preproc_d = max(d - 20, 2) for i in range(d): d_ = min(preproc_d, d - i) if d_ > 30: preproc_cost += 8 * float( 2**(0.1839 * d_ * log(d_, 2) - 0.995 * d_ + 16.25)) nf = round(log_vol * (1 / d)) log_vol -= d * nf # handle rounding errors squared_target_norm /= 2**nf r = [ 1.0219**(2 * (d - 2 * i - 1)) * 2**(log_vol * (1 / d)) for i in range(d) ] from fpylll.tools.bkz_simulator import simulate r, _ = simulate(r, BKZ.EasyParam(preproc_d)) (cost, prob), _ = cls.pruning_coefficients(squared_target_norm, r, preproc_cost, target_prob=target_prob) return int(round(cost * 64)), None
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 run_timing_test(n, block_size=60, bits=30, ncores=8, min_success_probability=0.5, max_loops=4): A = IntegerMatrix.random(n, "qary", k=n // 2, bits=bits) default_strategies = load_strategies_json(BKZ.DEFAULT_STRATEGY) param = BKZ.Param(block_size, strategies=default_strategies, min_success_probability=min_success_probability, max_loops=max_loops, flags=BKZ.VERBOSE | BKZ.MAX_LOOPS) random.seed(1) bkz = ParallelBKZ(copy(A), ncores=ncores) t = time.time() bkz(param) t = time.time() - t trace_p = bkz.trace print "Parallel(%d): %.2fs" % (ncores, t) random.seed(1) param = BKZ.Param(block_size, strategies=default_strategies, min_success_probability=min_success_probability, max_loops=max_loops, flags=BKZ.VERBOSE | BKZ.MAX_LOOPS) t = time.time() bkz = BKZ2(copy(A)) bkz(param) trace_s = bkz.trace t = time.time() - t print " Sequential: %.2fs" % (t, ) return trace_p, trace_s
def load_prebkz(n, s=0, blocksize=40): """ """ filename = "qarychallenge/prebkz-%02d-dim-%03d-seed-%02d.txt" % (blocksize, n, s) if not os.path.isdir("qarychallenge"): os.mkdir("qarychallenge") if os.path.isfile(filename) is False: set_random_seed(s) A = IntegerMatrix.random(n, "qary", q=2**30, k=n // 2) print "Did not find '{filename}'. Creating and reducing".format( filename=filename) print "created, ", sys.stdout.flush() A = LLL.reduction(A) print "LLLed, ", sys.stdout.flush() if A.nrows >= 160: float_type = "long double" elif A.nrows >= 200: float_type = "dd" else: float_type = "double" M = GSO.Mat(A, float_type=float_type, flags=GSO.ROW_EXPO) bkz = BKZReduction(M) for b in range(10, blocksize + 1): print "\r created, LLLed, BKZed %d" % b, sys.stdout.flush() par = fplll_bkz.Param(b, strategies=fplll_bkz.DEFAULT_STRATEGY, max_loops=1, flags=fplll_bkz.MAX_LOOPS) bkz(par) print fn = open(filename, "w") fn.write(str(A)) fn.close() return load_matrix_file(filename, randomize=False)
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