Esempio n. 1
0
def random_Dirichletwebpage():
    modulus = randint(1, 9999)
    number = randint(1, modulus - 1)
    while gcd(modulus, number) > 1:
        number = randint(1, modulus - 1)
    return redirect(
        url_for('.render_Dirichletwebpage',
                modulus=str(modulus),
                number=str(number)))
Esempio n. 2
0
def test_karatsuba_multiplication(base_ring, maxdeg1, maxdeg2,
        ref_mul=lambda f, g: f._mul_generic(g), base_ring_random_elt_args=[],
        numtests=10, verbose=False):
    """
    Test univariate karatsuba multiplication against other multiplication algorithms.

    EXAMPLES:

    First check that random tests are reproducible::

        sage: import sage.rings.tests
        sage: sage.rings.tests.test_karatsuba_multiplication(ZZ, 6, 5, verbose=True, seed=42)
        test_karatsuba_multiplication: ring=Univariate Polynomial Ring in x over Integer Ring, threshold=2
          (2*x^6 - x^5 - x^4 - 3*x^3 + 4*x^2 + 4*x + 1)*(4*x^4 + x^3 - 2*x^2 - 20*x + 3)
          (16*x^2)*(x^2 - 41*x + 1)
          (-x + 1)*(x^2 + 2*x + 8)
          (-x^6 - x^4 - 8*x^3 - x^2 - 4*x + 3)*(-x^3 - x^2)
          (2*x^2 + x + 1)*(x^4 - x^3 + 3*x^2 - x)
          (-x^3 + x^2 + x + 1)*(4*x^2 + 76*x - 1)
          (6*x + 1)*(-5*x - 1)
          (-x^3 + 4*x^2 + x)*(-x^5 + 3*x^4 - 2*x + 5)
          (-x^5 + 4*x^4 + x^3 + 21*x^2 + x)*(14*x^3)
          (2*x + 1)*(12*x^3 - 12)

    Test Karatsuba multiplication of polynomials of small degree over some common rings::

        sage: for C in [QQ, ZZ[I], ZZ[I, sqrt(2)], GF(49, 'a'), MatrixSpace(GF(17), 3)]:
        ....:     sage.rings.tests.test_karatsuba_multiplication(C, 10, 10)

    Zero-tests over ``QQbar`` are currently very slow, so we test only very small examples::

        sage.rings.tests.test_karatsuba_multiplication(QQbar, 3, 3, numtests=2)

    Larger degrees (over ``ZZ``, using FLINT)::

        sage: sage.rings.tests.test_karatsuba_multiplication(ZZ, 1000, 1000, ref_mul=lambda f,g: f*g, base_ring_random_elt_args=[1000])

    Some more aggressive tests::

        sage: for C in [QQ, ZZ[I], ZZ[I, sqrt(2)], GF(49, 'a'), MatrixSpace(GF(17), 3)]:
        ....:     sage.rings.tests.test_karatsuba_multiplication(C, 10, 10) # long time
        sage: sage.rings.tests.test_karatsuba_multiplication(ZZ, 10000, 10000, ref_mul=lambda f,g: f*g, base_ring_random_elt_args=[100000])

    """
    from sage.all import randint, PolynomialRing
    threshold = randint(0, min(maxdeg1,maxdeg2))
    R = PolynomialRing(base_ring, 'x')
    if verbose:
        print "test_karatsuba_multiplication: ring={}, threshold={}".format(R, threshold)
    for i in range(numtests):
        f = R.random_element(randint(0, maxdeg1), *base_ring_random_elt_args)
        g = R.random_element(randint(0, maxdeg2), *base_ring_random_elt_args)
        if verbose:
            print "  ({})*({})".format(f, g)
        if ref_mul(f, g) -  f._mul_karatsuba(g, threshold) != 0:
            raise ValueError("Multiplication failed")
    return
