def printset(s): for c in s: fiout.write(gmpy2.digits(c, 2).zfill(MAXLEN) + "\n") supcal = gmpy2.digits(c, 2).zfill(MAXLEN) tmp = genroot.getsup(supcal) retstr = "%s,%s,%.2f" % (tmp[0], supcal, tmp[1]) rettt.append(retstr)
def coin_jam(bits, m): FIRST_NUMBER = 2**(bits - 1) + 1 LAST_NUMBER = 2**(bits) - 1 n = FIRST_NUMBER c = 1 while n < LAST_NUMBER and c <= m: l = [] base = 10 is_prime = False while base >= 2: base_n = int(str(gmpy2.digits(n, 2)), base) if gmpy2.is_prime(base_n): is_prime = True break l.append(base_n) base -= 1 # Find non trivial divisors if not is_prime: l.append(gmpy2.digits(n, 2)) for (i, b) in enumerate(l[:9]): divisor = 2 while divisor < b: if b % divisor == 0: l[i] = divisor break divisor += 1 print(' '.join(map(str, l[::-1]))) c += 1 n += 2
def gen_rule(r, k, ruleNum): rule = {} hood = 2 * r + 1 bruleNum = digits(ruleNum, k).zfill(k ** hood)[::-1] for s in range(k ** hood): rule[digits(s, k).zfill(hood)] = int(bruleNum[s]) return rule
def generate_public_key(self, slot_index): slot_mpk = self.generate_common_public_key() if slot_index in self.msk['w'] and slot_index in self.msk['u']: slot_mpk['w'] = [gp.digits(i) for i in self.msk['w'][slot_index]] slot_mpk['u'] = [gp.digits(i) for i in self.msk['u'][slot_index]] return slot_mpk else: logger.error('the slot id is not found.') return None
def generate_public_key(self, vec_size): assert vec_size <= self.eta pk = dict() pk['bound'] = vec_size pk['g'] = gp.digits(self.mpk['g']) pk['p'] = gp.digits(self.mpk['p']) pk['pk'] = list() for i in range(vec_size): pk['pk'].append(gp.digits(self.mpk['pk'][i])) return pk
def _solve_dlog(self, p, g, h, dlog_max): """ Attempts to solve for the discrete log x, where g^x = h mod p via hash table. """ if self.dlog_table is not None: if gp.digits(h) in self.dlog_table: return self.dlog_table[gp.digits(h)] else: return self._solve_dlog_naive(p, g, h, dlog_max)
def generate_common_public_key(self): g_w = self.mpk['g_w'] g_w_digits = dict() for idx in g_w.keys(): g_w_digits[idx] = [gp.digits(j) for j in g_w[idx]] return { 'g': gp.digits(self.mpk['g']), 'p': gp.digits(self.mpk['p']), 'sec_param': self.mpk['sec_param'], 'g_w': g_w_digits }
def _solve_dlog(self, p, g, h, dlog_max): """ Attempts to solve for the discrete log x, where g^x = h mod p via hash table. """ if self.dlog_table is not None: if gp.digits(h) in self.dlog_table: return self.dlog_table[gp.digits(h)] else: logger.warning("did not find f in dlog table, may cost more time to compute") return self._solve_dlog_naive(p, g, h, dlog_max)
def buy(self, num, rt): if self.balance >= num * 1000: x = self.x y = rt.eval_at(x) code = '%s-%s-%s' % (gmpy2.digits(num, 10), gmpy2.digits(x, 62), gmpy2.digits(y, 62)) self.balance -= num * 1000 print '[+] Terima kasih telah membeli %d Hackcoin!' % (num) print '[+] Redeem Code untuk %d Hackcoin anda:' % (num) print '[+] %s' % (code) self.x = pow(self.x, 31337, PRIME) else: print '[-] Saldo anda tidak mencukupi!'
def q4(): c = mpz('22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256' + '46583996794288946076454204058156474898801373486412045232522932017648791666640299750918872997169052608322206777160001932' + '9260870009579993724077458967773697817571267229951148662959627934791540') n = mpz('17976931348623159077293051907890247336179769789423065727343008115' + '77326758055056206869853794492129829595855013875371640157101398586' + '47833778606925583497541085196591615128057575940752635007475935288' + '71082364994994077189561705436114947486504671101510156394068052754' + '0071584560878577663743040086340742855278549092581') e = mpz(65537) a = isqrt(n) + 1 x = isqrt(a**2 - n) p = a - x q = a + x fi = (p-1) * (q-1) d = invert(e, fi) r = powmod(c, d, n) m = digits(r, 16).split('00')[1] return m.decode('hex')
def generate_private_key(self, vec): assert len(vec) <= self.eta sk = gp.mpz(0) for i in range(len(vec)): sk = gp.add(sk, gp.mul(self.msk[i], vec[i])) return {'bound': len(vec), 'sk': gp.digits(sk)}
def q4(): c = mpz( '22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256' + '46583996794288946076454204058156474898801373486412045232522932017648791666640299750918872997169052608322206777160001932' + '9260870009579993724077458967773697817571267229951148662959627934791540' ) n = mpz( '17976931348623159077293051907890247336179769789423065727343008115' + '77326758055056206869853794492129829595855013875371640157101398586' + '47833778606925583497541085196591615128057575940752635007475935288' + '71082364994994077189561705436114947486504671101510156394068052754' + '0071584560878577663743040086340742855278549092581') e = mpz(65537) a = isqrt(n) + 1 x = isqrt(a**2 - n) p = a - x q = a + x fi = (p - 1) * (q - 1) d = invert(e, fi) r = powmod(c, d, n) m = digits(r, 16).split('00')[1] return m.decode('hex')
def getnum(): for c in A: bisect.insort_left(result, c) while len(A) > 0: minvalue = min(A) A.remove(minvalue) tm_ti = time.clock() keypos = bisect.bisect_right(result, minvalue) cp_result = copy.copy(result[keypos:]) tm_ti = time.clock() for c in cp_result: tmp = c | minvalue use_tmp = gmpy2.digits(tmp, 2) use_tmp = "0" * (genroot.prp_num - len(use_tmp)) + use_tmp if (genroot.getsup(use_tmp))[1] < sup_f: continue if tmp == c: continue if tmp >= MAXVALUE: break pos = bisect.bisect_right(result, tmp) if result[pos - 1] != tmp: bisect.insort_left(result, tmp) print("Topology numbers:", len(result), 'used time for sort:%.3f seconds' % (time.clock() - tm_ti))
def getBaseKDigitList(n, base, dropZeroes=False): if 1 < base < 63: if n < 0: raise ValueError( '\'get_base_k_digits\' does not support negative numbers.') asciiDigits = gmpy2.digits(int(n), int(base)) digits = [] ord0 = ord('0') orda = ord('a') ordA = ord('A') for i in asciiDigits: if '0' <= i <= '9': digits.append(ord(i) - ord0) elif 'a' <= i <= 'z': digits.append(ord(i) - orda + 10) else: digits.append(ord(i) - ordA + 36) else: digits = convertToBaseN(n, base, outputBaseDigits=True) result = [] for digit in digits: if dropZeroes and digit == 0: continue result.append(digit) return result
def encrypt(self, pk, vec): assert len(vec) == pk['bound'] p = gp.mpz(pk['p']) g = gp.mpz(pk['g']) r = _random(p, self.sec_param) ct0 = gp.digits(gp.powmod(g, r, p)) ct_list = [] for i in range(len(vec)): ct_list.append(gp.digits( gp.mul( gp.powmod(gp.mpz(pk['pk'][i]), r, p), gp.powmod(g, gp.mpz(int(vec[i])), p) ) )) return {'ct0': ct0, 'ct_list': ct_list}
def generate_config_files(sec_param, sec_param_config, dlog_table_config, func_bound): p, q, r = _param_generator(sec_param) g = _random_generator(sec_param, p, r) group_info = {'p': gp.digits(p), 'q': gp.digits(q), 'r': gp.digits(r)} sec_param_dict = { 'g': gp.digits(g), 'sec_param': sec_param, 'group': group_info } with open(sec_param_config, 'w') as outfile: json.dump(sec_param_dict, outfile) logger.info( 'Generate secure parameters config file successfully, see file %s' % sec_param_config) dlog_table = dict() bound = func_bound + 1 for i in range(bound): dlog_table[gp.digits(gp.powmod(g, i, p))] = i for i in range(-1, -bound, -1): dlog_table[gp.digits(gp.powmod(g, i, p))] = i dlog_table_dict = { 'g': gp.digits(g), 'func_bound': func_bound, 'dlog_table': dlog_table } with open(dlog_table_config, 'w') as outfile: # outfile.write(_json_zip(dlog_table_dict)) json.dump(dlog_table_dict, outfile) logger.info('Generate dlog table config file successfully, see file %s' % dlog_table_config)
def is_double_base_hui_wen(num): counts = 0 for base in range(2, 11): string = gmpy2.digits(num, base) if is_hui_wen(string): counts += 1 if counts >= 2: return True return False
def __init__(self,val=''): """ initialize the class. val may assume either string or integer representation. Integer decomposition is performed by gmpy2. """ if isinstance(val,str): self.label = val # must be a string '0101110001' else: self.label =gmpy2.digits(val,Configuration.base).zfill(Configuration.dimension)
def front(): if request.method == 'POST': rc = [session['rw'][0].upper(), session['rw'][1], session['rw'][2]] # Ensure CSRF token is set if (request.form.get('csrf_token') != session['csrf_token']) or \ (request.form.get('hp')): flash('You look like a bot', category='error') # Ensure reality check passes elif request.form.get('reality_check').split() != rc: flash('bad reality check {} != {}'.format( request.form.get('reality_check').split(), rc), category='error') else: # Open DB db = sqlite3.connect('shorturls.db') # If asked for a custom source, check if it exists source = None exists = 0 if request.form.get('custom'): source = request.form.get('custom_path') exists = db.execute( 'select count(*) from shorturls where shorturl = ?', (request.form.get('custom_path'), )).fetchone()[0] # Bail if the source exists if exists != 0: flash('custom path exists', category='error') # Set source if not else: # Create a short URL without a source cur = db.cursor() result = cur.execute( ''' insert into shorturls (destination) values (?) ''', (request.form.get('destination'), )) db.commit() # Set source to id if no source was given if not source: source = gmpy2.digits(result.lastrowid, 62) cur.execute( ''' update shorturls set shorturl = ? where id = ? ''', (source, result.lastrowid)) db.commit() flash(''' Your domain is <a href="{base}{path}"">{base}{path}</a>'''. format(base=app.config['BASE'], path=source), category='success') session['csrf_token'] = hashlib.sha1(os.urandom(40)).hexdigest() session['rw'] = RandomWords().random_words(count=3) return render_template('front.html', csrf_token=session['csrf_token'], rw=session['rw'])
def __repr__(self): if NC.display: f = gmpy2.mpfr(self.n) t = gmpy2.digits(f, 10, 5) return '0.%se%s' % (t) elif self.n / NC.threshold < 1: return str(self.n) else: return '<BIG_NUM>'
def __init__(self, val=''): """ initialize the class. val may assume either string or integer representation. Integer decomposition is performed by gmpy2. """ if isinstance(val, str): self.label = val # must be a string '0101110001' else: self.label = gmpy2.digits(val, Configuration.base).zfill( Configuration.dimension)
def part4(): e = gmpy2.mpz(65537) a = gmpy2.isqrt(N) + 1 x = gmpy2.isqrt(a**2 - N) p = a - x q = a + x fi = (p - 1) * (q - 1) d = gmpy2.invert(e, fi) r = gmpy2.powmod(C, d, N) m = gmpy2.digits(r, 16).split('00')[1] return bytearray.fromhex(m).decode()
def generate_private_key(self, vec, parties): vec_parties = self._split_vector(vec, parties) d = dict() z = gp.mpz(0) for idx in parties.keys(): if idx in self.msk['w'] and idx in self.msk['u']: w_idx = self.msk['w'][idx] u_idx = self.msk['u'][idx] vec_idx = vec_parties[idx] vec_w_idx = gp.mpz(0) for j in range(parties[idx]): vec_w_idx = vec_w_idx + gp.mul(gp.mpz(vec_idx[j]), w_idx[j]) d[idx] = gp.digits(vec_w_idx) for j in range(parties[idx]): z = z + gp.mul(gp.mpz(vec_idx[j]), u_idx[j]) else: logger.error('the id %s in parties is not found.' % idx) return {'d': d, 'z': gp.digits(z)}
def encrypt(self, slot_pk, vec): assert len(vec) <= len(slot_pk['u']) assert len(vec) <= len(slot_pk['w']) p = gp.mpz(slot_pk['p']) g = gp.mpz(slot_pk['g']) sec_param = slot_pk['sec_param'] u = slot_pk['u'] w = slot_pk['w'] r = _random(p, sec_param) t = gp.digits(gp.powmod(g, r, p)) c = [ gp.digits( gp.powmod( g, gp.mpz(vec[i]) + gp.mpz(u[i]) + gp.mul(gp.mpz(w[i]), r), p)) for i in range(len(vec)) ] return {'t': t, 'c': c}
def inttopoly(num, base): ''' Converts an int number into a polynomial, representing num in another numeral system. :param num: integer number to convert. :param base: base number of the numeral system. :return: numpy.polynomial.Polynomial object, representing integer num in the numeral system with base number base. ''' coeffs = [] new_num = gmpy2.digits(num, base) for digit in new_num: coeffs = [int(digit)] + coeffs return npp.Polynomial(coeffs)
def add_dct_data(cardpaths): """ sock away top and bottom dcts of pics as a persistent 64-bit int cardpaths = {card['id']: os.path.join(__local_dir__, card['pic_path']), card['id']: None, ...} cardpaths should be drawn from card_db where they are already vetted """ datas = [] counter = 0 print("Calculating DCT data for {} items...".format(len(cardpaths))) for idc, fsp in cardpaths.viewitems(): #id, top_dct, picpath, face current_card = orient_db.cur.execute("SELECT id, top_dct FROM orient WHERE id=(?)", (idc,)).fetchone() #print "AFF", fsp, current_card if fsp and not current_card['top_dct']: counter += 1 if not (counter % 200): print("{} new pics dct'd".format(counter)) shortpath = os.path.sep.join(fsp.split(os.path.sep)[-2:]) im = cv2.equalizeHist(cv2.imread(fsp, cv2.IMREAD_GRAYSCALE)) try: flim = im[::-1, ::-1] height, width = im.shape[:2] datas.append({'id': idc, 'picpath': shortpath, 'top_dct': gmpy2.digits(dct_hint(im[:width * __RAT__, :])), 'bot_dct': gmpy2.digits(dct_hint(flim[:width * __RAT__, :]))}) except TypeError as e: print("{} No picture was loaded for path: {}".format(e, fsp)) print("{} new pics dct'd".format(counter)) print("adding {} new lines of data to orient from {} card-paths".format(len(datas), len(cardpaths))) if datas: orient_db.add_data(datas, 'orient', 'id') print("committed!") q = orient_db.cur.execute("SELECT id FROM orient").fetchall() print("there are now {} lines in orient".format(len(q))) return datas
def getsup(obj): sups = "1" * obj_num sups_gmp = gmpy2.mpz(sups, 2) for i in range(0, len(obj)): if obj[i] == '1': sups_gmp &= gmpy2.mpz(fac_ver[i], 2) sups_gmp = gmpy2.digits(sups_gmp, 2) tmp_lie = "0" * (obj_num - len(sups_gmp)) + sups_gmp object_ss.append(tmp_lie) total_one = 0 for i in range(0, len(sups_gmp)): if sups_gmp[i] == '1': total_one += 1 return tmp_lie, round(total_one * 1.0 / obj_num, 6)
def q4(p,q,n): c = gmpy2.mpz('22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256' + '46583996794288946076454204058156474898801373486412045232522932017648791666640299750918872997169052608322206777160001932' + '9260870009579993724077458967773697817571267229951148662959627934791540') e = gmpy2.mpz(65537) fi = gmpy2.mul(gmpy2.sub(p,1) , gmpy2.sub(q,1)) d = gmpy2.invert(e, fi) r = gmpy2.powmod(c, d, n) m = gmpy2.digits(r, 16).split('00')[1] return m.decode('hex')
def main(): print "Case #1:" lower = 2 ** (N - 1) + 1 upper = 2 ** N - 1 coins = [] current = upper while len(coins) < J: assert current >= lower base2str = digits(current, 2) if none_prime(base2str): try: divisors = list(find_divisors(base2str)) coins.append((base2str, divisors)) print "{} {}".format(base2str, ' '.join(divisors)) except RuntimeError: pass current -= 2
def solve(): N_str = "11111111111" C_str = "11111111111" N = gmpy2.mpz(N_str) c = gmpy2.mpz(C_str) e = gmpy2.mpz('65537') phi = gmpy2.mpz(find_phi(N)) if phi is None: print 'Failed to factorize N' return None print 'N factorized.' d = gmpy2.invert(e, phi) print 'd found. Decrypting message ...' m = gmpy2.powmod(c, d, N) return binascii.unhexlify(gmpy2.digits(m, 16))
def base62_decode(cipher, print_info=""): if ("" != print_info): print("--------" + print_info.center(30) + "--------: ", end="") try: result = '' strlen = len(cipher) for i in range(0, strlen, 11): x = slice(i, i + 11) chunk = str(cipher)[x] outlen = math.floor((len(chunk) * 6) / 8) number = chunk.lstrip('0') if ('' == number): number = '0' y = gmpy2.digits(gmpy2.mpz(number, 62), 16) pad = y.zfill(outlen * 2) result += binascii.unhexlify(pad.encode()).decode() return result except: return None
def q4(p, q, n): c = gmpy2.mpz( '22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256' + '46583996794288946076454204058156474898801373486412045232522932017648791666640299750918872997169052608322206777160001932' + '9260870009579993724077458967773697817571267229951148662959627934791540' ) e = gmpy2.mpz(65537) fi = gmpy2.mul(gmpy2.sub(p, 1), gmpy2.sub(q, 1)) d = gmpy2.invert(e, fi) r = gmpy2.powmod(c, d, n) m = gmpy2.digits(r, 16).split('00')[1] return m.decode('hex')
def api(): db = sqlite3.connect('shorturls.db') key = request.args.get('key') # If there's no key, it's probably just the short URL /api if key is None: result = db.execute( 'select destination from shorturls where shorturl = ?', ('api', )).fetchone() # If it doesn't exist, abort; otherwise, redirect if result is None: abort(404) return redirect(result[0]) # Otherwise it's probably an API request api_success = db.execute('select count(*) from apikeys where key = ?', (key, )).fetchone()[0] if api_success != 0: # Create a short URL without a source cur = db.cursor() result = cur.execute( ''' insert into shorturls (destination) values (?) ''', (request.args.get('destination'), )) db.commit() # Set source to id if no source was given source = gmpy2.digits(result.lastrowid, 62) cur.execute( ''' update shorturls set shorturl = ? where id = ? ''', (source, result.lastrowid)) db.commit() flash(''' Your domain is <a href="{base}{path}">{base}{path}</a>'''.format( base=app.config['BASE'], path=source), category='success') else: flash('Invalid API key', category='error') return redirect('/')
def _decode_int_to_ACGT(the_int, seq_len): """ bustools encodes sequences as integers, this function decodes the ints into their sequence """ assert the_int >= 0 # the follwing line is a major performance HOG: # seq_decode = np.base_repr(the_int, 4) # seq_decode is a str: '10012031...' seq_decode = gmpy2.digits(the_int, 4) # the coding does not recognize leading 0 (adenines) # hence we pad 0 until we have the correct number of bases seq_decode_pad = seq_decode.zfill(seq_len) assert len( seq_decode_pad) == seq_len, f'{len(seq_decode_pad)} vs {seq_len}' seq_str = seq_decode_pad.replace('0', 'A').replace('1', 'C').replace( '2', 'G').replace('3', 'T') return seq_str
def get_representative(val, p=0): """ return the representative configuration of val with eigennumber p. This function explores the correspondence between finite groups {O} and permutation operations. Given a single state S (for instance '0101'), the linear combination with eigenvalue p is obtained by (1/Normalization) sum_k ([p Ô]^k S. We define the representative configuration as the state with lowest integer Ex: (base 2) state representative (p=0 and N=4) 1000 0001 0100 0001 0101 0101 1010 0101 """ #first let us consider only p=0 (no null norm) if isinstance(val, str): val = int(val, SymConf.base) rep = val current = val repetition = 1 for k in range(SymConf.dimension - 1): new = current * SymConf.base shift, current = divmod(new, SymConf.basemax) current = current + shift if not (current > rep): repetition = repetition + max(0, 1 - abs(rep - current)) rep = current return gmpy2.digits(rep, SymConf.base).zfill( SymConf.dimension), rep, repetition
def hastadAttack(n1, n2, n3, c1, c2, c3): e = 3 M = n1 * n2 * n3 m1 = M / n1 m2 = M / n2 m3 = M / n3 t1 = c1 * (m1) * gmpy2.invert(m1, n1) t2 = c2 * (m2) * gmpy2.invert(m2, n2) t3 = c3 * (m3) * gmpy2.invert(m3, n3) print("t3 = {}".format(t3)) print "\n" x = (t1 + t2 + t3) % M # chinese reminder theorem print("x = {}".format(x)) print "\n" m, exact = gmpy2.iroot(x, e) # recover m print exact if exact: print binascii.unhexlify(gmpy2.digits( m, 16)) # convert int -> hex -> ascii
def inttopoly(num, base): ''' Converts an int number into a polynomial, representing num in another numeral system. :param num: integer number to convert. :param base: base number of the numeral system. :return: numpy.polynomial.Polynomial object, representing integer num in the numeral system with base number base. ''' coeffs = [] sign = 1 if num < 0: sign = -1 num *= -1 new_num = gmpy2.digits(num, base) for digit in new_num: if not digit.isdigit(): d = ord(digit.lower()) - ord('a') + 10 else: d = int(digit) coeffs = [sign * d] + coeffs return npp.Polynomial(coeffs)
break #if g == N: brent(N) #return g if g!=N: return g else: return brent(N) print "Case #1: " count = 0 #for i in range(9, 100, 2): for i in xrange(2147483649, 4294967296, 2): #print i l = [] for j in xrange(2,11): b = gmpy2.digits(i,2) a = int(b,j) if gmpy2.is_prime(a): break l.append(a) if len(l)==9: ll = [] #print i, l for i in xrange(len(l)): ll.append(brent(l[i])) #ll.append(brent(1029)) # for j in xrange(2,int(math.sqrt(l[i]))): # if l[i] % j == 0: # ll.append(j) # break print b, ' '.join(str(x) for x in ll) count += 1
h = gmpy2.mpz('3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333') g = gmpy2.mpz('11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568') B = 2**20 #buidling the table tbl = {} x1 = 0 x0 = 0 for i in range(0, B): tmp = gmpy2.powmod(g, i, p) #get g^x1 tmp = gmpy2.invert(tmp, p) #get (g^x1)^-1 tmp = gmpy2.t_mod(gmpy2.mul(h, tmp), p) hash = MD4.new(gmpy2.digits(tmp)) tbl[hash.hexdigest()] = i #start bruteforcing for i in range(0, B): tmp = gmpy2.powmod(g, gmpy2.mul(B, i), p) hash = MD4.new(gmpy2.digits(tmp)) if hash.hexdigest() in tbl: x1 = tbl[hash.hexdigest()] x0 = i break res = (x0*B) + x1 print(res) print(x0)