예제 #1
0
파일: lll.py 프로젝트: Se-P3t/lattice_study
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
예제 #2
0
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
예제 #3
0
def test_enum_gram_coherence():
    """
        Test if the enumeration algorithm is consistent with the Gram matrices
        The vectors returned by the enumeration should be the same wether a
        lattice is given by its basis or by its Gram matrix
    """

    dimensions = ((3, 3), (10, 10), (20, 20), (25, 25))

    for m, n in dimensions:
        for int_type in int_types:
            A = make_integer_matrix(m, n, int_type=int_type)
            LLL.reduction(A)
            G = tools.compute_gram(A)
            for float_type in float_types:
                M_A = GSO.Mat(copy(A), float_type=float_type, gram=False)
                M_G = GSO.Mat(copy(G), float_type=float_type, gram=True)

                M_A.update_gso()
                M_G.update_gso()

                enum_obj_a = Enumeration(M_A, nr_solutions=min(m, 5))
                shortest_vectors_a = enum_obj_a.enumerate(
                    0, M_A.d, M_A.get_r(0, 0), 0)

                enum_obj_g = Enumeration(M_G, nr_solutions=min(m, 5))
                shortest_vectors_g = enum_obj_g.enumerate(
                    0, M_G.d, M_G.get_r(0, 0), 0)

                for i in range(len(shortest_vectors_a)):
                    assert shortest_vectors_a[i] == shortest_vectors_g[i]
예제 #4
0
def load_svp_challenge(d, seed=0):
    """
    Load SVP Challenge matrix in dimension `d` and ``seed``

    :param d: dimension
    :param seed: random seed

    """
    filename = os.path.join("data", "svp-challenge", "%03d-%d.txt" % (d, seed))

    if os.path.isfile(filename) is False:
        import requests

        logging.debug("Did not find '{filename}', downloading ...".format(
            filename=filename))
        r = requests.post(
            "https://www.latticechallenge.org/svp-challenge/generator.php",
            data={
                "dimension": d,
                "seed": seed,
                "sent": "True"
            },
        )
        logging.debug("%s %s" % (r.status_code, r.reason))
        fn = open(filename, "w")
        fn.write(r.text)
        fn.close()

    A = IntegerMatrix.from_file(filename)
    LLL.reduction(A)
    return A
예제 #5
0
파일: bkz.py 프로젝트: MatthiasMi/fpylll
    def __init__(self, A):
        """Construct a new instance of the BKZ algorithm.

        :param A: an integer matrix, a GSO object or an LLL object

        """
        if isinstance(A, GSO.Mat):
            L = None
            M = A
            A = M.B
        elif isinstance(A, LLL.Reduction):
            L = A
            M = L.M
            A = M.B
        elif isinstance(A, IntegerMatrix):
            L = None
            M = None
            A = A
        else:
            raise TypeError("Matrix must be IntegerMatrix but got type '%s'" %
                            type(A))

        if M is None and L is None:
            # run LLL first, but only if a matrix was passed
            LLL.reduction(A)

        self.A = A
        if M is None:
            self.M = GSO.Mat(A, flags=GSO.ROW_EXPO)
        else:
            self.M = M
        if L is None:
            self.lll_obj = LLL.Reduction(self.M, flags=LLL.DEFAULT)
        else:
            self.lll_obj = L
예제 #6
0
def test_enum_enum():
    for int_type in int_types:
        A = make_integer_matrix(20, 20, int_type=int_type)
        LLL.reduction(A)
        for float_type in float_types:
            M = GSO.Mat(copy(A), float_type=float_type)
            M.update_gso()
            enum_obj = Enumeration(M)
            enum_obj.enumerate(0, M.d, M.get_r(0, 0), 0)
예제 #7
0
def insert_in_IntegerMatrix(A, v):
    n = A.nrows
    AA = IntegerMatrix(n + 1, n, int_type="long")
    for j in xrange(n):
        AA[0, j] = v[j]
        for i in xrange(n):
            AA[i + 1, j] = A[i, j]
    LLL.reduction(AA)
    for j in xrange(n):
        for i in xrange(n):
            A[i, j] = AA[i + 1, j]
    del AA
예제 #8
0
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())
예제 #9
0
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 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
예제 #11
0
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
예제 #12
0
def test_gso_io():
    for m, n in dimensions:
        if m <= 2 or n <= 2:
            continue

        A = make_integer_matrix(m, n)
        v = list(A[0])
        LLL.reduction(A)

        for float_type in float_types:
            M = GSO.Mat(copy(A), float_type=float_type)
            M.update_gso()
            w = M.babai(v)
            v_ = IntegerMatrix.from_iterable(1, m, w) * A
            v_ = list(v_[0])
            assert v == v_