Esempio n. 3
0
def test_ae_equivalence(N, verbose=False):
    from timeit import default_timer
    false_negatives = 0
    false_positives = 0
    n_tested = 10
    for i in xrange(0, n_tested):
        # checking if linearly equivalent permutations are identified
        f = random_permutation(N)
        A = rand_linear_permutation(N)
        a = randint(0, 2**N - 1)
        B = rand_linear_permutation(N)
        b = randint(0, 2**N - 1)
        g = [
            oplus(apply_bin_mat(f[apply_bin_mat(oplus(x, a), A)], B), b)
            for x in xrange(0, 2**N)
        ]
        computation_start = default_timer()
        result = affine_equivalence(f, g)
        computation_end = default_timer()
        elapsed = computation_end - computation_start
        if len(result) > 1:
            if not check_affine_equivalence(f, g, result[0], result[1],
                                            result[2], result[3]):
                false_negatives += 1
                if verbose:
                    print("[FAIL] wrong affine permutations")
            else:
                if verbose:
                    print("[success]     AE {:0.4f}".format(elapsed))

        else:
            false_negatives += 1
            if verbose:
                print("[FAIL]     AE {:0.4f}s (nothing found)".format(elapsed))
        # checking if non-affine equivalent functions are identified
        g = random_permutation(N)
        result = affine_equivalence(f, g)
        if len(result) == 0:
            if verbose:
                print("[success] non-AE {:0.4f}s".format(elapsed))
        else:
            if check_affine_equivalence(f, g, result[0], result[1], result[2],
                                        result[3]):
                if verbose:
                    print("[success] act.AE {:0.4f}".format(elapsed))
            else:
                false_positives += 1
                if verbose:
                    print("[FAIL] matrices found for non-LE permutations")
    print(
        "* testing if AE functions are identified correctly (with correct affine permutations)"
    )
    print_result(n_tested - false_negatives, n_tested)
    print("* testing if NON-LE functions are identified correctly")
    print_result(n_tested - false_positives, n_tested)
