def generate_pseudoprime(bases, min_bitsize=0): """ Generates a pseudoprime which passes the Miller-Rabin primality test for the provided bases. :param bases: the bases :param min_bitsize: the minimum bitsize of the generated pseudoprime (default: 0) :return: a tuple containing the pseudoprime, as well as its 3 prime factors """ bases.sort() k2 = next_prime(bases[-1]) k3 = next_prime(k2) while True: residues = [inverse_mod(-k2, k3), inverse_mod(-k3, k2)] moduli = [k3, k2] s = _generate_s(bases, k2, k3) residue, modulus = _backtrack(s, bases, residues, moduli, 0) if residue and modulus: i = (2 ** (min_bitsize // 3)) // modulus while True: p1 = residue + i * modulus p2 = k2 * (p1 - 1) + 1 p3 = k3 * (p1 - 1) + 1 if is_prime(p1) and is_prime(p2) and is_prime(p3): return p1 * p2 * p3, p1, p2, p3 i += 1 else: k3 = next_prime(k3)
def roca(n): keySize = n.bit_length() if keySize <= 960: M_prime = 0x1B3E6C9433A7735FA5FC479FFE4027E13BEA m = 5 elif 992 <= keySize <= 1952: M_prime = ( 0x24683144F41188C2B1D6A217F81F12888E4E6513C43F3F60E72AF8BD9728807483425D1E ) m = 4 print("Have you several days/months to spend on this ?") elif 1984 <= keySize <= 3936: M_prime = 0x16928DC3E47B44DAF289A60E80E1FC6BD7648D7EF60D1890F3E0A9455EFE0ABDB7A748131413CEBD2E36A76A355C1B664BE462E115AC330F9C13344F8F3D1034A02C23396E6 m = 7 print("You'll change computer before this scripts ends...") elif 3968 <= keySize <= 4096: print("Just no.") return None else: print("Invalid key size: {}".format(keySize)) return None beta = 0.1 a3 = Zmod(M_prime)(n).log(65537) order = Zmod(M_prime)(65537).multiplicative_order() inf = a3 >> 1 sup = (a3 + order) >> 1 # Upper bound for the small root x0 XX = floor(2 * n ** 0.5 / M_prime) invmod_Mn = inverse_mod(M_prime, n) # Create the polynom f(x) F = PolynomialRing(Zmod(n), implementation="NTL", names=("x",)) (x,) = F._first_ngens(1) # Search 10 000 values at a time, using multiprocess # too big chunks is slower, too small chunks also chunk_size = 10000 for inf_a in range(inf, sup, chunk_size): # create an array with the parameter for the solve function inputs = [ ((M_prime, n, a, m, XX, invmod_Mn, F, x, beta), {}) for a in range(inf_a, inf_a + chunk_size) ] # the sage builtin multiprocessing stuff from sage.parallel.multiprocessing_sage import parallel_iter from multiprocessing import cpu_count for k, val in parallel_iter(cpu_count(), solve, inputs): if val: p = val[0] q = val[1] print("{}:{}".format(p, q)) return val return "Fail"
def test_key(k): if (k * self.ecdsa.GG).xy()[0] == self.r_list[0]: d = Integer( mod(inverse_mod(self.r_list[0], self.ecdsa.n) * (k * self.s_list[0] - self.h_list[0]), self.ecdsa.n) ) pubkey = self.ecdsa.GG * d if ( itob(pubkey.xy()[0], self.ecdsa.baselen) + itob(pubkey.xy()[1], self.ecdsa.baselen) == self.vk.to_string() ): return True, d return False, None
def _generate_s(bases, k2, k3): s = [] for b in bases: s_b = set() for p in range(1, 4 * b, 2): if legendre_symbol(b, p) == -1: s_b.add(p) s.append(s_b) for i in range(len(s)): mod = 4 * bases[i] inv2 = inverse_mod(k2, mod) inv3 = inverse_mod(k3, mod) s2 = set() s3 = set() for z in s[i]: s2.add(inv2 * (z + k2 - 1) % mod) s3.add(inv3 * (z + k3 - 1) % mod) s[i] &= s2 & s3 return s
def sign(self, h, sk, klen=256, return_k=False): """ Sign ``h`` and signing key ``sk`` :param h: "hash" :param sk: signing key :param klen: number of bits in the nonce. :param return_k: """ d = btoi(sk.to_string()) hi = btoi(h) k = ZZ.random_element(2 ** klen) r = Integer((self.GG * k).xy()[0]) s = lift(inverse_mod(k, self.n) * mod(hi + d * r, self.n)) sig = itob(r, self.baselen) + itob(s, self.baselen) if return_k: return k, sig return sig
def K(self,m,n,c): r""" K(m,n,c) = sum_{d (c)} e((md+n\bar{d})/c) """ summa=0 z=CyclotomicField(c).gen() print "z=",z for d in range(c): if gcd(d,c)>1: continue try: dbar = inverse_mod(d,c) except ZeroDivisionError: print "c=",c print "d=",d raise ZeroDivisionError arg=m*dbar+n*d #print "arg=",arg summa=summa+z**arg return summa
def K(self, m, n, c): r""" K(m,n,c) = sum_{d (c)} e((md+n\bar{d})/c) """ summa = 0 z = CyclotomicField(c).gen() print "z=", z for d in range(c): if gcd(d, c) > 1: continue try: dbar = inverse_mod(d, c) except ZeroDivisionError: print "c=", c print "d=", d raise ZeroDivisionError arg = m * dbar + n * d #print "arg=",arg summa = summa + z**arg return summa
def openButterfly(e, alpha, n=3, sx=False, sy=False): F = GF(2**n, name='w') if n == 3: assert F == F3 ei = inverse_mod(e, 2**n - 1) alpha = F.fetch_int(alpha) s = [] for x, k in product(range(2**n), range(2**n)): x = F.fetch_int(x) k = F.fetch_int(k) x += k**e x = x**ei if sx: x, k = k, x x += alpha * k x, k = k, x x += alpha * k if sy: x, k = k, x x = x**e x += k**e x = x.integer_representation() k = k.integer_representation() s.append((x << n) | k) return SBox2(s)
def solve(M, n, a, m): # I need to import it in the function otherwise multiprocessing doesn't find it in its context from sage_functions import coppersmith_howgrave_univariate base = int(65537) # the known part of p: 65537^a * M^-1 (mod N) known = int(pow(base, a, M) * inverse_mod(M, n)) # Create the polynom f(x) F = PolynomialRing(Zmod(n), implementation="NTL", names=("x",)) (x,) = F._first_ngens(1) pol = x + known beta = 0.1 t = m + 1 # Upper bound for the small root x0 XX = floor(2 * n ** 0.5 / M) # Find a small root (x0 = k) using Coppersmith's algorithm roots = coppersmith_howgrave_univariate(pol, n, beta, m, t, XX) # There will be no roots for an incorrect guess of a. for k in roots: # reconstruct p from the recovered k p = int(k * M + pow(base, a, M)) if n % p == 0: return p, n // p
def do(level, weight, lfun_filename=None, instances_filename=None, hecke_filename=None, traces_filename=None, only_traces=False, only_orbit=None): print "N = %s, k = %s" % (level, weight) polyinfile = os.path.join(base_import, 'polydb/{}.{}.polydb'.format(level, weight)) mfdbinfile = os.path.join(base_import, 'mfdb/{}.{}.mfdb'.format(level, weight)) Ldbinfile = os.path.join(base_import, 'mfldb/{}.{}.mfldb'.format(level, weight)) notfound = False if not os.path.exists(polyinfile): print '{} not found'.format(polyinfile) notfound = True if not os.path.exists(mfdbinfile): print '{} not found'.format(mfdbinfile) notfound = True if not os.path.exists(Ldbinfile): print '{} not found'.format(Ldbinfile) notfound = True if only_orbit is not None: print "N = %s, k = %s, orbit = %s" % (level, weight, only_orbit) if lfun_filename is None: lfun_filename = os.path.join( base_export, 'CMF_Lfunctions_%d_%d_%d.txt' % (level, weight, only_orbit)) if instances_filename is None: instances_filename = os.path.join( base_export, 'CMF_instances_%d_%d_%d.txt' % (level, weight, only_orbit)) if hecke_filename is None: hecke_filename = os.path.join( base_export, 'CMF_hecke_cc_%d_%d_%d.txt' % (level, weight, only_orbit)) if traces_filename is None: traces_filename = os.path.join( base_export, 'CMF_traces_%d_%d_%d.txt' % (level, weight, only_orbit)) if lfun_filename is None: lfun_filename = os.path.join( base_export, 'CMF_Lfunctions_%d.txt' % (level * weight**2)) if instances_filename is None: instances_filename = os.path.join( base_export, 'CMF_instances_%d.txt' % (level * weight**2)) if hecke_filename is None: hecke_filename = os.path.join( base_export, 'CMF_hecke_cc_%d.txt' % (level * weight**2)) if traces_filename is None: traces_filename = os.path.join( base_export, 'CMF_traces_%d.txt' % (level * weight**2)) def write_traces(traces_filename): with open(traces_filename, 'a') as F: for ol in Set(orbit_labels.values()): if only_orbit is not None: if ol != only_orbit: continue F.write('{}:{}:{}:{}:{}\n'.format(level, weight, ol, degrees_sorted[ol], traces_sorted[ol]).replace( ' ', '')) #level_list = set() #level_weight_list = [] #for dirpath, dirnames, filenames in os.walk(inpath): # for filename in filenames: # if not filename.endswith('.polydb'): # continue # level, weight, _ = filename.split('.') # level = int(level) # weight = int(weight) # level_weight_list.append( (level, weight, os.path.join(dirpath, filename)) ) # level_list.add(level) # #level_list = sorted(level_list) orbit_labels = {} G = DirichletGroup_conrey(level) orbits = G._galois_orbits() for k, orbit in enumerate(orbits): for chi in orbit: # we are starting at 1 orbit_labels[chi] = k + 1 if level == 1: k = 0 orbit_labels = {1: 1} degrees_sorted = [[] for _ in range(k + 2)] traces_sorted = [[] for _ in range(k + 2)] dim = dimension_new_cusp_forms(Gamma1(level), weight) if notfound: assert dim == 0, "dim = %s" % dim write_traces(traces_filename) return 1 degree_lists = {} traces_lists = {} db = sqlite3.connect(polyinfile) db.row_factory = sqlite3.Row ''' expected schema: CREATE TABLE heckepolys (level INTEGER, weight INTEGER, chi INTEGER, whatevernumber INTEGER, labelnumber INTEGER, operator BLOB, degree INTEGER, mforbit BLOB, polynomial BLOB); ''' mfdb = sqlite3.connect(os.path.join(mfdbinfile)) mfdb.row_factory = sqlite3.Row ''' expected schema: CREATE TABLE modforms (level INTEGER, weight INTEGER, chi INTEGER, orbit INTEGER, j INTEGER, prec INTEGER, exponent INTEGER, ncoeffs INTEGER, coefficients BLOB) ''' coeffs = {} for result in mfdb.execute( 'SELECT prec, exponent, ncoeffs, coefficients, chi, j FROM modforms WHERE level={} AND weight={};' .format(level, weight)): chi = result['chi'] chibar = inverse_mod(chi, level) if only_orbit is not None and only_orbit not in [ orbit_labels[chi], orbit_labels[chibar] ]: continue is_trivial = False #is_quadratic = False if chi == 1: is_trivial = True #elif (chi*chi) % level == 1: # is_quadratic = True j = result['j'] offset = 0 coeffblob = result['coefficients'] exponent = QQ(result['exponent']) prec = QQ(result['prec']) # print prec, exponent _coeffs = [CCC(0)] * (to_compute + 1) #for k in range(35): # number of prime powers < 100 for pp in prime_powers(to_compute): z, bytes_read = read_gmp_int(coeffblob, offset) #print z offset = offset + bytes_read real_part = CCC(z) * 2**exponent if prec != MF_PREC_EXACT: real_part = real_part.add_error(2**prec) imag_part = 0 if not is_trivial: z, bytes_read = read_gmp_int(coeffblob, offset) offset = offset + bytes_read imag_part = CCC.gens()[0] * CCC(z) * 2**exponent if prec != MF_PREC_EXACT: imag_part = imag_part.add_error(2**prec) #print real_part + imag_part _coeffs[pp] = real_part + imag_part #print coeffs _coeffs[1] = CCC(1) extend_multiplicatively(_coeffs) coeffs[(chi, j)] = _coeffs if chibar > chi: coeffs[(chibar, j)] = [elt.conjugate() for elt in _coeffs] if only_orbit is None: assert len(coeffs) == dim, "%s != %s, keys = %s" % (len(coeffs), dim, coeffs.keys()) if not only_traces: bad_euler_factors = {} euler_factors = {} angles = {} coeffs_f = {} for key, coeff in coeffs.iteritems(): chi, j = key coeffs_f[key], angles[key], euler_factors[key], bad_euler_factors[ key] = angles_euler_factors(coeff, level, weight, chi) #mforbits = {} for result in db.execute( 'SELECT level, weight, chi, whatevernumber, labelnumber, degree, mforbit from heckepolys;' ): level = result['level'] weight = result['weight'] chi = result['chi'] original_chi = chi if only_orbit is not None and only_orbit != orbit_labels[original_chi]: continue if (level, weight, chi) not in degree_lists: degree_lists[(level, weight, chi)] = [] traces_lists[(level, weight, chi)] = [] degree_lists[(level, weight, chi)].append(result['degree']) #whatever = result['whatevernumber'] label = result['labelnumber'] #degree = result['degree'] mforbit = read_orbit(result['mforbit']) #mforbits[original_chi] = mforbit #print level, weight, chi, whatever, label, degree, mforbit #is_trivial = False #is_quadratic = False #if chi == 1: # is_trivial = True #elif (chi*chi) % level == 1: # is_quadratic = True traces_bound = to_compute + 1 traces = [RRR(0)] * traces_bound for chi, j in mforbit: #if inverse_mod(chi, level) < chi: # continue for k, z in enumerate(coeffs[(chi, j)][:traces_bound]): traces[k] += RRR(z.real()) for i, z in enumerate(traces): try: traces[i] = z.unique_integer() except ValueError: traces = traces[:i] #print (level, weight, original_chi, orbit_labels[original_chi]) #print degree_lists[(level, weight, original_chi)] #print i, z #print traces[:i] break traces_lists[(level, weight, original_chi)].append( (traces[1:], mforbit)) Ldb = sqlite3.connect(os.path.join(Ldbinfile)) Ldb.row_factory = sqlite3.Row ''' expected schema: CREATE TABLE modformLfunctions (level INTEGER, weight INTEGER, chi INTEGER, orbit INTEGER, j INTEGER, rank INTEGER, rankverified INTEGER, signarg REAL gamma1 REAL, gamma2 REAL, gamma3 REAL, zeroprec INTEGER, nzeros INTEGER, zeros BLOB, valuesdelta REAL, nvalues INTEGER, Lvalues BLOB); ''' zeros = {} Ldbresults = {} if only_traces: cur = [] else: cur = Ldb.execute( 'SELECT level, weight, chi, j, rank, zeroprec, nzeros, zeros, valuesdelta, nvalues, Lvalues, signarg from modformLfunctions' ) for result in cur: nzeros = result['nzeros'] prec = result['zeroprec'] chi = result['chi'] if only_orbit is not None and only_orbit != orbit_labels[chi]: continue j = result['j'] #print result['level'], result['weight'], chi, j _zeros = [] offset = 0 for k in range(nzeros): nlimbs = struct.unpack_from(">I", result['zeros'], offset)[0] offset = offset + 4 zdata = struct.unpack_from("B" * nlimbs, result['zeros'], offset) offset = offset + nlimbs z = sum([x * 2**(8 * k) for (k, x) in enumerate(reversed(zdata))]) _zeros.append(z) zeros[(chi, j)] = map(ZZ, _zeros) Ldbresults[(chi, j)] = result ''' for level, weight, chi in sorted(degree_lists.keys()): toprint = '{}:{}:{}:[{}]:[{}]'.format(level, weight, orbit_labels[chi], sorted(degree_lists[(level, weight, chi)]), sorted(traces_lists[(level, weight, chi)])) print ''.join(toprint.split()) for chi2, j in mforbits[chi]: print chi2, j, zeros[(chi2, j)] ''' labels = {} original_pair = {} conjugates = {} selfduals = {} hecke_orbit_code = {} all_the_labels = {} embedding_m = {} for level, weight, originalchi in sorted(degree_lists.keys()): #toprint = '{}:{}:{}:{}'.format(level, weight, orbit_labels[originalchi], sorted(degree_lists[(level, weight, originalchi)])) #print ''.join(toprint.split()) degrees_sorted[orbit_labels[originalchi]] = sorted( degree_lists[(level, weight, originalchi)]) for mforbitlabel, (traces, mforbit) in enumerate( sorted(traces_lists[(level, weight, originalchi)])): selfdual = False if originalchi == 1: selfdual = True if (originalchi * originalchi) % level == 1: Z = coeffs[mforbit[0]] selfdual = True for z in Z: if not z.imag().contains_zero(): selfdual = False break #if selfdual: # print '*', #print mforbit, traces traces_sorted[orbit_labels[originalchi]].append(traces[:to_store]) if only_traces: continue chi_list = sorted(set(chi for (chi, j) in mforbit)) coeffs_list = {} for chi in chi_list: j_list = [elt for (_, elt) in mforbit if _ == chi] coeffs_list[chi] = [(chi, elt, coeffs[(chi, elt)]) for elt in j_list] coeffs_list[chi].sort(cmp=CBFlistcmp, key=lambda z: z[-1]) d = len(j_list) m = 1 for chi in chi_list: chibar = inverse_mod(chi, level) for k, _coeffs in enumerate(coeffs_list[chi]): j = _coeffs[1] assert chi == _coeffs[0] sa, sn = cremona_letter_code(mforbitlabel), k + 1 ol = cremona_letter_code(orbit_labels[chi] - 1) an_conjugate = [elt.conjugate() for elt in _coeffs[2]] if selfdual: chibar = chi ca, cn = sa, sn else: ca = sa # first try the obvious for elt in [k] + list(range(0, k)) + list( range(k + 1, d)): if CBFlisteq(coeffs_list[chibar][elt][2], an_conjugate): cn = elt + 1 break else: assert False assert CBFlisteq(coeffs_list[chibar][cn - 1][2], an_conjugate) # orbit_labels[chi] start at 1 # mforbitlabel starts at 0 hecke_orbit_code[(chi, j)] = int(level + (weight << 24) + ( (orbit_labels[chi] - 1) << 36) + (mforbitlabel << 52)) all_the_labels[(chi, j)] = (level, weight, ol, sa, chi, sn) converted_label = (chi, sa, sn) labels[(chi, j)] = converted_label original_pair[converted_label] = (chi, j) selfduals[converted_label] = selfdual conjugates[converted_label] = (chibar, ca, cn) embedding_m[(chi, j)] = m m += 1 if only_traces: write_traces(traces_filename) return 0 #for key, val in labels.iteritems(): # print key," \t-new->\t", val #for key, val in conjugates.iteritems(): # print key,"\t--c-->\t", val #for key, val in all_the_labels.iteritems(): # print key," \t--->\t" + "\t".join( map(str, [val,hecke_orbit_code[key]])) def origin(chi, a, n): return "ModularForm/GL2/Q/holomorphic/%d/%d/%s/%s/%d/%d" % ( level, weight, cremona_letter_code(orbit_labels[chi] - 1), a, chi, n) def rational_origin(chi, a): return "ModularForm/GL2/Q/holomorphic/%d/%d/%s/%s" % ( level, weight, cremona_letter_code(orbit_labels[chi] - 1), a) def label(chi, j): return labels[(chi, j)] def self_dual(chi, a, n): return selfduals[(chi, a, n)] Lhashes = {} instances = {} # the function below assumes this order assert schema_instances == ['url', 'Lhash', 'type'] def tuple_instance(row): return (row['origin'], row['Lhash'], default_type) real_zeros = {} rows = {} def populate_complex_row(Ldbrow): row = dict(constant_lf(level, weight, 2)) chi = int(Ldbrow['chi']) j = int(Ldbrow['j']) chil, a, n = label(chi, j) assert chil == chi row['order_of_vanishing'] = int(Ldbrow['rank']) zeros_as_int = zeros[(chi, j)][row['order_of_vanishing']:] prec = row['accuracy'] = Ldbrow['zeroprec'] two_power = 2**prec double_zeros = [float(z / two_power) for z in zeros_as_int] zeros_as_real = [ RealNumber(z.str() + ".") / two_power for z in zeros_as_int ] real_zeros[(chi, a, n)] = zeros_as_real zeros_as_str = [z.str(truncate=False) for z in zeros_as_real] for i, z in enumerate(zeros_as_str): assert float(z) == double_zeros[i] assert (RealNumber(z) * two_power).round() == zeros_as_int[i] row['positive_zeros'] = str(zeros_as_str).replace("'", "\"") row['origin'] = origin(chi, a, n) row['central_character'] = "%s.%s" % (level, chi) row['self_dual'] = self_dual(chi, a, n) row['conjugate'] = None row['Lhash'] = str((zeros_as_int[0] * 2**(100 - prec)).round()) if prec < 100: row['Lhash'] = '_' + row['Lhash'] Lhashes[(chi, a, n)] = row['Lhash'] row['sign_arg'] = float(Ldbrow['signarg'] / (2 * pi)) for i in range(0, 3): row['z' + str(i + 1)] = (RealNumber(str(zeros_as_int[i]) + ".") / 2**prec).str() row['plot_delta'] = Ldbrow['valuesdelta'] row['plot_values'] = [ float(CDF(elt).real_part()) for elt in struct.unpack('{}d'.format(len(Ldbrow['Lvalues']) / 8), Ldbrow['Lvalues']) ] row['leading_term'] = '\N' if row['self_dual']: row['root_number'] = str( RRR(CDF(exp(2 * pi * I * row['sign_arg'])).real()).unique_integer()) if row['root_number'] == str(1): row['sign_arg'] = 0 elif row['root_number'] == str(-1): row['sign_arg'] = 0.5 else: row['root_number'] = str(CDF(exp(2 * pi * I * row['sign_arg']))) #row['dirichlet_coefficients'] = [None] * 10 #print label(chi,j) for i, ai in enumerate(coeffs[(chi, j)][2:12]): if i + 2 <= 10: row['a' + str(i + 2)] = CBF_to_pair(ai) # print 'a' + str(i+2), ai_jsonb #row['dirichlet_coefficients'][i] = ai_jsonb row['coefficient_field'] = 'CDF' # only 30 row['euler_factors'] = map(lambda x: map(CBF_to_pair, x), euler_factors[(chi, j)][:30]) row['bad_lfactors'] = map( lambda x: [int(x[0]), map(CBF_to_pair, x[1])], bad_euler_factors[(chi, j)]) for key in schema_lf: assert key in row, "%s not in row = %s" % (key, row) assert len(row) == len(schema_lf), "%s != %s" % (len(row), len(schema_lf)) #rewrite row as a list rows[(chi, a, n)] = [row[key] for key in schema_lf] instances[(chi, a, n)] = tuple_instance(row) def populate_complex_rows(): for key, row in Ldbresults.iteritems(): populate_complex_row(row) def populate_conjugates(): # print Lhashes.keys() for key, row in rows.iteritems(): # print "key = %s" % (key,) row[schema_lf_dict['conjugate']] = Lhashes[conjugates[key]] row_conj = rows[conjugates[key]] zero_val_conj = row_conj[schema_lf_dict['plot_values']][0] assert (row[schema_lf_dict['plot_values']][0] - zero_val_conj) < 1e-10, "%s, %s: %s - %s = %s" % ( key, conjugates[key], row[schema_lf_dict['plot_values']][0], zero_val_conj, row[schema_lf_dict['plot_values']][0] - zero_val_conj) diff = (row[schema_lf_dict['sign_arg']] + row_conj[schema_lf_dict['sign_arg']]) % 1 assert min(diff, 1 - diff) < 1e-10, "%s + %s = %s" % ( row[schema_lf_dict['sign_arg']], row_conj[schema_lf_dict['sign_arg']], diff) rational_rows = {} def populate_rational_rows(): order_of_vanishing = schema_lf_dict['order_of_vanishing'] accuracy = schema_lf_dict['accuracy'] sign_arg = schema_lf_dict['sign_arg'] Lhash = schema_lf_dict['Lhash'] plot_delta = schema_lf_dict['plot_delta'] plot_values = schema_lf_dict['plot_values'] central_character = schema_lf_dict['central_character'] # reverse euler factors from the table for p^d < 1000 rational_keys = {} for chi, a, n in rows.keys(): orbit_label = orbit_labels[chi] if (orbit_label, a) not in rational_keys: rational_keys[(orbit_label, a)] = [] rational_keys[(orbit_label, a)].append((chi, a, n)) for (orbit_label, a), triples in rational_keys.iteritems(): # for now skip degree >= 100 if len(triples) > 80: # the real limit is 87 continue pairs = [original_pair[elt] for elt in triples] #print a, pairs, triples chi = triples[0][0] degree = 2 * len(triples) row = constant_lf(level, weight, degree) row['origin'] = rational_origin(chi, a) print row['origin'] row['self_dual'] = 't' row['conjugate'] = '\N' row['order_of_vanishing'] = sum( [rows[elt][order_of_vanishing] for elt in triples]) row['accuracy'] = min([rows[elt][accuracy] for elt in triples]) ### zeros_as_real = [] for elt in triples: zeros_as_real.extend(real_zeros[elt]) zeros_as_real.sort() zeros_as_str = [z.str(truncate=False) for z in zeros_as_real] row['positive_zeros'] = str(zeros_as_str).replace("'", "\"") zeros_hash = sorted([(rows[elt][Lhash], real_zeros[elt][0]) for elt in triples], key=lambda x: x[1]) row['Lhash'] = ",".join([elt[0] for elt in zeros_hash]) # character if degree == 2: row['central_character'] = rows[triples[0]][central_character] else: G = DirichletGroup_conrey(level) chiprod = prod([ G[int(rows[elt][central_character].split(".")[-1])] for elt in triples ]) chiprod_index = chiprod.number() row['central_character'] = "%s.%s" % (level, chiprod_index) row['sign_arg'] = sum([rows[elt][sign_arg] for elt in triples]) while row['sign_arg'] > 0.5: row['sign_arg'] -= 1 while row['sign_arg'] <= -0.5: row['sign_arg'] += 1 zeros_zi = [] for i in range(0, 3): for elt in triples: zeros_zi.append(rows[elt][schema_lf_dict['z' + str(i + 1)]]) zeros_zi.sort(key=lambda x: RealNumber(x)) for i in range(0, 3): row['z' + str(i + 1)] = zeros_zi[i] deltas = [rows[elt][plot_delta] for elt in triples] values = [rows[elt][plot_values] for elt in triples] row['plot_delta'], row['plot_values'] = prod_plot_values( deltas, values) row['leading_term'] = '\N' row['root_number'] = str( RRR(CDF(exp(2 * pi * I * row['sign_arg'])).real()).unique_integer()) if row['root_number'] == str(1): row['sign_arg'] = 0 elif row['root_number'] == str(-1): row['sign_arg'] = 0.5 row['coefficient_field'] = '1.1.1.1' for chi, _, _ in triples: if (level, weight, chi) in traces_lists: for elt in traces_lists[(level, weight, chi)]: if set(elt[1]) <= set(pairs): traces = elt[0] break else: print pairs print traces_lists[(level, weight, chi)] assert False break else: print pairs print traces_lists assert False euler_factors_cc = [euler_factors[elt] for elt in pairs] row['euler_factors'], row[ 'bad_lfactors'], dirichlet = rational_euler_factors( traces, euler_factors_cc, level, weight) #handling Nones row['euler_factors'] = json.dumps(row['euler_factors']) row['bad_lfactors'] = json.dumps(row['bad_lfactors']) # fill in ai for i, ai in enumerate(dirichlet): if i > 1: row['a' + str(i)] = int(dirichlet[i]) #print 'a' + str(i), dirichlet[i] for key in schema_lf: assert key in row, "%s not in row = %s" % (key, row.keys()) for key in row.keys(): assert key in schema_lf, "%s unexpected" % key assert len(row) == len(schema_lf), "%s != %s" % (len(row), len(schema_lf)) #rewrite row as a list rational_rows[(orbit_label, a)] = [row[key] for key in schema_lf] instances[(orbit_label, a)] = tuple_instance(row) # if dim == 1, drop row if len(triples) == 1: rows.pop(triples[0]) instances.pop(triples[0]) def get_hecke_cc(): # if field_poly exists then compute the corresponding embedding of the root # add the conrey label hecke_cc = {} for key, label in labels.iteritems(): # key = (chi,j) # label = (chi, a, n) chi, a, n = label ol = cremona_letter_code(orbit_labels[chi] - 1) lfuntion_label = ".".join( map(str, [level, weight] + [ol, a, chi, n])) hecke_cc[key] = [ int(hecke_orbit_code[key]), lfuntion_label, # N.k.c.x.n int(label[0]), # conrey_label int(label[2]), # embedding_index int(embedding_m[key]), '\N', # embedding_root_real '\N', # embedding_root_imag coeffs_f[key][1:], angles[key], ] return hecke_cc def json_hack(elt): if isinstance(elt, str): return elt else: return json.dumps(elt) def write_hecke_cc(hecke_filename): write_header_hecke_file(hecke_filename) with open(hecke_filename, 'a') as HF: for v in get_hecke_cc().values(): try: HF.write("\t".join(map(json_hack, v)).replace( '[', '{').replace(']', '}') + "\n") except TypeError: for elt in v: print elt print json_hack(elt) raise def export_complex_rows(lfunctions_filename, instances_filename): write_header(lfunctions_filename, instances_filename) #str_parsing_lf = '\t'.join(['%r'] * len(schema_lf)) + '\n' #str_parsing_instances = '\t'.join(['%r'] * len(schema_instances)) + '\n' with open(lfunctions_filename, 'a') as LF: for key, row in rows.iteritems(): try: LF.write("\t".join(map(json_hack, row)) + "\n") except TypeError: for i, elt in enumerate(row): print schema_lf[i] print elt print json_hack(elt) raise for key, row in rational_rows.iteritems(): try: LF.write("\t".join(map(json_hack, row)) + "\n") except TypeError: for elt in row: print elt print json_hack(elt) raise with open(instances_filename, 'a') as IF: for key, row in instances.iteritems(): IF.write("\t".join(map(json_hack, row)) + "\n") populate_complex_rows() #populate_conjugates() #populate_rational_rows() #export_complex_rows(lfun_filename, instances_filename) write_hecke_cc(hecke_filename) #write_traces(traces_filename) return 0
def gen_lattice(self, d=None): """FIXME! briefly describe function :param d: """ try: I = self.indices[self.nbases] # noqa self.nbases += 1 except ValueError: raise StopIteration("No more bases to sample.") p = self.ecdsa.n # w = 2 ** (self.klen - 1) w_list = [2 ** (klen - 1) for klen in self.klen_list] r_list = [self.r_list[i] for i in I] s_list = [self.s_list[i] for i in I] h_list = [self.h_list[i] for i in I] rm = r_list[-1] sm = s_list[-1] hm = h_list[-1] wm = w_list[-1] a_list = [ lift( wi - mod(r, p) * inverse_mod(s, p) * inverse_mod(rm, p) * mod(sm, p) * wm - inverse_mod(s, p) * mod(h, p) + mod(r, p) * inverse_mod(s, p) * mod(hm, p) * inverse_mod(rm, p) ) for wi, h, r, s in zip(w_list[:-1], h_list[:-1], r_list[:-1], s_list[:-1]) ] t_list = [ -lift(mod(r, p) * inverse_mod(s, p) * inverse_mod(rm, p) * sm) for r, s in zip(r_list[:-1], s_list[:-1]) ] d = self.d A = IntegerMatrix(d, d) f_list = [Integer(max(w_list) / w) for w in w_list] for i in range(d - 2): A[i, i] = p * f_list[i] for i in range(d - 2): A[d - 2, i] = t_list[i] * f_list[i] A[d - 2, d - 2] = f_list[-1] for i in range(d - 2): A[d - 1, i] = a_list[i] * f_list[i] A[d - 1, d - 1] = max(w_list) if self.ecdsa.nbits > 384: M = GSO.Mat( A, U=IntegerMatrix.identity(A.nrows, int_type=A.int_type), UinvT=IntegerMatrix.identity(A.nrows, int_type=A.int_type), float_type="ld", flags=GSO.ROW_EXPO, ) else: M = GSO.Mat( A, U=IntegerMatrix.identity(A.nrows, int_type=A.int_type), UinvT=IntegerMatrix.identity(A.nrows, int_type=A.int_type), flags=GSO.ROW_EXPO, ) M.update_gso() return M
assert xs == small_lgs(matrix(A)) print ' Testing homogenous LGS modulo prime' hi = 2**128 lo = 2**100 p = next_prime(hi) n = 40 # num vars m = 35 # num equations xs = [randrange(lo) for _ in range(n)] xs = vector(xs) A = [] for i in range(m): cs = [randrange(p) for _ in range(n-1)] last_c = -sum(c*x for c, x in zip(cs, xs)) * inverse_mod(xs[-1], p) cs.append(last_c % p) assert sum(c*x for c, x in zip(cs, xs))%p == 0 A.append(cs) A = matrix(ZZ, A) assert xs == small_lgs(A, mod=p) assert xs == small_lgs2(A, c=None, mod=p) print ' Testing homogenous LGS modulo composite' hi = 2**128 lo = 2**100 p = hi + 1 assert not is_prime(p) n = 40 # num vars
sigs = [] print 'Filling buffer...' iter = 0 while True: iter += 1 n = 50 sigs.append(oracle(msg)) while len(sigs) < n + 1: sigs.append(oracle(msg)) print 'Iteration %d' % iter (r0, s0, klo0) = sigs[-n - 1] r0inv = inverse_mod(r0, q) svec, tvec = [], [] for idx in range(-n, 0): (r, s, klo) = sigs[idx] t = inverse_mod(-s, q) A = (h * (1 - r * r0inv) * t) % q B = (r * r0inv * s0 * t) % q inv = inverse_mod(M, q) t = ((A + B * klo0 + klo) * inv) % q s = (B * M * inv) % q svec.append(s) tvec.append(t) A = [[-1] + svec] + [[0] * i + [q] + [0] * (n - i)
def crack_by_q(self): g = gcd(self.q - 1, self.e) d = inverse_mod(Integer(self.e / g), self.q - 1) mg = powmod(self.c % self.q, d, self.q) CRSE = CrackSmallE(mg, g, self.q, self.q - 1) return mg if g == 1 else CRSE.crack()
def test_SECCON_2020_crypto01(): masked_flag = 8077275413285507538357977814283814136815067070436948406142717872478737670143034266458000767181162602217137657160614964831459653429727469965712631294123225 ciphertexts = [ ( 886775008733978973740257525650074677865489026053222554158847150065839924739525729402395428639350660027796013999414358689067171124475540042281892825140355436902197270317502862419355737833115120643020255177020178331283541002427279377648285229476212651491301857891044943211950307475969543789857568915505152189, 428559018841948586040450870835405618958247103990365896475476359721456520823105336402250177610460462882418373365551361955769011150860740050608377302711322189733933012507453380208960247649622047461113987220437673085, (80103920082434941308951713928956232093682985133090231319482222058601362901404235742975739345738195056858602864819514638254604213654261535503537998613664606957411824998071339098079622119781772477940471338367084695408560473046701072890754255641388442248683562485936267601216704036749070688609079527182189924, 842529568002033827493313169405480104392127700904794758022297608679141466431472390397211660887148306350328312067659313538964875094877785244888004725864621826211254824064492961341512012172365417791553455922872091302295614295785447354268009914265614957287377743897340475899980395298019735631787570231395791009 ), 59051335744243522933765175665, ), ( 37244493713246153778174562251362609960152354778990433088693945121840521598316370898923829767722653817418453309557995775960963654893571162621888675965423771020678918714406461976659339420718804301006282789714856197345257634581330970033427061846386874027391337895557558939538516456076874074642348992933600929747, 152657520846237173082171645969128953029734435220247551748055538422696193261367413610113664730705318574898280226247526051526753570012356026049784218573767765351341949785570284026342156807244268439356037529507501666987, (14301224815357080657295611483943004076662022528706782110580690613822599700117720290144067866898573981166927919045773324162651193822888938569692341428439887892150361361566562459037438581637126808773605536449091609307652818862273375400935935851849153633881318435727224452416837785155763820052159016539063161774, 711567521767597846126014317418558888899966530302382481896965868976010995445213619798358362850235642988939870722858624888544954189591439381230859036120045216842190726357421800117080884618285875510251442474167884705409694074544449959388473647082485564659040849556130494057742499029963072560315800049629531101 ), 56178670950277431873900982569, ), ( 6331516792334912993168705942035497262087604457828016897033541606942408964421467661323530702416001851055818803331278149668787143629857676822265398153269496232656278975610802921303671791426728632525217213666490425139054750899596417296214549901614709644307007461708968510489409278966392105040423902797155302293, 2041454339352622193656627164408774503102680941657965640324880658919242765901541504713444825283928928662755298871656269360429687747026596290805541345773049732439830112665647963627438433525577186905830365395002284129, (4957181230366693742871089608567285130576943723414681430592899115510633732100117146460557849481224254840925101767808247789524040371495334272723624632991086495766920694854539353934108291010560628236400352109307607758762704896162926316651462302829906095279281186440520100069819712951163378589378112311816255944, 2715356151156550887523953822376791368905549782137733960800063674240100539578667744855739741955125966795181973779300950371154326834354436541128751075733334790425302253483346802547763927140263874521376312837536602237535819978061120675338002761853910905172273772708894687214799261210445915799607932569795429868 ), 70953285682097151767648136059, ), ] HINTSIZE = 96 def decrypt(c, d, n): n = int(n) size = n.bit_length() // 2 c_high, c_low = c b = (c_low**2 - c_high**3) % n EC = EllipticCurve(Zmod(n), [0, b]) m_high, m_low = (EC((c_high, c_low)) * d).xy() m_high, m_low = int(m_high), int(m_low) return (m_high << size) | m_low hintmod = 2**HINTSIZE todec = masked_flag for data in ciphertexts: n, e, c, hint = data c_high, c_low = c for f in (e / QQ(n)).continued_fraction().convergents(): y = f.numerator() x = f.denominator() if is_prime(x) and is_prime(y): print("good", x, y) break plo = hint qlo = n * inverse_mod(plo, hintmod) % hintmod slo = (plo + qlo) % hintmod assert plo * qlo % hintmod == n % hintmod a = e * x - (n + 1) * y z_mod_y = (-a) % y z_mod_hintmod = (-a + slo * y) % hintmod midmod = hintmod * y zmid = crt([z_mod_y, z_mod_hintmod], [y, hintmod]) aa = a - slo * y + zmid assert aa % midmod == 0 aa //= midmod # shi = (p + q) // hintmod # zhi is ~216 bits # assert shi == aa + zhi sumpq = aa * hintmod eps = 2**216 * hintmod rsa = RSA(n) pbound, qbound = rsa.bound_primes_from_approximate_sum( sumpq - eps, 2 * eps) try: print("factor1") p, q = rsa.factor_with_prime_hint(low_mod=(plo, hintmod), bounds=pbound, beta=0.49) except RuntimeError: print("factor2") p, q = rsa.factor_with_prime_hint(low_mod=(qlo, hintmod), bounds=pbound, beta=0.49) print("ok!") d = inverse_mod(e, n + p + q + 1) mask = decrypt(c, d, n) todec ^= mask assert Bin(todec).bytes == b'SECCON{gut_poweeeeeeeeeeeeeer}'