예제 #13
0
def ntru_plain_hybrid_basis(A, g, q, nsamples):
    """
		Construct ntru basis for the MitM hybrid
	"""
    n = A.ncols
    ell = n - g

    B = IntegerMatrix(nsamples + ell, nsamples + ell)

    for i in range(ell):
        B[i, i] = 1
        for j in range(nsamples):
            B[i, j + ell] = A[i, j]
    for i in range(nsamples):
        B[i + ell, i + ell] = q

    # print('B:')
    # print(B)

    Al = B.submatrix(0, ell, ell, ell + nsamples)
    Ag = A.submatrix(ell, 0, nsamples, nsamples)

    B = LLL.reduction(B)

    return B, Al, Ag
예제 #14
0
    def __init__(self, A, preprocessing_levels=1, preprocessing_cutoff=45):
        """
        Create a new BKZ Simulation object.

        :param A: An integer matrix, a GSO object or a list of squared Gram-Schmidt norms.
        :param preprocessing_levels: how many levels of preprocessing to simulate (slow!)

        .. note :: Our internal representation is log2 norms of Gram-Schmidt vectors (not squared).

        """
        if isinstance(A, GSO.Mat):
            A.update_gso()
            r = A.r()
            self.r = [log(r_, 2) / 2.0 for r_ in r]
        elif isinstance(A, LLL.Reduction):
            A.M.update_gso()
            r = A.M.r()
            self.r = [log(r_, 2) / 2.0 for r_ in r]
        elif isinstance(A, IntegerMatrix):
            M = GSO.Mat(LLL.reduction(A))
            M.update_gso()
            r = M.r()
            self.r = [log(r_, 2) / 2.0 for r_ in r]
        else:
            try:
                self.r = [log(r_, 2) / 2.0 for r_ in A]
            except TypeError:
                raise TypeError("Unsupported type '%s'" % type(A))
        self.preprocessing_levels = preprocessing_levels
        self.preprocessing_cutoff = preprocessing_cutoff
예제 #15
0
def primal_lattice_basis(A, c, q, m=None):
    """
    Construct primal lattice basis for LWE challenge
    ``(A,c)`` defined modulo ``q``.

    :param A: LWE matrix
    :param c: LWE vector
    :param q: integer modulus
    :param m: number of samples to use (``None`` means all)

    """
    if m is None:
        m = A.nrows
    elif m > A.nrows:
        raise ValueError("Only m=%d samples available." % A.nrows)
    n = A.ncols

    B = IntegerMatrix(m + n + 1, m + 1)
    for i in range(m):
        for j in range(n):
            B[j, i] = A[i, j]
        B[i + n, i] = q
        B[-1, i] = c[i]
    B[-1, -1] = 1

    B = LLL.reduction(B)
    assert (B[:n] == IntegerMatrix(n, m + 1))
    B = B[n:]

    return B
예제 #16
0
def sample_matrix(d, lattice_type="qary", seed=None):
    """
    Sample a matrix in dimension `d`.

    :param d: lattice dimension
    :param lattice_type: see module level documentation
    :param seed: optional random seed
    :returns: LLL-reduced integer matrix

    .. note :: This function seeds the FPLLL RNG, i.e. it is deterministic.

    """

    if seed is None:
        FPLLL.set_random_seed(d)
    else:
        FPLLL.set_random_seed(seed)

    if lattice_type == "qary":
        A = IntegerMatrix.random(d, "qary", bits=30, k=d // 2, int_type="long")
    elif lattice_type == "qary-lv":
        A = IntegerMatrix.random(d, "qary", bits=10 * d, k=d // 2)
    else:
        raise ValueError("Lattice type '%s' not supported." % lattice_type)

    A = LLL.reduction(A)
    return A
예제 #17
0
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"
예제 #18
0
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()
예제 #19
0
def test_callback_enum(d=40):

    FPLLL.set_random_seed(0x1337)
    A = LLL.reduction(IntegerMatrix.random(100, "qary", k=50, q=7681))
    M = GSO.Mat(A)
    M.update_gso()

    # we are not imposing a constraint
    enum_obj = Enumeration(M)
    solutions = enum_obj.enumerate(0, d, 0.99*M.get_r(0, 0), 0)
    max_dist, sol = solutions[0]
    assert(A.multiply_left(sol)[0] != 2)

    # now we do
    def callback(new_sol_coord):
        if A.multiply_left(new_sol_coord)[0] == 2:
            return True
        else:
            return False

    enum_obj = Enumeration(M, callbackf=callback)
    solutions = enum_obj.enumerate(0, d, 0.99*M.get_r(0, 0), 0)
    max_dist, sol = solutions[0]

    assert(A.multiply_left(sol)[0] == 2)
예제 #20
0
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})
예제 #21
0
 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))
예제 #22
0
def test_svp_too_large():
    from fpylll.config import max_enum_dim
    m = max_enum_dim + 1
    n = max_enum_dim + 1
    A = make_integer_matrix(m, n)
    A = LLL.reduction(A)
    M = GSO.Mat(A)
    M.update_gso()
    with pytest.raises(NotImplementedError):
        SVP.shortest_vector(A)
