Ejemplo n.º 1
0
def test_gso_int_gram_enabled():
    for int_type in int_types:
        for m, n in dimensions:
            A = make_integer_matrix(m, n, int_type=int_type)
            for float_type in float_types:
                M = GSO.Mat(copy(A), float_type=float_type)
                assert M.int_gram_enabled is False
                assert M.transform_enabled is False

                M = GSO.Mat(copy(A), float_type=float_type, flags=GSO.INT_GRAM)
                assert M.int_gram_enabled is True
                assert M.transform_enabled is False

                if m and n:
                    U = IntegerMatrix(m, m, int_type=int_type)
                    M = GSO.Mat(copy(A), U=U, float_type=float_type)
                    assert M.transform_enabled is True
                    assert M.inverse_transform_enabled is False

                    UinvT = IntegerMatrix(m, m, int_type=int_type)
                    M = GSO.Mat(copy(A),
                                U=U,
                                UinvT=UinvT,
                                float_type=float_type)
                    assert M.transform_enabled is True
                    assert M.inverse_transform_enabled is True
Ejemplo n.º 2
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
Ejemplo n.º 3
0
def test_multisol():
    A = make_integer_matrix()
    m = GSO.Mat(A)
    lll_obj = LLL.Reduction(m)
    lll_obj()

    solutions = []
    solutions = Enumeration(m, nr_solutions=200).enumerate(0, 27, 48.5, 0)
    assert len(solutions) == 126 / 2
    for _, sol in solutions:
        sol = IntegerMatrix.from_iterable(1, A.nrows,
                                          map(lambda x: int(round(x)), sol))
        sol = tuple((sol * A)[0])
        dist = sum([x**2 for x in sol])
        assert dist == 48

    solutions = []
    solutions = Enumeration(m, nr_solutions=126 / 2).enumerate(0, 27, 100., 0)
    assert len(solutions) == 126 / 2
    for _, sol in solutions:
        sol = IntegerMatrix.from_iterable(1, A.nrows,
                                          map(lambda x: int(round(x)), sol))
        sol = tuple((sol * A)[0])
        dist = sum([x**2 for x in sol])
        assert dist == 48
Ejemplo n.º 4
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
Ejemplo n.º 5
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
Ejemplo n.º 6
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
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
Ejemplo n.º 8
0
def test_dump_r(nrows=10):
    A = IntegerMatrix(nrows, nrows)
    A.randomize("ntrulike", bits=10, q=1023)
    M = GSO.Mat(A)
    if not have_numpy:
        return

    M.update_gso()
    r = dump_r(M, 0, nrows)

    for i in range(nrows):
        assert abs(M.get_r(i, i) - r[i]) < 0.001
Ejemplo n.º 9
0
def test_dump_r(nrows=10):
    A = IntegerMatrix(nrows, nrows)
    A.randomize("ntrulike", bits=10, q=1023)
    M = GSO.Mat(A)
    if not have_numpy:
        return

    M.update_gso()
    r = dump_r(M, 0, nrows)

    for i in range(nrows):
        assert abs(M.get_r(i, i) - r[i]) < 0.001
Ejemplo n.º 10
0
def test_dump_mu(nrows=10):
    A = IntegerMatrix(nrows, nrows)
    A.randomize("ntrulike", bits=10, q=1023)
    M = GSO.Mat(A)
    if not have_numpy:
        return

    M.update_gso()
    mu = dump_mu(M, 0, nrows)

    for i in range(nrows):
        for j in range(i):
            assert abs(M.get_mu(i, j) - mu[i, j]) < 0.001
Ejemplo n.º 11
0
def test_dump_mu(nrows=10):
    A = IntegerMatrix(nrows, nrows)
    A.randomize("ntrulike", bits=10, q=1023)
    M = GSO.Mat(A)
    if not have_numpy:
        return

    M.update_gso()
    mu = dump_mu(M, 0, nrows)

    for i in range(nrows):
        for j in range(nrows):
            assert abs(M.get_mu(i, j) - mu[i, j]) < 0.001
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
Ejemplo n.º 13
0
def test_dump_r(nrows=10):
    A = IntegerMatrix(nrows, nrows)
    A.randomize("ntrulike", bits=10, q=1023)
    M  = GSO.Mat(A)
    if not have_numpy:
        return

    r = numpy.ndarray(dtype='double', shape=nrows)

    M.update_gso()
    dump_r(r, M, 0, nrows)

    for i in range(nrows):
        assert abs(M.get_r(i, i) - r[i]) < 0.001