Esempio n. 4
0
def test_nose(cls=Kyber,
              l=None,
              t=128,
              seed=0xdeadbeef,
              proof=False,
              worst_case=True):
    """
    Test correctness of the Sneeze/Snort gadget for normal form MLWE parameters.

    TESTS::

        sage: test_nose(MiniKyber)
        sage: test_nose(MiniPseudoLima, seed=1, worst_case=False)
        sage: test_nose(MiniKyber, l = Nose.prec(MiniKyber)-1)
        Traceback (most recent call last):
        ...
        AssertionError
        sage: test_nose(MiniPseudoLima, l = Nose.prec(MiniPseudoLima)-1, seed=1, worst_case=False)
        Traceback (most recent call last):
        ...
        AssertionError

    .. note :: An ``AssertionError`` if final key does not match original.

    """
    if seed is not None:
        set_random_seed(seed)

    R, x = PolynomialRing(ZZ, "x").objgen()
    D = BinomialDistribution
    # TODO ce
    n, q, eta, k, f = cls.n, cls.q, cls.eta, cls.k, R(cls.f)
    Rq = PolynomialRing(GF(q), "x")

    if not l:
        l = Nose.prec(cls)
    l = ceil(l)

    for _ in range(t):
        if worst_case:
            a = vector(Rq, k, [[q // 2 + randint(0, 1) for _ in range(n)]
                               for i in range(k)])  # noqa
            s = vector(R, k, [[((-1)**randint(0, 1)) * eta for _ in range(n)]
                              for i in range(k)])
            e = R([((-1)**randint(0, 1)) * eta for _ in range(n)])
        else:
            a = vector(Rq, k,
                       [Rq.random_element(degree=n - 1) for i in range(k)])
            s = vector(R, k, [[D(eta) for _ in range(n)] for i in range(k)])
            e = R([D(eta) for _ in range(n)])
        b = (a * s + e) % f

        bb = Rq(Nose.muladd(cls, a, s, e, l=l))

        assert (b == bb)
Esempio n. 5
0
    def basis_of_simple_closed_curves(self):
        from sage.graphs.digraph import DiGraph
        from sage.all import randint

        n = self._origami.nb_squares()
        C = self.chain_space()
        G = DiGraph(multiedges=True, loops=True, implementation='c_graph')

        for i in xrange(2 * n):
            G.add_edge(self._starts[i], self._ends[i], i)

        waiting = [0]
        gens = []
        reps = [None] * G.num_verts()
        reps[0] = C.zero()

        while waiting:
            x = waiting.pop(randint(0, len(waiting) - 1))
            for v0, v1, e in G.outgoing_edges(x):
                if reps[v1] is not None:
                    gens.append(reps[v0] + C.gen(e) - reps[v1])
                else:
                    reps[v1] = reps[v0] + C.gen(e)
                    waiting.append(v1)

        return gens
Esempio n. 6
0
def find_element_of_order(k,r):
    """
    Description:
    
        Finds a random element of order k in Z_r^*
    
    Input:
    
        k - integer such that r % k == 1
        r - prime
    
    Output:
    
        h - element of order k in Z_r^*
    
    """
    assert r % k == 1
    h = 0
    def order(h,k,p):
        bool = True
        g = h
        for i in range(1,k):
            bool = bool and g != 1
            g = Mod(g * h, p)
        bool = bool and g == 1
        return bool
    while not order(h,k,r): # expected number of iterations is k/euler_phi(k)
        h = power_mod(randint(2, r-1), (r-1)//k, r)
    return h
Esempio n. 7
0
def find_element_of_order(k, r):
    """
    Description:
    
        Finds a random element of order k in Z_r^*
    
    Input:
    
        k - integer such that r % k == 1
        r - prime
    
    Output:
    
        h - element of order k in Z_r^*
    
    """
    assert r % k == 1
    h = 0

    def order(h, k, p):
        bool = True
        g = h
        for i in range(1, k):
            bool = bool and g != 1
            g = Mod(g * h, p)
        bool = bool and g == 1
        return bool

    while not order(h, k,
                    r):  # expected number of iterations is k/euler_phi(k)
        h = power_mod(randint(2, r - 1), (r - 1) // k, r)
    return h
Esempio n. 8
0
def test_fast_multiplier(verbose=False):
    print("testing fast linear mappings")
    all_good = True
    n, m = 8, 4
    for index_L in xrange(0, 10):
        m += 1
        L = rand_linear_function(n, m)
        L_map = FastLinearMapping(L)
        if verbose:
            print "--- ", L_map.input_size(), L_map.output_size()
        for index_x in xrange(0, 8):
            x = randint(1, 2**n - 1)
            y = apply_bin_mat(x, L)
            y_prime = L_map(x)
            if verbose:
                print y, y_prime
            if y != y_prime:
                all_good = False
                break
    if verbose:
        if all_good:
            print("[SUCCESS]")
        else:
            print("[FAIL]")
    return all_good
Esempio n. 9
0
    def basis_of_simple_closed_curves(self):
        from sage.graphs.digraph import DiGraph
        from sage.all import randint

        n = self._origami.nb_squares()
        C = self.chain_space()
        G = DiGraph(multiedges=True,loops=True,implementation='c_graph')

        for i in xrange(2*n):
            G.add_edge(self._starts[i], self._ends[i], i)

        waiting = [0]
        gens = []
        reps = [None] * G.num_verts()
        reps[0] = C.zero()

        while waiting:
            x = waiting.pop(randint(0,len(waiting)-1))
            for v0,v1,e in G.outgoing_edges(x):
                if reps[v1] is not None:
                    gens.append(reps[v0] + C.gen(e) - reps[v1])
                else:
                    reps[v1] = reps[v0] + C.gen(e)
                    waiting.append(v1)

        return gens
Esempio n. 10
0
 def time_search_loop(p):
     y = random_vector(F, n)
     g = random_matrix(F, p, n).rows()
     scalars = [  [ Fstar[randint(0,q-2)] for i in range(p) ]
                      for s in range(100) ]
     before = process_time()
     for m in scalars:
         e = y - sum(m[i]*g[i] for i in range(p))
     return (process_time() - before)/100.
Esempio n. 11
0
def random_url():
    routes = [
            "L/",
            "L/",
            "L/",
            "ModularForm/GL2/Q/holomorphic/",
            "ModularForm/GL2/Q/Maass/",
            "ModularForm/GL2/TotallyReal/",
            "ModularForm/GL2/ImaginaryQuadratic/",
            "EllipticCurve/Q/",
            "EllipticCurve/",
            "Genus2Curve/Q/",
            "HigherGenus/C/Aut/",
            "Variety/Abelian/Fq/",
            "NumberField/",
            "LocalNumberField/",
            "Character/Dirichlet/",
            "ArtinRepresentation/",
            "GaloisGroup/",
            "SatoTateGroup/"
            ]
    if is_beta():
        routes += [
                "ModularForm/GSp/Q/",
                "Belyi/",
                "Motive/Hypergeometric/Q/",
                "Lattice/"
                ]
    route = routes[randint(0,len(routes)-1)]
    if route == "ModularForm/GL2/Q/holomorphic/":
        ind = randint(0,1)
        if ind == 0:
            route += "random"
        else:
            route += "random_space"
    elif route == "Motive/Hypergeometric/Q/":
        ind = randint(0,1)
        if ind == 0:
            route += "random_motive"
        else:
            route += "random_family"
    else:
        route += "random"
    return route
Esempio n. 12
0
def gen_instance(n, q, h, alpha=None, m=None, seed=None, s=None):
    """
    Generate FHE-style LWE instance

    :param n:     dimension
    :param q:     modulus
    :param alpha: noise rate (default: 8/q)
    :param h:     hamming weight of the secret (default: 2/3n)
    :param m:     number of samples (default: n)

    """
    if seed is not None:
        set_random_seed(seed)

    q = next_prime(ceil(q) - 1, proof=False)
    if alpha is None:
        stddev = 3.2
    else:
        stddev = alpha * q / sqrt(2 * pi)

    #RR = parent(alpha*q)
    #stddev = alpha*q/RR(sqrt(2*pi))

    if m is None:
        m = n
    K = GF(q, proof=False)

    while 1:
        A = random_matrix(K, m, n)
        if A.rank() == n:
            break

    if s is not None:
        c = A * s

    else:
        if h is None:
            s = random_vector(ZZ, n, x=-1, y=1)
        else:
            S = [-1, 1]
            s = [S[randint(0, 1)] for i in range(h)]
            s += [0 for _ in range(n - h)]
            shuffle(s)
            s = vector(ZZ, s)
        c = A * s

    D = DiscreteGaussian(stddev)

    for i in range(m):
        c[i] += D()

    u = random_vector(K, m)

    print '(A, c) is n-dim LWE samples (with secret s) / (A, u) is uniform samples'

    return A, c, u, s
 def time_search_loop(p):
     y = random_vector(F, n)
     g = random_matrix(F, p, n).rows()
     scalars = [  [ Fstar[randint(0,q-2)] for i in range(p) ]
                      for s in range(100) ]
     before = time.clock()
     for m in scalars:
         e = y - sum(m[i]*g[i] for i in range(p))
         errs = e.hamming_weight()
     return (time.clock() - before)/100.
Esempio n. 14
0
 def time_search_loop(p):
     y = random_vector(F, n)
     g = random_matrix(F, p, n).rows()
     scalars = [[Fstar[randint(0, q - 2)] for i in range(p)]
                for s in range(100)]
     before = time.clock()
     for m in scalars:
         e = y - sum(m[i] * g[i] for i in range(p))
         errs = e.hamming_weight()
     return (time.clock() - before) / 100.
Esempio n. 15
0
def test_conrey(nranges=[(20, 100), (200, 1000), (500, 500000)]):
    for n, r in nranges:
        for i in range(n):
            q = randint(1, r)
            print("n, r, i, q = {}, {}, {}, {}".format(n, r, i, q))
            G = DirichletGroup_conrey(q)
            inv = G.invariants()
            cinv = tuple([Mod(g, q).multiplicative_order() for g in G.gens()])
            try:
                assert prod(inv) == G.order()
                assert q <= 2 or G.zeta_order() == inv[0]
                assert cinv == inv
            except:
                print('group error')
                return q, inv, G
            if q > 2:
                m = 0
                while gcd(m, q) != 1:
                    m = randint(1, q)
                chi = G[m]
                n = randint(1, q)
                try:
                    assert chi.multiplicative_order() == Mod(
                        m, q).multiplicative_order()
                    if gcd(n, q) != 1:
                        try:
                            assert chi.logvalue(n) == -1
                        except:
                            print('non unit value error')
                            return chi, n, r
                    elif q < 10 ^ 6:
                        try:
                            ref = chi.sage_character()(n).n().real()
                            new = N(chi(n).real)
                            assert abs(ref - new) < 1e-5
                        except:
                            print('unit value error')
                            return chi, n
                except:
                    print('char error')
                    return chi, n, r
Esempio n. 16
0
def test_bn(num_tests):
    # finds num_tests BN curves with random bit sizes;
    # checks that each curve found is a suitable curve
    print('testing BN...')
    fail = 0
    for i in range(0, num_tests):
        num_bits = randint(50,100)
        num_curves = randint(1, 20)
        try:
            curves = bn.make_curve(num_bits, num_curves)
            assert len(curves) == num_curves
            for q,t,r,k,D in curves:
                assert utils.is_suitable_curve(q,t,r,k,D, num_bits)
        except AssertionError as e:
            fail+=1
    if fail == 0:
        print('test passed')
        return True
    else:
        print("failed %.2f" %(100*fail/num_tests) + "% of tests!")
        return False
Esempio n. 17
0
def test_bn(num_tests):
    # finds num_tests BN curves with random bit sizes;
    # checks that each curve found is a suitable curve
    print('testing BN...')
    fail = 0
    for i in range(0, num_tests):
        num_bits = randint(50, 100)
        num_curves = randint(1, 20)
        try:
            curves = bn.make_curve(num_bits, num_curves)
            assert len(curves) == num_curves
            for q, t, r, k, D in curves:
                assert utils.is_suitable_curve(q, t, r, k, D, num_bits)
        except AssertionError as e:
            fail += 1
    if fail == 0:
        print('test passed')
        return True
    else:
        print("failed %.2f" % (100 * fail / num_tests) + "% of tests!")
        return False
Esempio n. 18
0
    def random_point(self):
        """
        Return a random closed point on the curve.

        """
        F = self.function_field()
        F0 = self.rational_function_field()
        R = F0._ring
        f = R.random_element(degree=(1,3)).factor()[0][0](F0.gen())
        v0 = F0.valuation(f)
        V = v0.extensions(F)
        v = V[randint(0, len(V)-1)]
        return PointOnSmoothProjectiveCurve(self, v)
def run(num_bits, k):
    """
    Description:
    
        Runs the Dupont-Enge-Morain method multiple times until a valid curve is found
    
    Input:
    
        num_bits - number of bits
        k - an embedding degree
    
    Output:
    
        (q,t,r,k,D) - an elliptic curve;
                      if no curve is found, the algorithm returns (0,0,0,k,0)
    
    """
    j, r, q, t = 0, 0, 0, 0
    num_generates = 512
    h = num_bits / (euler_phi(k))
    tried = [(0, 0)]  # keep track of random values tried for efficiency
    for i in range(0, num_generates):
        D = 0
        y = 0
        while (D, y) in tried:  # find a pair that we have not tried
            D = -randint(1,
                         1024)  # pick a small D so that the CM method is fast
            D = fundamental_discriminant(D)
            m = 0.5 * (h - log(-D).n() / (2 * log(2)).n())
            if m < 1:
                m = 1
            y = randint(floor(2**(m - 1)), floor(2**m))
        tried.append((D, y))
        q, t, r, k, D = method(num_bits, k, D, y)  # run DEM
        if q != 0 and t != 0 and r != 0 and k != 0 and D != 0:  # found an answer, so output it
            assert is_valid_curve(q, t, r, k, D), 'Invalid output'
            return q, t, r, k, D
    return 0, 0, 0, k, 0  # found nothing
def test_ec(num_tests, num_bits, debug=False):
    print('testing EC chain...')
    func_start = time.time()
    fail = 0
    for i in range(0, num_tests):
        try:
            k = randint(5, 20)
            r = 0
            while not (r % k == 1 and is_prime(r)):
                r = random_prime(2**(num_bits - 1), 2**num_bits)
            k_vector = [k]
            k_vector.append(randint(5, 20))
            k_vector.append(randint(5, 20))
            curves = ec.new_chain(r, k_vector)
            assert ec.is_chain(curves)
        except AssertionError as e:
            fail += 1
    if fail == 0:
        print('test passed')
        return True
    else:
        print("failed %.2f" % (100 * fail / num_tests) + "% of tests!")
        return False
Esempio n. 21
0
def test_ec(num_tests,num_bits, debug=False):
    print('testing EC chain...')
    func_start = time.time()
    fail = 0
    for i in range(0, num_tests):
        try:
            k = randint(5,20)
            r = 0
            while not (r % k == 1 and is_prime(r)):
                r = random_prime(2**(num_bits-1), 2**num_bits)
            k_vector = [k]
            k_vector.append(randint(5,20))
            k_vector.append(randint(5,20))
            curves = ec.new_chain(r, k_vector)
            assert ec.is_chain(curves)
        except AssertionError as e:
            fail += 1
    if fail == 0:
        print('test passed')
        return True
    else:
        print("failed %.2f" %(100*fail/num_tests) + "% of tests!")
        return False
Esempio n. 22
0
def run(num_bits,k):
    """
    Description:
    
        Runs the Dupont-Enge-Morain method multiple times until a valid curve is found
    
    Input:
    
        num_bits - number of bits
        k - an embedding degree
    
    Output:
    
        (q,t,r,k,D) - an elliptic curve;
                      if no curve is found, the algorithm returns (0,0,0,k,0)
    
    """
    j,r,q,t = 0,0,0,0
    num_generates = 512
    h = num_bits/(euler_phi(k))
    tried = [(0,0)] # keep track of random values tried for efficiency
    for i in range(0,num_generates):
        D = 0
        y = 0
        while (D,y) in tried: # find a pair that we have not tried
            D = -randint(1, 1024) # pick a small D so that the CM method is fast
            D = fundamental_discriminant(D)
            m = 0.5*(h - log(-D).n()/(2*log(2)).n())
            if m < 1:
                m = 1
            y = randint(floor(2**(m-1)), floor(2**m))
        tried.append((D,y))
        q,t,r,k,D = method(num_bits,k,D,y) # run DEM
        if q != 0 and t != 0 and r != 0 and k != 0 and D != 0: # found an answer, so output it
            assert is_valid_curve(q,t,r,k,D), 'Invalid output'
            return q,t,r,k,D
    return 0,0,0,k,0 # found nothing
Esempio n. 23
0
def test_segment_intersect():
    from flatsurf.geometry.polygon import segment_intersect

    for _ in range(4096):
        us = (randint(-4, 4), randint(-4, 4))
        ut = (randint(-4, 4), randint(-4, 4))
        vs = (randint(-4, 4), randint(-4, 4))
        vt = (randint(-4, 4), randint(-4, 4))
        if us == ut or vs == vt:
            continue
        ans1 = segment_intersect((us,ut),(vs,vt))
        ans2 = segment_intersect((ut,us),(vs,vt))
        ans3 = segment_intersect((us,ut),(vt,vs))
        ans4 = segment_intersect((ut,us),(vt,vs))
        ans5 = segment_intersect((vs,vt),(us,ut))
        ans6 = segment_intersect((vt,vs),(us,ut))
        ans7 = segment_intersect((vs,vt),(ut,us))
        ans8 = segment_intersect((vt,vs),(ut,us))
        assert (ans1 == ans2 == ans3 == ans4 == ans5 == ans6 == ans7 == ans8), (us, ut, vs, vt, ans1, ans2, ans3, ans4, ans5, ans6, ans7, ans8)
Esempio n. 24
0
def random_split_primes(field, primes = 1, bits = 62, seed = None, relative_ext = None):
    # input:
    # * Number Field
    # * number of split primes in the field
    # * number of bits desired in each prime
    # * random "seed"
    # * optionally we might also require that a certain polynomial splits completely over the split primes
    # Output a list [(p, root)] where:
    # * p is a partially split prime in the number field (and fully split in the relative extension)
    # * a root of the defining polynomial mod p
    lower_bound = 2 ** (bits - 1);
    if seed is None:
        k = randint(1,2 ** (bits - 2) )
    else:
        k = 0;
    p = lower_bound + 1 + 2*k;
    if field is QQ:
        f = [0, 1]
    else:
        f = field.defining_polynomial().list()

    output = [];
    ps = [];

    if relative_ext is not None:
        f_relative = relative_ext.list();


    while len(output) < primes:
        while not is_pseudoprime(p):
            p += 2;
        FF = FiniteField(p);
        FFz = PolynomialRing(FF, "z");
        roots = FFz(f).roots()
        if len(roots) > 0: #== f.degree():
            root = roots[0][0].lift();
            if relative_ext is not None:
                if len(FFz( reduce_list_split(f_relative, (p, root)) ).roots()) == len(f_relative) - 1:
                    output.append((p, root));
                    ps.append(p);
            else:
                output.append((p, root));
                ps.append(p);
        p += 2;
    return output;
Esempio n. 25
0
def gen_fhe_instance(n, q, alpha=None, h=None, m=None, seed=None):
    """
    Generate FHE-style LWE instance

    :param n:     dimension
    :param q:     modulus
    :param alpha: noise rate (default: 8/q)
    :param h:     hamming weight of the secret (default: 2/3n)
    :param m:     number of samples (default: n)

    """
    if seed is not None:
        set_random_seed(seed)

    q = next_prime(ceil(q) - 1, proof=False)
    if alpha is None:
        alpha = ZZ(8) / q

    n, alpha, q = preprocess_params(n, alpha, q)

    stddev = stddevf(alpha * q)

    if m is None:
        m = n
    K = GF(q, proof=False)
    A = random_matrix(K, m, n)

    if h is None:
        s = random_vector(ZZ, n, x=-1, y=1)
    else:
        S = [-1, 1]
        s = [S[randint(0, 1)] for i in range(h)]
        s += [0 for _ in range(n - h)]
        shuffle(s)
        s = vector(ZZ, s)
    c = A * s

    D = DiscreteGaussian(stddev)

    for i in range(m):
        c[i] += D()

    return A, c
Esempio n. 26
0
def gen_fhe_instance(n, q, alpha=None, h=None, m=None, seed=None):
    """
    Generate FHE-style LWE instance

    :param n:     dimension
    :param q:     modulus
    :param alpha: noise rate (default: 8/q)
    :param h:     hamming weight of the secret (default: 2/3n)
    :param m:     number of samples (default: n)

    """
    if seed is not None:
        set_random_seed(seed)

    q = next_prime(ceil(q)-1, proof=False)
    if alpha is None:
        alpha = ZZ(8)/q

    n, alpha, q = preprocess_params(n, alpha, q)

    stddev = stddevf(alpha*q)

    if m is None:
        m = n
    K = GF(q, proof=False)
    A = random_matrix(K, m, n)

    if h is None:
        s = random_vector(ZZ, n, x=-1, y=1)
    else:
        S = [-1, 1]
        s = [S[randint(0, 1)] for i in range(h)]
        s += [0 for _ in range(n-h)]
        shuffle(s)
        s = vector(ZZ, s)
    c = A*s

    D = DiscreteGaussian(stddev)

    for i in range(m):
        c[i] += D()

    return A, c
def test_dem2(num_tests,num_bits,k, debug=False):
    # runs dupont enge morain method num_tests times;
    # each test uses a fixed embedding degree k
    print('testing DEM...')
    fail = 0
    k2 = k
    for i in range(0, num_tests):
        if not k2:
            k = randint(5,20)
        try:
            q,t,r,k,D = dem.run(num_bits,k)
            assert utils.is_suitable_curve(q,t,r,k,D,num_bits)
        except AssertionError as e:
            fail += 1
    if fail == 0:
        print('test passed')
        return True
    else:
        print("failed %.2f" %(100*fail/num_tests) + "% of tests!")
        return False
def test_cm(num_tests,num_bits, debug=False): 
    # runs CM method num_tests times;
    # each test uses a random output from the CP method with a num_bits bit prime
    print('testing CM...')
    fail = 0
    for i in range(0, num_tests):
        try:
            k = randint(5,50)
            r,k,D = cp.gen_params_from_bits(num_bits,k)
            q,t,r,k,D = cp.run(r,k,D)
            E = cm.make_curve(q,t,r,k,D)
            assert E
            assert cm.test_curve(q,t,r,k,D,E)
        except AssertionError as e:
            fail += 1
    if fail == 0:
        print('test passed')
        return True
    else:
        print("failed %.2f" %(100*fail/num_tests) + "% of tests!")
        return False
def test_cm(num_tests, num_bits, debug=False):
    # runs CM method num_tests times;
    # each test uses a random output from the CP method with a num_bits bit prime
    print('testing CM...')
    fail = 0
    for i in range(0, num_tests):
        try:
            k = randint(5, 50)
            r, k, D = cp.gen_params_from_bits(num_bits, k)
            q, t, r, k, D = cp.run(r, k, D)
            E = cm.make_curve(q, t, r, k, D)
            assert E
            assert cm.test_curve(q, t, r, k, D, E)
        except AssertionError as e:
            fail += 1
    if fail == 0:
        print('test passed')
        return True
    else:
        print("failed %.2f" % (100 * fail / num_tests) + "% of tests!")
        return False
def test_cp2(num_tests,num_bits,k, debug=False):
    # runs CP method num_tests times;
    # uses the same embedding degree k for every test
    print('testing CP...')
    fail = 0
    k2 = k
    for i in range(0, num_tests):
        if not k2:
            k = randint(5,50)
        try:
            r,k,D = cp.gen_params_from_bits(num_bits, k)
            assert cp.test_promise(r,k,D)
            q,t,r,k,D = cp.run(r,k,D)
            assert utils.is_suitable_curve(q,t,r,k,D,num_bits)
        except AssertionError as e:
            fail += 1
    if fail == 0:
        print('test passed')
        return True
    else:
        print("failed %.2f" %(100*fail/num_tests) + "% of tests!")
        return False
Esempio n. 31
0
def BinomialDistribution(eta):
    r = 0
    for i in range(eta):
        r += randint(0, 1) - randint(0, 1)
    return r
Esempio n. 32
0
File: main.py Progetto: koffie/lmfdb
def random_Dirichletwebpage():
    modulus = randint(1,9999)
    number = randint(1,modulus-1)
    while gcd(modulus,number) > 1:
        number = randint(1,modulus-1)
    return redirect(url_for('.render_Dirichletwebpage', modulus=str(modulus), number=str(number)))