예제 #23
0
파일: test_gso.py 프로젝트: thedrow/fpylll
def test_gso_update_gso():
    for m, n in dimensions:
        A = make_integer_matrix(m, n)
        LLL.reduction(A)

        r00 = []
        re00 = []
        g00 = []
        for float_type in float_types:
            M = GSO.Mat(copy(A), float_type=float_type)
            M.update_gso()
            if (m, n) == (0, 0):
                continue
            r00.append(M.get_r(0, 0))
            re00.append(M.get_r_exp(0, 0)[0])
            g00.append(M.get_gram(0, 0))

        for i in range(1, len(r00)):
            abs(r00[0]/r00[i] - 1.0) < 0.0001
            abs(re00[0]/re00[i] - 1.0) < 0.0001
            abs(g00[0]/g00[i] - 1.0) < 0.0001
예제 #24
0
def test_gso_update_gso():
    for m, n in dimensions:
        A = make_integer_matrix(m, n)
        LLL.reduction(A)

        r00 = []
        re00 = []
        g00 = []
        for float_type in float_types:
            M = GSO.Mat(copy(A), float_type=float_type)
            M.update_gso()
            if (m, n) == (0, 0):
                continue
            r00.append(M.get_r(0, 0))
            re00.append(M.get_r_exp(0, 0)[0])
            g00.append(M.get_gram(0, 0))

        for i in range(1, len(r00)):
            assert abs(r00[0]/r00[i] - 1.0) < 0.0001
            assert abs(re00[0]/re00[i] - 1.0) < 0.0001
            assert abs(g00[0]/g00[i] - 1.0) < 0.0001
예제 #25
0
 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))
예제 #26
0
def test_bkz_postprocessing():
    A = IntegerMatrix.random(20, "qary", bits=20, k=10, int_type="long")
    LLL.reduction(A)

    bkz = BKZ(A)
    bkz.M.update_gso()
    tracer = BKZTreeTracer(bkz)

    solution = (2, 2, 0, 3, 4, 5, 7)

    v = A.multiply_left(solution, 3)
    bkz.svp_postprocessing(3, len(solution), solution, tracer)
    w = tuple(A[3])
    assert v == w

    solution = (2, 1, 0, 3, 4, 5, 7)

    v = A.multiply_left(solution, 3)
    bkz.svp_postprocessing(3, len(solution), solution, tracer)
    w = tuple(A[3])
    assert v == w
예제 #27
0
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)
예제 #28
0
def test_svp():
    for m, n in dimensions:
        A = make_integer_matrix(m, n)
        A = LLL.reduction(A)
        M = GSO.Mat(A)
        M.update_gso()
        E = Enumeration(M)
        _, v1 = E.enumerate(0, M.d, M.get_r(0, 0), 0)[0]
        v1 = A.multiply_left(v1)
        nv1 = sum([v_**2 for v_ in v1])

        v0 = SVP.shortest_vector(A)
        nv0 = sum([v_**2 for v_ in v0])

        assert nv0 == nv1
예제 #29
0
def test_gso_update_gso():
    EPSILON = 0.0001

    for int_type in int_types:
        for m, n in dimensions:
            A = make_integer_matrix(m, n, int_type=int_type)
            LLL.reduction(A)

            r00 = []
            re00 = []
            g00 = []
            for float_type in float_types:
                M = GSO.Mat(copy(A), float_type=float_type)
                M.update_gso()
                if (m, n) == (0, 0):
                    continue
                r00.append(M.get_r(0, 0))
                re00.append(M.get_r_exp(0, 0)[0])
                g00.append(M.get_gram(0, 0))

            for i in range(1, len(r00)):
                assert r00[0] == pytest.approx(r00[i], rel=EPSILON)
                assert re00[0] == pytest.approx(re00[i], rel=EPSILON)
                assert g00[0] == pytest.approx(g00[i], rel=EPSILON)
예제 #30
0
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
예제 #31
0
def test_cvp():
    for m, n in dimensions:
        A = make_integer_matrix(m, n)
        A = LLL.reduction(A)
        M = GSO.Mat(A)
        M.update_gso()
        t = list(make_integer_matrix(n, n)[0])
        v0 = CVP.closest_vector(A, t)

        E = Enumeration(M)
        v1, _ = E.enumerate(0, A.nrows, 2, 40, M.from_canonical(t))
        v1 = IntegerMatrix.from_iterable(1, A.nrows, map(lambda x: int(round(x)), v1))
        v1 = tuple((v1*A)[0])

        assert v0 == v1
예제 #32
0
def test_cvp():
    for m, n in dimensions:
        A = make_integer_matrix(m, n)
        A = LLL.reduction(A)
        M = GSO.Mat(A)
        M.update_gso()
        t = list(make_integer_matrix(n, n)[0])
        v0 = CVP.closest_vector(A, t)

        E = Enumeration(M)
        v1, _ = E.enumerate(0, A.nrows, 2, 40, M.from_canonical(t))[0]
        v1 = IntegerMatrix.from_iterable(1, A.nrows,
                                         map(lambda x: int(round(x)), v1))
        v1 = tuple((v1 * A)[0])

        assert v0 == v1
예제 #33
0
 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))
예제 #34
0
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