Ejemplo n.º 14
0
def test_gso_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)
            del M

            U = IntegerMatrix(m, m)
            M = GSO.Mat(copy(A), U=U, float_type=float_type)
            del M

            UinvT = IntegerMatrix(m, m)
            M = GSO.Mat(copy(A), U=U, UinvT=UinvT, float_type=float_type)
            del M
Ejemplo n.º 15
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
Ejemplo n.º 16
0
def test_dump_mu(nrows=10):
    A = IntegerMatrix(nrows, nrows)
    A.randomize("ntrulike", bits=10, q=1023)
    M  = GSO.Mat(A)
    if not have_numpy:
        return

    mu = numpy.ndarray(dtype='double', shape=(nrows, nrows))

    M.update_gso()
    dump_mu(mu, M, 0, nrows)

    for i in range(nrows):
        for j in range(nrows):
            assert abs(M.get_mu(i, j) - mu[i, j]) < 0.001
Ejemplo n.º 17
0
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
Ejemplo n.º 18
0
def svp_time(seed, params, return_queue=None):
    """Run SVP reduction of AutoBKZ on ``A`` using ``params``.

    :param A: a matrix
    :param params: AutoBKZ parameters
    :param queue: if not ``None``, the result is put on this queue.

    """
    FPLLL.set_random_seed(seed)
    A = IntegerMatrix.random(params.block_size, "qary", bits=30,
                             k=params.block_size//2, int_type="long")

    M = GSO.Mat(A)
    bkz = BKZ2(M)
    tracer = BKZTreeTracer(bkz, start_clocks=True)

    with tracer.context(("tour", 0)):
        bkz.svp_reduction(0, params.block_size, params, tracer)
        bkz.M.update_gso()

    tracer.exit()

    tracer.trace.data["|A_0|"] = A[0].norm()

    if return_queue:
        return_queue.put(tracer.trace)
    else:
        return tracer.trace
Ejemplo n.º 19
0
def svp_time(seed, params, return_queue=None):
    """Run SVP reduction of AutoBKZ on ``A`` using ``params``.

    :param A: a matrix
    :param params: AutoBKZ parameters
    :param queue: if not ``None``, the result is put on this queue.

    """
    FPLLL.set_random_seed(seed)
    FPLLL.set_threads(params["threads"])
    q = 33554393
    k = params.block_size // 2
    A = IntegerMatrix.random(params.block_size,
                             "qary",
                             q=q,
                             k=k,
                             int_type="long")

    M = GSO.Mat(A)
    bkz = BKZ2(M)
    tracer = BKZTreeTracer(bkz, start_clocks=True)

    with tracer.context(("tour", 0)):
        bkz.svp_reduction(0, params.block_size, params, tracer)
        bkz.M.update_gso()

    tracer.exit()

    log_delta = (log(A[0].norm()) - log(q) *
                 (k / float(params.block_size))) / float(params.block_size)
    tracer.trace.data["delta"] = exp(log_delta)
    if return_queue:
        return_queue.put(tracer.trace)
    else:
        return tracer.trace
Ejemplo n.º 20
0
def worker_process(seed, params, queue=None):
    """
    This function is called to collect statistics.

    :param A: basis
    :param params: BKZ parameters
    :param queue: queue used for communication

    """
    FPLLL.set_random_seed(seed)
    A = IntegerMatrix.random(params.block_size, "qary", bits=30, k=params.block_size//2, int_type="long")

    M = GSO.Mat(A)
    bkz = CallbackBKZ(M)  # suppresses initial LLL call
    tracer = BKZTreeTracer(bkz, start_clocks=True)

    with tracer.context(("tour", 0)):
        bkz.svp_reduction(0, params.block_size, params, tracer)
        M.update_gso()

    tracer.exit()
    try:
        # close connection
        params.strategies[params.block_size].connection.send(None)
    except AttributeError:
        pass
    if queue:
        queue.put(tracer.trace)
    else:
        return tracer.trace
Ejemplo n.º 21
0
def IntegerMatrix_to_long(A):
    n = A.nrows
    AA = IntegerMatrix(n, n, int_type="long")
    for i in xrange(n):
        for j in xrange(n):
            AA[i, j] = A[i, j]
    return AA
Ejemplo n.º 22
0
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
Ejemplo n.º 23
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"
Ejemplo n.º 24
0
def worker_process(seed, params, queue=None):
    """
    This function is called to collect statistics.

    :param A: basis
    :param params: BKZ parameters
    :param queue: queue used for communication

    """
    FPLLL.set_random_seed(seed)
    A = IntegerMatrix.random(params.block_size,
                             "qary",
                             bits=30,
                             k=params.block_size // 2,
                             int_type="long")

    M = GSO.Mat(A)
    bkz = CallbackBKZ(M)  # suppresses initial LLL call
    tracer = BKZTreeTracer(bkz, start_clocks=True)

    with tracer.context(("tour", 0)):
        bkz.svp_reduction(0, params.block_size, params, tracer)
        M.update_gso()

    tracer.exit()
    try:
        # close connection
        params.strategies[params.block_size].connection.send(None)
    except AttributeError:
        pass
    if queue:
        queue.put(tracer.trace)
    else:
        return tracer.trace
Ejemplo n.º 25
0
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
Ejemplo n.º 26
0
 def build_cvp_lattice(self, signatures, dim, bounds):
     b = IntegerMatrix(dim + 1, dim + 1)
     for i in range(dim):
         b[i, i] = (2**self.bound_func(i, dim, bounds)) * self.curve.group.n
         b[dim, i] = (2**self.bound_func(i, dim, bounds)) * signatures[i][0]
     b[dim, dim] = 1
     return b
Ejemplo n.º 27
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
Ejemplo n.º 28
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()
Ejemplo n.º 29
0
Archivo: simhash.py Proyecto: obqq/g6k
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)
Ejemplo n.º 30
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)
Ejemplo n.º 31
0
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
Ejemplo n.º 32
0
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
Ejemplo n.º 33
0
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
Ejemplo n.º 34
0
 def copy_to_IntegerMatrix_long(self, A):
     n = A.nrows
     l = A.ncols
     AA = IntegerMatrix(n, l, int_type="long")
     for i in xrange(n):
         for j in xrange(l):
             AA[i, j] = A[i, j]
     return AA
