def enc(cls, kyber, pk, m=None, seed=None, l=None): """IND-CPA encryption sans compression :param kyber: Kyber class, inherit and change constants to change defaults :param pk: public key :param m: optional message, otherwise all zero string is encrypted :param seed: seed used for random sampling if provided """ n, q, eta, k, D = kyber.n, kyber.q, kyber.eta, kyber.k, kyber.D if seed is not None: set_random_seed(seed) A, t = pk R = PolynomialRing(ZZ, "x") r = vector(R, k, [R([(D(eta)) for _ in range(n)]) for _ in range(k)]) e1 = vector(R, k, [R([(D(eta)) for _ in range(n)]) for _ in range(k)]) e2 = R([(D(eta)) for _ in range(n)]) if m is None: m = (0,) u = vector(R, [cls.muladd(kyber, r, A.column(i), e1[i], l=l) for i in range(k)]) u.set_immutable() v = cls.muladd(kyber, r, t, e2 + q//2 * R(list(m)), l=l) return u, v
def encap(cls, pk, seed=None): """IND-CCA encapsulation sans compression or extra hash :param cls: Kyber class, inherit and change constants to change defaults :param pk: public key :param seed: seed used for random sampling if provided .. note :: Resembles Algorithm 4 of the Kyber paper. """ n = cls.n if seed is not None: set_random_seed(seed) m = random_vector(GF(2), n) m.set_immutable() set_random_seed(hash(m)) # NOTE: this is obviously not faithful K_ = random_vector(GF(2), n) K_.set_immutable() r = ZZ.random_element(0, 2**n-1) c = cls.enc(pk, m, r) K = hash((K_, c)) # NOTE: this obviously isn't a cryptographic hash return c, K
def _gap_reset_random_seed(seed=100): """ Resets the random seed of GAP and (if necessary) reads three libraries. TEST: When :mod:`~pGroupCohomology.auxiliaries` is imported, some global variable in libGAP is defined:: sage: from pGroupCohomology.auxiliaries import _gap_reset_random_seed sage: libgap.eval('exportMTXLIB') == "MTXLIB=%s; export MTXLIB; "%sage.env.MTXLIB True The _gap_reset_random_seed function is automatically executed as well. Calling it again will reset libGAP's random seed. :: sage: libgap.eval('List([1..10],i->Random(1,100000))') [ 45649, 49273, 19962, 64029, 11164, 5492, 19892, 67868, 62222, 80867 ] sage: _gap_reset_random_seed() sage: libgap.eval('List([1..10],i->Random(1,100000))') [ 45649, 49273, 19962, 64029, 11164, 5492, 19892, 67868, 62222, 80867 ] """ from sage.all import set_random_seed set_random_seed(seed) gap.eval('Reset(GlobalMersenneTwister, {})'.format(seed)) gap.eval('Reset(GlobalRandomSource, {})'.format(seed))
def set_seed(self, seed): if __debug__: assert seed >= 0, seed self.seed = seed set_random_seed(self.seed) logger.debug('Set seed to: {}'.format(self.seed))
def decap(cls, sk, pk, c): """IND-CCA decapsulation :param cls: Kyber class, inherit and change constants to change defaults :param sk: secret key :param pk: public key :param c: ciphertext .. note :: Resembles Algorithm 5 of the Kyber paper. """ n = cls.n m = cls.dec(sk, c) m.set_immutable() set_random_seed(hash(m)) # NOTE: this is obviously not faithful K_ = random_vector(GF(2), n) K_.set_immutable() r = ZZ.random_element(0, 2**n-1) c_ = cls.enc(pk, m, r) if c == c_: return hash((K_, c)) # NOTE: this obviously isn't a cryptographic hash else: return hash(c) # NOTE ignoring z
def set_seed(self, seed=0): if __debug__: assert seed >= 0, seed self.seed = seed set_random_seed(self.seed) logger.debug('Set seed to: {}'.format(self.seed))
def enc(cls, pk, m=None, seed=None): """IND-CPA encryption sans compression :param cls: Kyber class, inherit and change constants to change defaults :param pk: public key :param m: optional message, otherwise all zero string is encrypted :param seed: seed used for random sampling if provided .. note :: Resembles Algorithm 2 of the Kyber paper. """ n, q, eta, k, D = cls.n, cls.q, cls.eta, cls.k, cls.D if seed is not None: set_random_seed(seed) A, t = pk R, x = PolynomialRing(ZZ, "x").objgen() f = R(cls.f) r = vector(R, k, [R([(D(eta)) for _ in range(n)]) for _ in range(k)]) e1 = vector(R, k, [R([(D(eta)) for _ in range(n)]) for _ in range(k)]) e2 = R([(D(eta)) for _ in range(n)]) if m is None: m = (0,) u = (r*A + e1) % f # NOTE ignoring compression u.set_immutable() v = (r*t + e2 + q//2 * R(list(m))) % f # NOTE ignoring compression return u, v
def key_gen(cls, seed=None): """Generate a new public/secret key pair :param cls: Kyber class, inherit and change constants to change defaults :param seed: seed used for random sampling if provided .. note :: Resembles Algorithm 1 of the Kyber paper. """ n, q, eta, k, D = cls.n, cls.q, cls.eta, cls.k, cls.D if seed is not None: set_random_seed(seed) R, x = PolynomialRing(ZZ, "x").objgen() Rq = PolynomialRing(GF(q), "x") f = R(cls.f) A = matrix(Rq, k, k, [Rq.random_element(degree=n - 1) for _ in range(k * k)]) s = vector(R, k, [R([(D(eta)) for _ in range(n)]) for _ in range(k)]) e = vector(R, k, [R([(D(eta)) for _ in range(n)]) for _ in range(k)]) t = (A * s + e) % f # NOTE ignoring compression return (A, t), s
def main7(): set_random_seed(0) p = next_prime(randrange(2**96)) q = next_prime(randrange(2**97)) n = p * q print(p, q, n) print(qsieve(n))
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 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)
def test(): #set_random_seed(0) #cohendiv() #set_random_seed(0) #sqrt1() #set_random_seed(0) #knuth() set_random_seed(0) aes_KeySetupEnc6()
def test_fractional_CRT_sample(): QQt = PolynomialRing(QQ, "t"); t = QQt.gen(); for K in [QQ, NumberField(t**2 - 2, "a"), NumberField(t**2 + 3, "a"), NumberField(t**3 - 2, "a"), NumberField(t**6 - t**5 + 2*t**4 + 8*t**3 - t**2 - 5*t + 7, "a"), NumberField(t**7 - 2*t**6 + 3*t**5 - 8*t**4 + 12*t**3 - 13*t**2 + 14*t - 6,"a"),NumberField(t**7 - 4*t**5 - t**4 - 5*t**3 + 4*t**2 - 4*t + 1,"a"), NumberField(t**5 - t**4 - 4*t**3 + 3*t**2 + 3*t - 1,"a")]: print "Testing fractional CRT on the %s" % K for i in range(100): set_random_seed(i) x, x_CRT = test_fractional_CRT(K) if x != x_CRT: print "Failed at i = %d" % i break; else: print "Test passed!\n"
def compute_kernel(args): if args.seed is not None: set_random_seed(args.seed) FPLLL.set_random_seed(args.seed) ecdsa = ECDSA(nbits=args.nlen) lines, k_list, _ = ecdsa.sample(m=args.m, klen_list=args.klen_list, seed=args.seed, errors=args.e) w_list = [2 ** (klen - 1) for klen in args.klen_list] f_list = [Integer(max(w_list) / wi) for wi in w_list] targetvector = vector([(k - w) * f for k, w, f in zip(k_list, w_list, f_list)] + [max(w_list)]) try: solver = ECDSASolver(ecdsa, lines, m=args.m, d=args.d, threads=args.threads) except KeyError: raise ValueError("Algorithm {alg} unknown".format(alg=args.alg)) expected_length = solver.evf(args.m, max(args.klen_list), prec=args.nlen // 2) gh = solver.ghf(args.m, ecdsa.n, args.klen_list, prec=args.nlen // 2) params = args.params if args.params else {} key, res = solver(solver=args.algorithm, flavor=args.flavor, **params) RR = RealField(args.nlen // 2) logging.info( ( "try: {i:3d}, tag: 0x{tag:016x}, success: {success:1d}, " "|v|: 2^{v:.2f}, |b[0]|: 2^{b0:.2f}, " "|v|/|b[0]|: {b0r:.3f}, " "E|v|/|b[0]|: {eb0r:.3f}, " "|v|/E|b[0]|: {b0er:.3f}, " "cpu: {cpu:10.1f}s, " "wall: {wall:10.1f}s, " "work: {total:d}" ).format( i=args.i, tag=args.tag, success=int(res.success), v=float(log(RR(targetvector.norm()), 2)), b0=float(log(RR(res.b0), 2)), b0r=float(RR(targetvector.norm()) / RR(res.b0)), eb0r=float(RR(expected_length) / RR(res.b0)), b0er=float(RR(targetvector.norm()) / gh), cpu=float(res.cputime), wall=float(res.walltime), total=res.ntests, ) ) return key, res, float(targetvector.norm())
def residue_ring_arith(P, e, n=None): """ Test that arithmetic in the residue field is correct. """ set_random_seed(0) R = ResidueRing(P, e) n0, n1 = R._moduli() alpha = F.gen() reps = [i+j*alpha for i in range(n0) for j in range(n1)] if n is not None: reps = [reps[random.randrange(len(reps))] for i in range(n)] reps_mod = [R(a) for a in reps] for i in range(len(reps)): for j in range(len(reps)): assert reps_mod[i] * reps_mod[j] == R(reps[i] * reps[j]) assert reps_mod[i] + reps_mod[j] == R(reps[i] + reps[j]) assert reps_mod[i] - reps_mod[j] == R(reps[i] - reps[j])
def residue_ring_arith(P, e, n=None): """ Test that arithmetic in the residue field is correct. """ set_random_seed(0) R = ResidueRing(P, e) n0, n1 = R._moduli() alpha = F.gen() reps = [i + j * alpha for i in range(n0) for j in range(n1)] if n is not None: reps = [reps[random.randrange(len(reps))] for i in range(n)] reps_mod = [R(a) for a in reps] for i in range(len(reps)): for j in range(len(reps)): assert reps_mod[i] * reps_mod[j] == R(reps[i] * reps[j]) assert reps_mod[i] + reps_mod[j] == R(reps[i] + reps[j]) assert reps_mod[i] - reps_mod[j] == R(reps[i] - reps[j])
def f(N): set_random_seed(0) # to replicate any linear algebra issues? level = no_space(canonical_gen(N)).replace('*','').replace('-','_') F = open(os.path.join(dir,'%s.txt'%level),'w') H = HilbertModularForms(N) level = no_space(canonical_gen(N)) try: D = H.elliptic_curve_factors() F.write('count %s %s %s\n'%(N.norm(), level, len(D))) F.flush() for i, E in enumerate(D): v = E.aplist(B) s = '%s\t%s\t%s\t%s'%(N.norm(), level, i, ' '.join([no_space(x) for x in v])) print s F.write(s+'\n') F.flush() except Exception, msg: F.write('exception %s %s "%s"\n'%(N.norm(), level, msg))
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 f(N): set_random_seed(0) # to replicate any linear algebra issues? level = no_space(canonical_gen(N)).replace('*', '').replace('-', '_') F = open(os.path.join(dir, '%s.txt' % level), 'w') H = HilbertModularForms(N) level = no_space(canonical_gen(N)) try: D = H.elliptic_curve_factors() F.write('count %s %s %s\n' % (N.norm(), level, len(D))) F.flush() for i, E in enumerate(D): v = E.aplist(B) s = '%s\t%s\t%s\t%s' % (N.norm(), level, i, ' '.join( [no_space(x) for x in v])) print s F.write(s + '\n') F.flush() except Exception, msg: F.write('exception %s %s "%s"\n' % (N.norm(), level, msg))
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 populate(self, level, weight, character=None, verbose=True): nc = self.collection level, weight, character, D = nc.normalize(level, weight, character) if verbose: print D C = nc.collection.counts.find(D) if C.count() == 0: if verbose: print "Skipping -- no newforms known yet (counts=0)" return cnt = C.next()['count'] if cnt == 0: # There are no newforms, so don't do any further work. if verbose: print "No newforms" return # Now check to see if all of the eigenvalue fields are known # by doing a query for all forms of the given level, weight, and # character for which the eigenvalue_field key is set. E = dict(D) E['eigenvalue_field'] = {'$exists': True} if nc.collection.find(E).count() == cnt: if verbose: print "All eigenvalue fields already known" return from psage.modform.rational.newforms import eigenvalue_fields from sage.all import set_random_seed, QQ set_random_seed(0) fields = eigenvalue_fields(level, weight, character) for num, K in enumerate(fields): # Update the document for the given newform query = dict(D) query['number'] = num if K == QQ: f = 'x-1' else: f = str(K.defining_polynomial()).replace(' ', '') if verbose: print f nc.collection.update(query, {'$set': { 'eigenvalue_field': f }}, safe=True)
def populate(self, level, weight, character=None, verbose=True): nc = self.collection level, weight, character, D = nc.normalize(level, weight, character) if verbose: print D C = nc.collection.counts.find(D) if C.count() == 0: if verbose: print "Skipping -- no newforms known yet (counts=0)" return cnt = C.next()['count'] if cnt == 0: # There are no newforms, so don't do any further work. if verbose: print "No newforms" return # Now check to see if all of the eigenvalue fields are known # by doing a query for all forms of the given level, weight, and # character for which the eigenvalue_field key is set. E = dict(D) E['eigenvalue_field'] = {'$exists':True} if nc.collection.find(E).count() == cnt: if verbose: print "All eigenvalue fields already known" return from psage.modform.rational.newforms import eigenvalue_fields from sage.all import set_random_seed, QQ set_random_seed(0) fields = eigenvalue_fields(level, weight, character) for num, K in enumerate(fields): # Update the document for the given newform query = dict(D) query['number'] = num if K == QQ: f = 'x-1' else: f = str(K.defining_polynomial()).replace(' ','') if verbose: print f nc.collection.update(query, {'$set':{'eigenvalue_field':f}}, safe=True)
# Copyright (C) 2016-2017, Edgar Costa # See LICENSE file for license details from sage.all import CC, Infinity, PolynomialRing, RealField, ZZ from sage.all import ceil, copy, gcd, log, norm, set_random_seed, sqrt, vector from AbelJacobi import AJ1, AJ2, PariIntNumInit, SetPariPrec from Divisor import Divisor from InvertAJglobal import InvertAJglobal set_random_seed(1) import random random.seed(1) digits = 150 prec = ceil(log(10) / log(2) * digits) SetPariPrec(digits + 50) PariIntNumInit(3) power = 6 threshold = 2**(prec * .5) ncurves = 8 #i = 8 needs more precision for i in range(ncurves): print "i = %s of %s" % (i + 1, ncurves) smoothQ = False ZT = PolynomialRing(ZZ, "T") T = ZT.gen() while not smoothQ: g = ZT.random_element(degree=6) # ZT([-4, 12, 0, -20, 0, 8, 1])# dg = g.derivative() smoothQ = gcd(g, dg) == 1 print "C: y^2 = %s" % g
def process_curve_standalone(label, digits=600, power=15, verbose=True, internalverbose=False, folder=None): import os set_random_seed(1) import random random.seed(1) C = lmfdb.getDBconnection() curve = C.genus2_curves.curves.find_one({'label': label}) if curve is None: print "Wrong label" return 2 endo_alg = curve['real_geom_end_alg'] # deals with the default folders if folder is None: if not '__datadir__' in globals(): import os import inspect filename = inspect.getframeinfo(inspect.currentframe())[0] __datadir__ = os.path.dirname(filename) + "/data/" base_folder = __datadir__ if endo_alg == 'R': print "End = QQ, Nothing to do" return 0 elif endo_alg == 'R x R': if curve['is_simple_geom']: type_folder = 'simple/RM' else: type_folder = 'split/nonCM_times_nonCM' elif endo_alg == 'C x R': type_folder = 'split/CM_times_nonCM' elif endo_alg == 'C x C': if curve['is_simple_geom']: type_folder = 'simple/CM' else: type_folder = 'split/CM_times_CM' elif endo_alg == 'M_2(R)': if curve['is_simple_geom']: type_folder = 'simple/QM' else: type_folder = 'split/nonCM_square' elif endo_alg == 'M_2(C)': type_folder = 'split/CM_square' else: print "did I forget a case?" return 1 folder = os.path.join(base_folder, type_folder) if not os.path.exists(folder): print "Creating dir: %s" % folder os.makedirs(folder) assert os.path.exists(folder) #filenames stdout_filename = os.path.join(folder, label + ".stdout") stderr_filename = os.path.join(folder, label + ".stderr") output_filename = os.path.join(folder, label + ".sage") sys.stdout = open(stdout_filename, 'w', int(0)) sys.stderr = open(stderr_filename, 'w') c, w = cputime(), walltime() data, sout, verified = process_curve_lmfdb(curve, digits, power=power, verbose=True, internalverbose=False) print "Time: CPU %.2f s, Wall: %.2f s" % ( cputime(c), walltime(w), ) output_file = open(output_filename, 'w') output_file.write(sout) output_file.close() sys.stdout.flush() os.fsync(sys.stdout.fileno()) sys.stderr.flush() os.fsync(sys.stderr.fileno()) sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ print "Done: label = %s, verified = %s" % (label, verified) print os.popen("tail -n 1 %s" % stdout_filename).read() if verified: return 0 else: return 1