Ejemplo n.º 35
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})
Ejemplo n.º 36
0
def test_multisol():
    A = make_integer_matrix()
    m = GSO.Mat(A)
    lll_obj = LLL.Reduction(m)
    lll_obj()

    solutions = []
    solutions = Enumeration(m, nr_solutions=200).enumerate(0, 27, 48.5, 0)
    assert len(solutions)== 126 / 2
    for sol, _ in solutions:
        sol = IntegerMatrix.from_iterable(1, A.nrows, map(lambda x: int(round(x)), sol))
        sol = tuple((sol*A)[0])
        dist = sum([x**2 for x in sol])
        assert dist==48

    solutions = []
    solutions = Enumeration(m, nr_solutions=126 / 2).enumerate(0, 27, 100., 0)
    assert len(solutions)== 126 / 2
    for sol, _ in solutions:
        sol = IntegerMatrix.from_iterable(1, A.nrows, map(lambda x: int(round(x)), sol))
        sol = tuple((sol*A)[0])
        dist = sum([x**2 for x in sol])
        assert dist==48
Ejemplo n.º 37
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
Ejemplo n.º 38
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_
Ejemplo n.º 39
0
def prepare(n, m):
    A = [IntegerMatrix.random(n, "qary", bits=n, k=n) for _ in range(m)]
    M = [GSO.Mat(a) for a in A]
    L = [LLL.Reduction(m) for m in M]
    [l() for l in L]
    return M
Ejemplo n.º 40
0
def prepare(n):
    A = IntegerMatrix.random(n, "qary", bits=n/2, k=n/2)
    M = GSO.Mat(A)
    L = LLL.Reduction(M)
    L()
    return M
Ejemplo n.º 41
0
def make_integer_matrix(n):
    A = IntegerMatrix.random(n, "uniform", bits=30)
    return A
Ejemplo n.º 42
0
def make_integer_matrix(m, n):
    A = IntegerMatrix(m, n)
    A.randomize("uniform", bits=m+n)
    return A
Ejemplo n.º 43
0
def make_integer_matrix(m, n):
    A = IntegerMatrix(m, n)
    A.randomize(algorithm="ntrulike", bits=30, q=2147483647)
    return A
Ejemplo n.º 44
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
Ejemplo n.º 45
0
def make_integer_matrix(n):
    A = IntegerMatrix.random(n, "ntrulike", bits=30)
    return A
Ejemplo n.º 46
0
    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