def elemop(N=1000): r''' (Takes about 40ms on a first-generation Macbook Pro) ''' for i in range(N): assert a+b == 579 assert a-b == -333 assert b*a == a*b == 56088 assert b%a == 87 assert divmod(a, b) == (0, 123) assert divmod(b, a) == (3, 87) assert -a == -123 assert pow(a, 10) == 792594609605189126649 assert pow(a, 7, b) == 99 assert cmp(a, b) == -1 assert '7' in str(c) assert '0' not in str(c) assert a.sqrt() == 11 assert _g.lcm(a, b) == 18696 assert _g.fac(7) == 5040 assert _g.fib(17) == 1597 assert _g.divm(b, a, 20) == 12 assert _g.divm(4, 8, 20) == 3 assert _g.divm(4, 8, 20) == 3 assert _g.mpz(20) == 20 assert _g.mpz(8) == 8 assert _g.mpz(4) == 4 assert a.invert(100) == 87
def __add__(self, Q): if isinstance(Q, Ideal): return self x1, y1, x2, y2 = self.x, self.y, Q.x, Q.y lambda1 = 0 if (x1, y1) == (x2, y2): if y1 == 0: return Ideal(self.curve) lambda1 = divm((3 * powmod(x1, 2, self.mod) + self.curve.a), (2 * y1), self.mod) else: try: lambda1 = divm((y2 - y1), (x2 - x1), self.mod) except ZeroDivisionError: # print "x1-x2" # print x2-x1 return x2 - x1 x3 = (powmod(lambda1, 2, self.mod) - x1 - x2) % self.mod y3 = (lambda1 * (x1 - x3) - y1) % self.mod return Point(self.curve, x3, y3)
def decrypt(self, common_pk, sk, vec, ct, max_inner_prod): assert len(ct['ct_dict']) == len(sk['d']) p = gp.mpz(common_pk['p']) g = gp.mpz(common_pk['g']) z = gp.mpz(sk['z']) d = sk['d'] vec_parties = self._split_vector(vec, ct['parties']) ct_dict = ct['ct_dict'] g_f = gp.mpz(1) for idx in ct_dict.keys(): vec_idx = vec_parties[idx] c_idx = ct_dict[idx]['c'] t_idx = ct_dict[idx]['t'] d_idx = d[idx] assert len(vec_idx) == len(c_idx) init_idx = gp.mpz(1) for j in range(len(c_idx)): init_idx = gp.mul( init_idx, gp.powmod(gp.mpz(c_idx[j]), gp.mpz(vec_idx[j]), p)) g_f = gp.mul( g_f, gp.divm(init_idx, gp.powmod(gp.mpz(t_idx), gp.mpz(d_idx), p), p)) g_f = gp.divm(g_f, gp.powmod(g, z, p), p) f = self._solve_dlog(p, g, g_f, max_inner_prod) return f
def verifysignature(curve, pubkey, signature, message, hashalgo=SHA): pkobj = (bytes2int(pubkey[0]), bytes2int(pubkey[1])) publickeypoint = ec.PointJ(curve, pkobj) n = curve.params.order if isinstance(message, str): message = message.encode('UTF-8') h = hashalgo.new(message).digest() e = mpz(int.from_bytes(h[:n.bit_length()], byteorder='big')) # bits de gauche de e r, s = signature u1 = gmpy2.divm(e, s, n) u2 = gmpy2.divm(r, s, n) resultpoint = curve.g * u1 + publickeypoint * u2 v = resultpoint.affine()[0] % n return v == r # on doit avoir r ≡ x1 (mod n)
def _deblind_signed_id_batch(signed_blinded_hashed_ids, blind_numbers, n): signed_hashed_ids = [divm(x, r, n).digits() for x, r in zip(signed_blinded_hashed_ids, blind_numbers)] hashed_signed_hashed_ids = \ PsiRsaSigner._crypto_hash_list(signed_hashed_ids) return hashed_signed_hashed_ids
def challenge(p, g, h): # Equation: # [h/g^(x1) = (g^B)^x0] in Zp B = pow(2, 20) # Compute hash table of values for: # h/g^(x1) hashTableX1 = {} for x1 in range(B): x = gmpy2.divm(h, gmpy2.powmod(g, x1, p), p) hashTableX1[x] = x1 print("Pre compute complete!") # Compare values by computing # (g^B)^x0 for x0 in range(B): t = gmpy2.mpfr(gmpy2.powmod(gmpy2.powmod(g, B, p), x0, p)) % p if t in hashTableX1: x1 = hashTableX1[t] # Calculates x x = x0 * B + x1 print("Value found!") print(x) break else: print("## No value found! ##")
def gen_hash_table(numiter): hash_table = {} hash_table[0] = gmpy2.f_mod(h1,p1) r = gmpy2.divm(h1,g1,p1) aux2 = gmpy2.divm(mpz(1),g1,p1) for i in range(1,numiter+1): if i == 1: aux = gmpy2.f_mod(gmpy2.mul(r,1),p1) else: aux = gmpy2.f_mod(gmpy2.mul(r,aux2),p1) hash_table[aux] = i r = aux return hash_table
def predict_next(self): results = self.gen.next_N(10) diffs = list(self.get_diffs(results)) # d2*d0 = a*d1 * d0 = a*a*d0*d0 # d1*d1 = a*d0 * a*d0 = a*a*d0*d0 # ... zeroes = list(self.get_zeros(diffs)) # each number on the list mod m = 0 # 0 = zeroes[0] mod m = k0 * m # 0 = zeroes[1] mod m = k1 * m # ... m = reduce(gcd, zeroes) # print(m) a = gmpy2.divm(diffs[1], diffs[0], m) b = (results[1] - results[0]* a) % m # # print(a) # # print(b) prediction = (a*results[len(results)-1] + b)%m return prediction
def c_s_k_ske(self,x2): self.x121=gmpy2.powmod(x2,self.k11,self.p) if(gmpy2.is_even(self.x121)): self.e2=gmpy2.sub(self.x121,1) else: self.e2=self.x121 self.d2=gmpy2.divm(1,self.e2,gmpy2.sub(self.p,1))
def discrete_log(p, g, h, max_x=2**40): """ (mpz, mpz, mpz) -> mpz Given prime p and integer g, h in [0, p-1] which fit the equation that h = g ** x (mod p) where 1 <= x <= 2 ** 40. Return the discrete log, i.e. x Here this program use a trick to avoid brute force computation of all max_x possibilities. Instead the time consumed is O(max_x ** 0.5). Let b equals max_x ** 0.5 and x = x0 * b + x1 where x0, x1 are in the range [0, b-1]. Then h = g ** x (mod p) = g ** (x0 * b + x1) (mod p) = g ** (x0 * b) * g ** x1 (mod p). By moving the g ** x1 to left, we obtain h / g ** x1 = g ** (x0 * b) (mod p). For every possible x1 in [0, b-1], we hash the left as key and x1 as value to a hash table. Then for every possible x0, we calculate if the right is in this hash table. If so, we get the right pair of x0 and x1 as x can be calculated. >>> discrete_log(mpz(1073676287), mpz(1010343267), mpz(857348958)) 1026831 :param p: a multi-precision prime :param g: a multi-precision integer :param h: a multi-precision integer :param max_x: the max possible number of x :return: the discrete log x """ b = int(max_x**0.5) hash_table = {} for x1 in range(b): temp = divm(h, powmod(g, x1, p), p) hash_table[temp] = x1 for x0 in range(b): temp = powmod(g, x0 * b, p) if temp in hash_table: x1 = hash_table[temp] break x = x0 * b + x1 return x
def build_table(self, start=1, end=B): g_x1 = gmpy2.powmod(self.g, start, self.p) for x1 in xrange(start, end): lhs = gmpy2.divm(self.h, g_x1, self.p) self.lookup_table[lhs] = x1 if (x1 % self.CHECKPOINT) == 0: self.log.print_progress(x1) g_x1 = gmpy2.f_mod(gmpy2.mul(g_x1, self.g), self.p)
def c_s_k_sbox(self,x2): self.x21=gmpy2.powmod(x2,self.k1,self.p) if(gmpy2.is_even(self.x21)): self.e1=gmpy2.sub(self.x21,1) self.x(self.e1) else: self.e1=self.x21 self.x(self.e1) self.d1=gmpy2.divm(1,self.e1,gmpy2.sub(self.p,1))
def computeLHS(): for i in range(0, B): gx1 = gmpy2.divm(h, gmpy2.powmod(g, i, p), p) #calculat g pow i mod p for range 0-B try: LHS[gx1] = LHS[gx1] + i except Exception: LHS[gx1] = i print("Finished LHS") return
def dec(ct, k): a = a2i(ct) b = 0 while a: x = a % P # Solve for pt x = gmpy2.divm(x - B * k, A, P) b *= P b += x a /= P return i2a(b)
def dlog(prime, g, h): CONST_2_20 = 2 ** 20 h_x1 = {} for x1 in xrange(CONST_2_20 + 1): val = divm(h, powmod(g, x1, prime), prime) h_x1[val] = x1 gb = powmod(g, CONST_2_20, prime) for x0 in xrange(CONST_2_20 + 1): val = powmod(gb, x0, prime) if val in h_x1: x1 = h_x1[val] x = x0 * CONST_2_20 + x1 print x break
def getIntermidiateX(p, g, h): table = {} for x1 in range(0, 2 ** 20 + 1): denominator = powmod(g, x1, p) division = divm(h, denominator, p) table[division] = x1 # print division for x0 in range(0, 2 ** 20 + 1): rightHandSide = mpz(powmod(powmod(g, B, p), mpz(x0), p)) # print rightHandSide if rightHandSide in table: print "Win x0={0}, x1={1}".format(x0, table[rightHandSide]) return x0, table[rightHandSide]
def meetinthemiddle_calculate(p, g, h, maxexp=40): B = gmpy2.mpz(2**(maxexp/2)) g = gmpy2.mpz(g) h = gmpy2.mpz(h) p = gmpy2.mpz(p) middle = {} for x1 in range(B): middle[gmpy2.divm(h, gmpy2.powmod(g, x1, p), p)] = x1 for x0 in range(B): v = gmpy2.powmod(g, B*x0, p) if middle.has_key(v): x1 = middle[v] return B*x0+x1 return None
def decrypt(self, pk, sk, vec, ct, max_innerprod): p = gp.mpz(pk['p']) g = gp.mpz(pk['g']) res = gp.mpz(1) for i in range(len(vec)): res = gp.mul( res, gp.powmod(gp.mpz(ct['ct_list'][i]), gp.mpz(vec[i]), p) ) res = gp.t_mod(res, p) g_f = gp.divm(res, gp.powmod(gp.mpz(ct['ct0']), gp.mpz(sk['sk']), p), p) f = self._solve_dlog(p, g, g_f, max_innerprod) return f
def dlog(pgh): p = pgh[0] g = pgh[1] h = pgh[2] B = gmpy2.powmod(2,20,mpz(p)) B_low = 0 #B_low = gmpy2.powmod(2,18,mpz(p)) print "B: " + repr(B) # build the hash hash_table = {} for i in range(B_low,B): left = gmpy2.divm(mpz(h),gmpy2.powmod(mpz(g),i, mpz(p)),mpz(p)) try: hash_table[left] print "collision at " + i except KeyError: hash_table[left] = i continue print "Hash table built" #print "keys: " + repr(hash_table.keys()) counter = mpz(0) # meet in the middle x0 = mpz(0) x1 = mpz(0) for i in range(B_low,B): counter = gmpy2.add(counter,mpz(1)) right = gmpy2.powmod(gmpy2.powmod(mpz(g),mpz(B),mpz(p)),i,mpz(p)) try: h_entry = hash_table[right] print 'found x0 and x1...' x0 = i x1 = h_entry print 'x0=' + repr(x0) print 'x1=' + repr(x1) break except KeyError: continue print "counter: " + repr(counter) x = gmpy2.t_mod(gmpy2.add(gmpy2.mul(x0,B),x1), mpz(p)) return x
def sign(entity: ECEntity, message, hashalgo=SHA): if isinstance(message, str): message = message.encode('UTF-8') h = hashalgo.new(message).digest() n = entity.curve.params.order e = mpz(int.from_bytes(h[:n.bit_length()], byteorder='big')) # bits de gauche de e while True: k = Sr().randint(1, n - 1) p1 = entity.curve.g * k r = p1.affine()[0] % n if r == 0: continue s = gmpy2.divm(e + entity.secret * r, k, n) if s == 0: continue return int(r), int(s)
def process_host_guest_idx(self, host_idx, guest_idx_host): ''' :param host_idx = [hash(hash(host_uer_id)^d % n)] :param guest_idx_host = [r * (hash(guest_user_id)^d % n)] :return: (encrypted_intersect_idx, raw_intersect_idx), encrypted_intersect_idx = hash(hash(intersect_user_id)^d % n) ''' print('Process host and guest encrypted idx at guest') n = self.rsa_public_key.n # guest_idx_dec = ([hash(hash(guest_user_id)^d % n)] guest_idx = list( map(lambda x: IntersectTools.hash(gmpy2.divm(x[0], x[1], n)), zip(guest_idx_host, self.random_r))) # intersect_idx_map = {encrypted guest id : raw guest id} intersect_idx_map = dict(zip(guest_idx, self.dataset)) intersect_idx_enc = set(host_idx) & set(guest_idx) intersect_idx_raw = set( map(lambda x: intersect_idx_map[x], intersect_idx_enc)) return (intersect_idx_enc, intersect_idx_raw)
def calculate(p,g,h): B = gmpy2.mpz(2**20) p = gmpy2.mpz(p) g = gmpy2.mpz(g) h = gmpy2.mpz(h) table = {} for x1 in range(B): table[gmpy2.divm(h, gmpy2.powmod(g,x1,p),p)] = x1 for x0 in range(B): value = gmpy2.powmod(g, B*x0, p) if value in table: x1 = table[value] return B*x0+x1 return None
def meet_in_the_middle(p, g, h): p = gmpy2.mpz(p) g = gmpy2.mpz(g) h = gmpy2.mpz(h) B = gmpy2.mpz(2**20) middle = {} for x1 in range(B): middle[gmpy2.divm(h, gmpy2.powmod(g, x1, p), p)] = x1 for x0 in range(B): v = gmpy2.powmod(g, B * x0, p) if v in middle: x1 = middle[v] return x0 * B + x1 return None
def __F_x(self, k, lsc, lc): #lsc是s的系数列表,lc是除s外的系数列表 Fk = list() self.__Fkg = list() qm = gmpy2.mpz(730750818665451621361119245571504901405976559617) for i in range(k): temp1 = gmpy2.divm(1, lsc[i], qm) lc[i] = gmpy2.mul(lc[i], temp1) lsc[i] = gmpy2.mpz(1) for i in range(k): p = np.poly1d([1, lc[i]]) Fk.append(p) temp = Fk[0] for j in range(1, k): temp = temp * Fk[j] self.__Fkg = list(temp.coef) for n in range(k): self.__Fkg[i] = gmpy2.mul(lsc[i], self.__Fkg[i]) self.__Fkg[i] = np.mod(self.__Fkg[i], q) return self.__Fkg
def F_x(self,k,lsc,lc):#lsc是s的系数列表,lc是常数项列表 Fk = list() Fc = gmpy2.mpz(1) self.Fkg = list() qm = gmpy2.mpz(730750818665451621361119245571504901405976559617) for i in range(k): Fc = Fc * lsc[i] temp1 = gmpy2.divm(gmpy2.mpz(1),lsc[i],qm) lc[i] = gmpy2.mul(lc[i],temp1) #lsc[i] = gmpy2.mpz(1) for i in range(k): p = np.poly1d([gmpy2.mpz(1),lc[i]]) #print(p) Fk.append(p) temp = Fk[0] for j in range(1,k): temp = temp * Fk[j] self.Fkg = list(temp.coef) for n in range(k): self.Fkg[n] = self.Fkg[n] * Fc self.Fkg[i] = gmpy2.f_mod(self.Fkg[i],q)
def discrete_log(p, h, g, maxExp=40): """ Computes x such that h = g^x mod p """ B = mpz(2**(int(maxExp/2))) g = mpz(g) h = mpz(h) p = mpz(p) print("Computing x1s...") x1s = { divm(h, powmod(g,i,p), p) : i for i in range(B) } print("Checking for equality...") for x0, exprR in compute_x0s(p,h,g,B): x1 = x1s.get(exprR) if x1 is not None: print("Found values!") print("x0 = {}".format(x0)) print("x1 = {}".format(x1)) return mpz(x0)*B+mpz(x1) raise ValueError("No suitable x0, x1 found!")
def discrete_log(p, h, g, maxExp=40): """ Computes x such that h = g^x mod p """ B = mpz(2**(int(maxExp / 2))) g = mpz(g) h = mpz(h) p = mpz(p) print("Computing x1s...") x1s = {divm(h, powmod(g, i, p), p): i for i in range(B)} print("Checking for equality...") for x0, exprR in compute_x0s(p, h, g, B): x1 = x1s.get(exprR) if x1 is not None: print("Found values!") print("x0 = {}".format(x0)) print("x1 = {}".format(x1)) return mpz(x0) * B + mpz(x1) raise ValueError("No suitable x0, x1 found!")
def printDlog(self, p=P, g=G, h=H): """an algorithm that runs in time roughly sqr(2**40)−−−2**20 using a meet in the middle attack""" p = mpz(p) g = mpz(g) h = mpz(h) dico = {} # h = g**x where x = x0 * 2**20 + x1 # For x0 in 0 .. 2**20 -1 compute h div g**x1 mod p for x1 in range(2**20): dicoKey = divm(h, powmod(g, x1, p), p) try: # if dicoKey has been already computed or Exception otherwise dico[dicoKey].append(x1) except Exception as e: dico[dicoKey] = [x1] # search x0 in 0 ... 2**20 -1 such that (g**(x0 * 2**20)) is a dicoKey for x0 in range(2**20): rightSide = powmod(g, x0 * (2**20), p) if rightSide in dico.keys (): print("x is {0} * 2**20 + {1}".format(x0, dico[rightSide][0])) print(x0 * 2 ** 20 + dico[rightSide][0]) break
def dlog(p, g, h): B = 2**20 # hash all possible h / g^x1 lhs = {} for x1 in range(B + 1): try: lhs[gmpy2.divm(h, gmpy2.powmod(g, x1, p), p)] = x1 print('Adding x1 %d' % x1) except: print('Skipping x1 %d' % x1) # test all possible g^(B * x0) gB = gmpy2.powmod(g, B, p) for x0 in range(B + 1): rhs = gmpy2.powmod(gB, x0, p) print('Trying x0 %d' % x0) if rhs in lhs.keys(): x1 = lhs[rhs] print('Found x1 %d' % x1) return x0 * B + x1 print('Not found') return -1
def _calc_left(self, x1): """h/g^x1 mod p""" return divm(self.h, powmod(self.g, x1, self.p), self.p)
#!/usr/bin/env python import gmpy2 p = gmpy2.mpz(13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171) g = gmpy2.mpz(11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568) h = gmpy2.mpz(3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333) B = gmpy2.mpz(2**20) # h / g**x1 == (g**B)**x0 in Zp # Build a hash table of all possible values of the left hand side left = dict() for x1 in range(B): left[gmpy2.divm(h, gmpy2.powmod(g, x1, p), p)] = x1 X0 = None X1 = None # Check if the right hand side is in the hash table. for x0 in range(B): right = gmpy2.powmod(gmpy2.powmod(g, B, p), x0, p) if right in left: X1 = left[right] X0 = x0 break assert X0 assert X1 x = X0 * B + X1 assert h == gmpy2.powmod(g, x, p)
e1 = 23327726251786044391936648292839024146595570048812611847624416250567688593345991832899021739083633707931968367156418190899541789343695389214035656198940443694084863357891182940631262956610000834594411211315758491456537944164084910491343406970745522710006109273603306488884410008378076931379206447782497243706369716697059256561725387615119884228589913593993645939129523478697412302154935380290501912673190621589740810804066077627474186070432986181561024447756012172820603306269258330506288920549332959574399518917092258727284222880210724633474583014251305405371011153335054425546173263137887788146305123305580077169057 e2 = 4505393555835504606487870826353282766163603740698895254878220113620334944012547967067346196688168599517385927564245132817559450218298676399015204234657803594840924155175294821072394320087632487687709335317959898359874909957941994999403653727363881399918781552049592188872962138057339546832307104572095689473998567852409918864081711504405440197625511675662540095802033995298543682105609580732329855045702269123756160569686958372885975253846349951912551718569579353235032931809290081407524752714630257325839455477203384063890663622162286535533581269758828577639540220463199561278767098004389426416442649173454758063593 ct1=4233044783802450767510854832467599383874984490928621837132491742730752724752217005532746733648982119481207263207347390650525959553847872807003926686123715379339258876048838155724211935776102657811236099147154738299091713377631319252508240697121761366168720623672314814953982154251538837799665259126745039953878777913954452155395985972826024405555776503526895775982469050309789192782301529758997539136610448593258839137156214543513151801258872192489526015814984748588363132713449038207356219433366058705329936845506047123529164055321864249063109235848259632543809737738985141716433577429535413292853463783353178989962 ct2=6075835535321081176504740063423401401650533753512763308733448998126590394070144825790771366929331177778331823915033447942242747244407385702930336446635360319066625175276824452578280030178806358496488156534302292070595419389497035149137639683404226073920908619709289347005720490482153763065128868337344006807657718638474597334786594641635091735773518724283414331096453527873344332247556211543193147484053411926197875104366421570855916508234629186088440627164364312313807365761919109514877454052921937157078484640987810540950600740665618950169895027751404829047430453105662938201430487721124744219263365815376241123868 p1 = gcd(N2,N1) p2 = p1 q1= N1/p1 q2= N2/p2 r1=(p1-1)*(q1-1) r2=(p2-1)*(q2-1) print p1 #print q1 #print e1 #print r1 d1 = long(gmpy2.divm(1, e1, r1)) d2 = long(gmpy2.divm(1, e2, r2)) rsa1 = RSA.construct((N1,e1,d1,p1,q1)) pt1 = rsa1.decrypt(ct1) print pt1 rsa2 = RSA.construct((N2,e2,d2,p2,q2)) pt2 = rsa2.decrypt(ct2) print pt2
def recover_poly(self, split, t, userid): poly_coef_up = dict() poly_coef_down = list() poly_coef = dict() qm = gmpy2.mpz(730750818665451621361119245571504901405976559617) for i in range(t): coef_of_variable = list() coef_of_constant = list() akcoef1 = list() temp1 = 1 for j in range(t): if j != i: coef_of_variable.append(1) coef_of_constant.append(-(userid[j + 1])) coef = self.__F_x(len(coef_of_variable), coef_of_variable, coef_of_constant) poly_coef_up[i + 1] = coef for m in range(t): akcoef1.append(userid[m + 1]) for m in range(t): if m != i: temp1 = gmpy2.mul(temp1, (gmpy2.sub(akcoef1[i], akcoef1[m]))) temp1 = gmpy2.f_mod(temp1, q) poly_coef_down.append(temp1) for i in range(t): poly_coef_up_i = poly_coef_up[i + 1] poly_coef_down_i = poly_coef_down[i] temp4 = list() for j in range(len(poly_coef_up_i)): poly_coef_up_i[0] = gmpy2.mpz(1) temp2 = poly_coef_up_i[j] temp3 = gmpy2.divm(temp2, poly_coef_down_i, qm) temp4.append(temp3) poly_coef[i + 1] = temp4 split_recover = list() #存用于恢复多项式的分片 __recover_poly_coef = list() #恢复后的多项式系数 split_mul_poly = dict() m = 0 for i in range(t): m += 1 if m <= 3: split_recover.append(split[akcoef1[i]]) for i in range(t): temp7 = list() temp5 = poly_coef[i + 1] for j in range(len(temp5)): temp6 = gmpy2.mul(split_recover[i], temp5[j]) temp6 = gmpy2.f_mod(temp6, q) temp7.append(temp6) split_mul_poly[i] = temp7 __recover_poly_coef = split_mul_poly[0] for i in range(t): if i != 0: temp = split_mul_poly[i] for j in range(len(__recover_poly_coef)): __recover_poly_coef[j] = gmpy2.add(__recover_poly_coef[j], temp[j]) __recover_poly_coef[j] = gmpy2.f_mod( __recover_poly_coef[j], q) __secret_of_poly = np.polyval(__recover_poly_coef, 0) #由恢复出来的多项式得到的秘密值 __secret_of_poly = gmpy2.f_mod(__secret_of_poly, qm) return __recover_poly_coef, __secret_of_poly
def run(self, data_instances): LOGGER.info("Start rsa intersection") public_keys = self.transfer_variable.rsa_pubkey.get(-1) LOGGER.info("Get RSA public_key:{} from Host".format(public_keys)) self.e = [int(public_key["e"]) for public_key in public_keys] self.n = [int(public_key["n"]) for public_key in public_keys] cache_version_match_info = self.get_cache_version_match_info() # generate random value and sent intersect guest ids to guest # table(sid, r) random_value = data_instances.mapValues( lambda v: random.SystemRandom().getrandbits(self.random_bit)) # table(sid, hash(sid)) hash_sid = data_instances.map( lambda k, v: (k, int(RsaIntersectionGuest.hash(k), 16))) # table(sid. r^e % n *hash(sid)) for each host guest_id_list = [] for i in range(len(self.e)): guest_id_list.append( random_value.join( hash_sid, lambda r, h: h * gmpy_math.powmod( r, self.e[i], self.n[i]))) # table(r^e % n *hash(sid), 1) for i, guest_id in enumerate(guest_id_list): mask_guest_id = guest_id.map(lambda k, v: (v, 1)) self.transfer_variable.intersect_guest_ids.remote(mask_guest_id, role=consts.HOST, idx=i) LOGGER.info("Remote guest_id to Host {}".format(i)) # table(r^e % n *hash(sid), sid) exchange_guest_id_kv = [ guest_id.map(lambda k, v: (v, k)) for guest_id in guest_id_list ] host_ids_process_list = self.get_host_id_process( cache_version_match_info) LOGGER.info("Get host_ids_process") # Recv process guest ids # table(r^e % n *hash(sid), guest_id_process) recv_guest_ids_process = self.transfer_variable.intersect_guest_ids_process.get( idx=-1) LOGGER.info("Get guest_ids_process from Host") # table(r^e % n *hash(sid), sid, guest_ids_process) join_guest_ids_process = [ v.join(recv_guest_ids_process[i], lambda sid, g: (sid, g)) for i, v in enumerate(exchange_guest_id_kv) ] # table(sid, guest_ids_process) sid_guest_ids_process = [ e.map(lambda k, v: (v[0], v[1])) for e in join_guest_ids_process ] # table(sid, hash(guest_ids_process/r))) sid_guest_ids_process_final = [ v.join( random_value, lambda g, r: RsaIntersectionGuest.hash( gmpy2.divm(int(g), int(r), self.n[i]))) for i, v in enumerate(sid_guest_ids_process) ] # table(hash(guest_ids_process/r), sid) guest_ids_process_final_kv_exchange = [ e.map(lambda k, v: (v, k)) for e in sid_guest_ids_process_final ] # intersect table(hash(guest_ids_process/r), sid) encrypt_intersect_ids = [ v.join(host_ids_process_list[i], lambda sid, h: sid) for i, v in enumerate(guest_ids_process_final_kv_exchange) ] raw_intersect_ids = [ e.map(lambda k, v: (v, 1)) for e in encrypt_intersect_ids ] intersect_ids = self.get_common_intersection(raw_intersect_ids) LOGGER.info("Finish intersect_ids computing") # send intersect id if self.sync_intersect_ids: for i, host_party_id in enumerate(self.host_party_id_list): remote_intersect_id = self.map_raw_id_to_encrypt_id( intersect_ids, encrypt_intersect_ids[i]) self.transfer_variable.intersect_ids.remote( remote_intersect_id, role=consts.HOST, idx=i) LOGGER.info( "Remote intersect ids to Host {}!".format(host_party_id)) else: LOGGER.info("Not send intersect ids to Host!") if not self.only_output_key: intersect_ids = self._get_value_from_data(intersect_ids, data_instances) return intersect_ids
def left(x): return divm(h, powmod(g, x, p), p)
def div(x,y): return divm(x,y,N)
Each of these three numbers is about 153 digits. Find x such that h=g^x in Zp. To solve this assignment it is best to use an environment that supports multi-precision and modular arithmetic. In Python you could use the gmpy2 or numbthy modules. Both can be used for modular inversion and exponentiation. In C you can use GMP. In Java use a BigInteger class which can perform mod, modPow and modInverse operations. """ import gmpy2 p = gmpy2.mpz('134078079299425970995740249982058461274793658205923933' '77723561443721764030073546976801874298166903427690031' '858186486050853753882811946569946433649006084171') g = gmpy2.mpz('11717829880366207009516117596335367088558084999998952205' '59997945906392949973658374667057217647146031292859482967' '5428279466566527115212748467589894601965568') h = gmpy2.mpz('323947510405045044356526437872806578864909752095244' '952783479245297198197614329255807385693795855318053' '2878928001494706097394108577585732452307673444020333') B = 2 ** 20 gB = gmpy2.powmod(g, B, p) hash_table = {} for x1 in range(B): hash_table[gmpy2.divm(h, gmpy2.powmod(g, x1, p), p)] = x1 for x0 in range(B): if gmpy2.powmod(gB, x0, p) in hash_table: x1 = hash_table[gmpy2.powmod(gB, x0, p)] print x0 * B + x1
msg="I'm YoungC in OneA" class DSA: def calcR(self,k,p,q): r=gmpy2.f_mod(gmpy2.powmod(g,k,p),q) return r def calcS(self,k,h,x,r): s=gmpy2.f_mod(gmpy2.mpz(gmpy2.mul(gmpy2.invert(k,q),gmpy2.add(h,gmpy2.mul(x,r)))),q) return s def s2i(s): #字符串转整数 return int(s.encode('hex'),16) if __name__=="__main__": b=DSA() h=s2i(a.digest()) for k in range(2**16): r=b.calcR(k,p,q) #s=b.calcS(k,h,x,r) if r==548099063082341131477253921760299949438196259240: s=857042759984254168557880549501802188789837994940 print "found!" x=gmpy2.divm((gmpy2.mul(s,k)-h),r,q) print "因为k很小,爆破即得k值,解得x为:" print str(x) c=sha.new() c.update(hex(x)[2:]) print "x的sha1值为"+c.hexdigest() print "与题设0954edd5e0afe5542a4adf012611a91912a3ec16相同" print "finish"
def dealer(bits=2048, players=10, k=5): #random.seed(1203103) global n, m, p, q, e, d, shares assert bits == 2048, 'need different parameters' p = safe_prime_1 q = safe_prime_2 assert p.bit_length() == q.bit_length() == 1024 n = p*q # RSA modulus m = (p-1)/2 * (q-1)/2 trapdoors = dict(p=p, q=q) # Public exponent e = millerrabin.generateLargePrime(players.bit_length()+1) # Compute d such that de == 1 mod m d = gmpy2.divm(1, e, m) assert (d*e) % m == 1 public_key = (n,e) #print 'public_key', public_key trapdoor = dict(d=d, p=p, q=q) # Random polynomial coefficients a = [d] for i in range(1,k): a.append(random.randrange(0,m)) assert len(a) == k # Polynomial evaluation def f(x): y = 0 xx = 1 for coeff in a: y += coeff * xx xx *= x return y # Shares of master secret key SKs = [] for i in range(1,players+1): SKs.append(f(i)) # Random quadratic residue VK = v = random_Qn(n) # Verification keys VKs = [] for i in range(players): VKs.append(gmpy2.powmod(v, SKs[i], n)) public_key = ShoupPublicKey(n, e, players, k, VK, VKs) secret_keys = [ShoupPrivateKey(n, e, players, k, VK, VKs, SK, i) for i, SK in enumerate(SKs,start=1)] for i in [0]: S = set(range(1,k+1)) lhs = (public_key.Delta() * f(i)) % m rhs = sum(public_key.lambdaS(S,i,j) * f(j) for j in S) % m assert lhs == rhs #print i, 'ok' return public_key, secret_keys
from gmpy2 import divm,powmod p=13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171 g=11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568 h=3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333 n=40 B=int(2**(n/2)) m={divm(h,powmod(g,x,p),p):x for x in range(B)} gB=powmod(g,B,p) for x in range(B): r=powmod(gB,x,p) if r in m: X=x*B+m[r]
from Crypto.PublicKey import RSA from fractions import gcd import gmpy2 import base64 N = 123948613128507245097711825164030080528129311429181946930789480629270692835124562568997437300916285601268900901495788327838386854611883075845387070635813324417496512348003686061832004434518190158084956517800098929984855603216625922341285873495112316366384741709770903928077127611563285935366595098601100940173 N2 = 122890614849300155056519159433849880305439158904289542874766496514523043027349829509818565800562562195671251134947871996792136355514373160369135263766229423623131725044925870918859304353484491601318921285331340604341809979578202817714205469839224620893418109679223753141128229197377934231853172927071087589849 e = 65537L ct = 'Pob7AQZZSml618nMwTpx3V74N45x/rTimUQeTl0yHq8F0dsekZgOT385Jls1HUzWCx6ZRFPFMJ1RNYR2Yh7AkQtFLVx9lYDfb/Q+SkinBIBX59ER3/fDhrVKxIN4S6h2QmMSRblh4KdVhyY6cOxu+g48Jh7TkQ2Ig93/nCpAnYQ=' ct = base64.b64decode(ct) p = gcd(N,N2) q = N/p r=(p-1)*(q-1) d = long(gmpy2.divm(1, e, r)) rsa = RSA.construct((N,e,d,p,q)) pt = rsa.decrypt(ct) print pt
return curval p=mpz('13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171') g=mpz('11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568') h=mpz('3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333') B = 2**20 gB = gmpy2.powmod(g, B, p) #val of h/g^x1 hgx1val = {} #make hashtable by with keys being the values of hgx1 for x1 in xrange(2**20 + 1): gx1 = gmpy2.powmod(g, x1,p) #calculate g^x1 hgx1 = str(gmpy2.divm(h,gx1,p)) #calculating h/g^x1 in Z_p and make str hgx1val[hgx1] = x1 #adding val as key and gpow as value to hash for x0 in xrange(2**20 + 1): gBx0 = str(gmpy2.powmod(gB,x0, p)) #calculate (g^B)^x0 and make str if gBx0 in hgx1val: xret = gmpy2.mul(x0,B) xret = gmpy2.add(hgx1val[gBx0], xret) xret = gmpy2.f_mod(xret, p) print(xret) break
import sys,gmpy2 from gmpy2 import mpz,powmod,divm,add,mul p = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171 g = 11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568 h = 3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333 B = pow(2,20) Brange = range(B) hashtable = dict() # # create a hash table of LHS result -- h/g^x1 (mod p) # note we hash the LHS result, not the indices; the index is the value for x1 in Brange: hashtable[divm(h,powmod(g,x1,p),p)] = x1 # # check for each RHS result in hash table until a match is found for x0 in Brange: x1 = hashtable.get(powmod(g,mul(B,x0),p)) # if a match is found, calculate x if x1: x = add(mul(x0,B),mpz(x1)) # double-check that h matches, and if so, exit i = powmod(g,x,p) if (h == i): print str(x) sys.exit(0)
ans = [] points = [] for i in [3, 6]: msg = '%064x' % i msg += order s.sendline(msg) root = int(s.recvline().strip().split(',')[1][1:-1], 16) points.append((i, root)) orig = pow(root, 2, q) orig = orig - pow(i, 3, q) ans.append(orig) # s * a + b a, b = sp.symbols('a b') sol = sp.solve([ans[0] - (3 * a + b), ans[1] - (6 * a + b)], a, b) a = int(gmpy2.divm(-1264784453881987711378734714637094073662569449865694247234410111979889287160, 3, q)) b = int(sol[b] % q) log.info('a: ' + hex(a)) log.info('b: ' + hex(b)) curve = libnum.ecc.Curve(a, b, q) # now we just need to get a point S st eS[0] = h h = int(hashlib.sha256(orderpad).hexdigest(), 16) H = curve.check_x(h)[0] # print H n = 65537 l = 16503925798136106726026894143294039201930439456987742756395524593191976084900 k = gmpy2.invert(n, l) Q = curve.power(H, k)
def div(self,x,y): return int(gmpy2.divm(x,y,self.N))
def s2i(s): #字符串转整数 return int(s.encode('hex'),16) class DSA: def calcR(self,k,p,q): r=gmpy2.f_mod(gmpy2.powmod(g,k,p),q) return r def calcS(self,k,h,x,r): s=gmpy2.f_mod(gmpy2.mpz(gmpy2.mul(gmpy2.invert(k,q),gmpy2.add(h,gmpy2.mul(x,r)))),q) return s def s2i(s): #字符串转整数 return int(s.encode('hex'),16) if __name__=="__main__": print "首先,我们选择两个有着同样r值的签名,这说明他们公用了一个k值" m1=gmpy2.mpz(int("a4db3de27e2db3e5ef085ced2bced91b82e0df19",16)) m2=gmpy2.mpz(int("d22804c4899b522b23eda34d2137cd8cc22b9ce8",16)) s1=gmpy2.mpz(1267396447369736888040262262183731677867615804316) s2=gmpy2.mpz(1021643638653719618255840562522049391608552714967) r1=gmpy2.mpz(1105520928110492191417703162650245113664610474875) k=gmpy2.divm((m1-m2),(s1-s2),q) c=DSA() print "用式k=(m1-m2)/(s1-s2)(mod q)" print "求得k="+str(k) R1=c.calcR(k,p,q) if r1==R1: print "k校验正确!"
#!/usr/bin/env python3 import binascii import gmpy2 n = 126390312099294739294606157407778835887 e = 65537 c = 13612260682947644362892911986815626931 # From factordb. p = 9336949138571181619 q = 13536574980062068373 r = (q - 1) * (p - 1) d = gmpy2.divm(1, e, r) p = gmpy2.powmod(c, d, n) print(binascii.unhexlify(hex(p)[2:]).decode())
import gmpy2 import math p = gmpy2.mpz(13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171) g = gmpy2.mpz(11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568) h = gmpy2.mpz(3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333) B = gmpy2.mpz(2**20) # 1. Build a hash table of all possible values of h/g^{x1} mod p for x1 = 0,1,...,2^20 print("Building hash table...") values={} for x1 in range(0, B): if (x1 % 1000 == 0): print('%d: %.1f%%' % (x1, 100*x1/B)) try: v = gmpy2.divm(h, gmpy2.powmod(g, x1, p), p) values[v] = x1 except ZeroDivisionError: pass # 2. For each value x0 = 0,1,...,2^20 check if (g^B)^{x0} mod p is in the hash table. # If found, x = x0*B + x1. print("Checking if value is in hash table...") x = None for x0 in range(0, B): if (x0 % 1000 == 0): print('%d: %.1f%%' % (x0, 100*x0/B)) v = gmpy2.powmod(gmpy2.powmod(g, B, p), x0, p) if v in values: x1 = values[v] x = (x0*B + x1) % p break
import gmpy2, time from gmpy2 import mpz p = mpz(13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171) g = mpz(11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568) h = mpz(3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333) B = mpz(2**20) gB = pow(g,B,p) x0, x1 = 0, 0 d = {} i = 2**19 start1 = time.clock() tmp = gmpy2.invert(pow(g,i,p), p) elapsed1 = (time.clock() - start1) start2 = time.clock() d[gmpy2.t_mod(gmpy2.mul(h,tmp),p)] = i elapsed2 = (time.clock() - start2) start3 = time.clock() d[gmpy2.divm(h, pow(g,i,p), p)] = i elapsed3 = (time.clock() - start2) print(elapsed1, elapsed2, elapsed3)
def left(x): return gmpy2.divm(h, numbthy.powmod(g, x, p), p)
def split_calculation_process(self, data_instances): LOGGER.info("RSA intersect using split calculation.") # split data sid_hash_odd = data_instances.filter(lambda k, v: k & 1) sid_hash_even = data_instances.filter(lambda k, v: not k & 1) # LOGGER.debug(f"sid_hash_odd count: {sid_hash_odd.count()}," # f"odd fraction: {sid_hash_odd.count()/data_instances.count()}") # generate rsa keys self.e, self.d, self.n = self.generate_protocol_key() LOGGER.info("Generate host protocol key!") public_key = {"e": self.e, "n": self.n} # sends public key e & n to guest self.transfer_variable.host_pubkey.remote(public_key, role=consts.GUEST, idx=0) LOGGER.info("Remote public key to Guest.") # generate ri for even ids # count = sid_hash_even.count() # self.r = self.generate_r_base(self.random_bit, count, self.random_base_fraction) # LOGGER.info(f"Generate {len(self.r)} r values.") # receive guest key for even ids guest_public_key = self.transfer_variable.guest_pubkey.get(0) # LOGGER.debug("Get guest_public_key:{} from Guest".format(guest_public_key)) LOGGER.info(f"Get guest_public_key from Guest") self.rcv_e = int(guest_public_key["e"]) self.rcv_n = int(guest_public_key["n"]) # encrypt & send guest pubkey-encrypted odd ids pubkey_ids_process = self.pubkey_id_process( sid_hash_even, fraction=self.random_base_fraction, random_bit=self.random_bit, rsa_e=self.rcv_e, rsa_n=self.rcv_n) LOGGER.info(f"Finish pubkey_ids_process") mask_host_id = pubkey_ids_process.mapValues(lambda v: 1) self.transfer_variable.host_pubkey_ids.remote(mask_host_id, role=consts.GUEST, idx=0) LOGGER.info("Remote host_pubkey_ids to Guest") # encrypt & send prvkey-encrypted host odd ids to guest prvkey_ids_process_pair = self.cal_prvkey_ids_process_pair( sid_hash_odd, self.d, self.n) prvkey_ids_process = prvkey_ids_process_pair.mapValues(lambda v: 1) self.transfer_variable.host_prvkey_ids.remote(prvkey_ids_process, role=consts.GUEST, idx=0) LOGGER.info("Remote host_prvkey_ids to Guest.") # get & sign guest pubkey-encrypted odd ids guest_pubkey_ids = self.transfer_variable.guest_pubkey_ids.get(idx=0) LOGGER.info(f"Get guest_pubkey_ids from guest") host_sign_guest_ids = guest_pubkey_ids.map( lambda k, v: (k, self.sign_id(k, self.d, self.n))) LOGGER.debug(f"host sign guest_pubkey_ids") # send signed guest odd ids self.transfer_variable.host_sign_guest_ids.remote(host_sign_guest_ids, role=consts.GUEST, idx=0) LOGGER.info("Remote host_sign_guest_ids_process to Guest.") # recv guest privkey-encrypted even ids guest_prvkey_ids = self.transfer_variable.guest_prvkey_ids.get(idx=0) LOGGER.info("Get guest_prvkey_ids") # receive guest-signed host even ids recv_guest_sign_host_ids = self.transfer_variable.guest_sign_host_ids.get( idx=0) LOGGER.info(f"Get guest_sign_host_ids from Guest.") guest_sign_host_ids = pubkey_ids_process.join( recv_guest_sign_host_ids, lambda g, r: (g[0], RsaIntersectionHost.hash( gmpy2.divm(int(r), int(g[1]), self.rcv_n), self. final_hash_operator, self.rsa_params.salt))) sid_guest_sign_host_ids = guest_sign_host_ids.map(lambda k, v: (v[1], v[0])) encrypt_intersect_even_ids = sid_guest_sign_host_ids.join( guest_prvkey_ids, lambda sid, h: sid) # filter & send intersect even ids intersect_even_ids = self.filter_intersect_ids( [encrypt_intersect_even_ids]) remote_intersect_even_ids = encrypt_intersect_even_ids.mapValues( lambda v: 1) self.transfer_variable.host_intersect_ids.remote( remote_intersect_even_ids, role=consts.GUEST, idx=0) LOGGER.info(f"Remote host intersect ids to Guest") # recv intersect ids intersect_ids = None if self.sync_intersect_ids: encrypt_intersect_odd_ids = self.transfer_variable.intersect_ids.get( idx=0) intersect_odd_ids_pair = encrypt_intersect_odd_ids.join( prvkey_ids_process_pair, lambda e, h: h) intersect_odd_ids = intersect_odd_ids_pair.map(lambda k, v: (v, 1)) intersect_ids = intersect_odd_ids.union(intersect_even_ids) LOGGER.info("Get intersect ids from Guest") return intersect_ids
while b > 0: if b & 1 == 1: ret = gmpy2.mul(ret,a) ret = gmpy2.f_mod(ret,N) a = gmpy2.mul(a,a) a = gmpy2.f_mod(a,N) b = b >> 1 return gmpy2.f_mod(ret,N) p=13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171 g=11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568 h=3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333 B=1<<20 h_g=dict() for x1 in range(0,B+1): g_x1=mypowmod(g,x1,p) _g_x1=gmpy2.divm(1,g_x1,p) h_gx1=gmpy2.mul(h,_g_x1) h_gx1=gmpy2.f_mod(h_gx1,p) h_g[h_gx1]=x1 g_B=mypowmod(g,B,p) for x0 in range(0,B+1): gB_x0=mypowmod(g_B,x0,p) if gB_x0 in h_g: x1=h_g[gB_x0] print x0, x1 x0_B=gmpy2.mul(B,x0) print gmpy2.add(x0_B,x1) break
print "Question 4" c = 22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256465839967942889460764542040581564748988013734864120452325229320176487916666402997509188729971690526083222067771600019329260870009579993724077458967773697817571267229951148662959627934791540 e = 65537 N = N1 p = p1 q = q1 assert p * q == N phi = (p - 1) * (q - 1) assert phi == N - p - q + 1 # e*d = 1 % phi d = gmpy2.divm(1, e, phi) assert (e * d) % phi == 1 # encrypt c = m^e in Zn # decrypt m = c^d in Zn m = gmpy2.powmod(c, d, N) assert gmpy2.powmod(m, e, N) == c hexstring = format(m, "x") hexstring = hexstring.split("00")[1] plaintext = hexstring.decode("hex") print plaintext # correct answer assert plaintext == "Factoring lets us break RSA."
def run(self, data_instances): LOGGER.info("Start ras intersection") public_key = get(name=self.transfer_variable.rsa_pubkey.name, tag=self.transfer_variable.generate_transferid( self.transfer_variable.rsa_pubkey), idx=0) LOGGER.info("Get RAS public_key:{} from Host".format(public_key)) self.e = public_key["e"] self.n = public_key["n"] # generate random value and sent intersect guest ids to guest # table(sid, r) table_random_value = data_instances.mapValues( lambda v: random.SystemRandom().getrandbits(self.random_bit)) # table(sid, hash(sid)) table_hash_sid = data_instances.map( lambda k, v: (k, int(RsaIntersectionGuest.hash(k), 16))) # table(sid. r^e % n *hash(sid)) table_guest_id = table_random_value.join( table_hash_sid, lambda r, h: h * gmpy_math.powmod(r, self.e, self.n)) # table(r^e % n *hash(sid), 1) table_send_guest_id = table_guest_id.map(lambda k, v: (v, 1)) remote(table_send_guest_id, name=self.transfer_variable.intersect_guest_ids.name, tag=self.transfer_variable.generate_transferid( self.transfer_variable.intersect_guest_ids), role=consts.HOST, idx=0) LOGGER.info("Remote guest_id to Host") # table(r^e % n *hash(sid), sid) table_exchange_guest_id = table_guest_id.map(lambda k, v: (v, k)) # Recv host_ids_process # table(host_id_process, 1) table_host_ids_process = get( name=self.transfer_variable.intersect_host_ids_process.name, tag=self.transfer_variable.generate_transferid( self.transfer_variable.intersect_host_ids_process), idx=0) LOGGER.info("Get host_ids_process from Host") # Recv process guest ids # table(r^e % n *hash(sid), guest_id_process) table_recv_guest_ids_process = get( name=self.transfer_variable.intersect_guest_ids_process.name, tag=self.transfer_variable.generate_transferid( self.transfer_variable.intersect_guest_ids_process), # role=consts.HOST, idx=0) LOGGER.info("Get guest_ids_process from Host") # table(r^e % n *hash(sid), sid, guest_ids_process) table_join_guest_ids_process = table_exchange_guest_id.join( table_recv_guest_ids_process, lambda sid, g: (sid, g)) # table(sid, guest_ids_process) table_sid_guest_ids_process = table_join_guest_ids_process.map( lambda k, v: (v[0], v[1])) # table(sid, hash(guest_ids_process/r))) table_sid_guest_ids_process_final = table_sid_guest_ids_process.join( table_random_value, lambda g, r: hashlib.sha256( bytes(str(gmpy2.divm(int(g), int(r), self.n)), encoding="utf-8")).hexdigest()) # table(hash(guest_ids_process/r), sid) table_guest_ids_process_final_sid = table_sid_guest_ids_process_final.map( lambda k, v: (v, k)) table_intersect_ids = table_guest_ids_process_final_sid.join( table_host_ids_process, lambda sid, h: sid) LOGGER.info("Finish intersect_ids computing") # send intersect id if self.send_intersect_id_flag: remote(table_intersect_ids, name=self.transfer_variable.intersect_ids.name, tag=self.transfer_variable.generate_transferid( self.transfer_variable.intersect_ids), role=consts.HOST, idx=0) LOGGER.info("Remote intersect ids to Host!") else: LOGGER.info("Not send intersect ids to Host!") return table_intersect_ids
print prime_factors(N1) e1 = 23327726251786044391936648292839024146595570048812611847624416250567688593345991832899021739083633707931968367156418190899541789343695389214035656198940443694084863357891182940631262956610000834594411211315758491456537944164084910491343406970745522710006109273603306488884410008378076931379206447782497243706369716697059256561725387615119884228589913593993645939129523478697412302154935380290501912673190621589740810804066077627474186070432986181561024447756012172820603306269258330506288920549332959574399518917092258727284222880210724633474583014251305405371011153335054425546173263137887788146305123305580077169057 e2 = 4505393555835504606487870826353282766163603740698895254878220113620334944012547967067346196688168599517385927564245132817559450218298676399015204234657803594840924155175294821072394320087632487687709335317959898359874909957941994999403653727363881399918781552049592188872962138057339546832307104572095689473998567852409918864081711504405440197625511675662540095802033995298543682105609580732329855045702269123756160569686958372885975253846349951912551718569579353235032931809290081407524752714630257325839455477203384063890663622162286535533581269758828577639540220463199561278767098004389426416442649173454758063593 ct1 = 4233044783802450767510854832467599383874984490928621837132491742730752724752217005532746733648982119481207263207347390650525959553847872807003926686123715379339258876048838155724211935776102657811236099147154738299091713377631319252508240697121761366168720623672314814953982154251538837799665259126745039953878777913954452155395985972826024405555776503526895775982469050309789192782301529758997539136610448593258839137156214543513151801258872192489526015814984748588363132713449038207356219433366058705329936845506047123529164055321864249063109235848259632543809737738985141716433577429535413292853463783353178989962 ct2 = 6075835535321081176504740063423401401650533753512763308733448998126590394070144825790771366929331177778331823915033447942242747244407385702930336446635360319066625175276824452578280030178806358496488156534302292070595419389497035149137639683404226073920908619709289347005720490482153763065128868337344006807657718638474597334786594641635091735773518724283414331096453527873344332247556211543193147484053411926197875104366421570855916508234629186088440627164364312313807365761919109514877454052921937157078484640987810540950600740665618950169895027751404829047430453105662938201430487721124744219263365815376241123868 p1 = gcd(N2, N1) p2 = p1 q1 = N1 / p1 q2 = N2 / p2 r1 = (p1 - 1) * (q1 - 1) r2 = (p2 - 1) * (q2 - 1) print p1 #print q1 #print e1 #print r1 d1 = long(gmpy2.divm(1, e1, r1)) d2 = long(gmpy2.divm(1, e2, r2)) rsa1 = RSA.construct((N1, e1, d1, p1, q1)) pt1 = rsa1.decrypt(ct1) print pt1 rsa2 = RSA.construct((N2, e2, d2, p2, q2)) pt2 = rsa2.decrypt(ct2) print pt2
def compute_x1(p, g, h, B): return { divm(h, powmod(g, idx1, p), p) : idx1 for idx1 in range(B) }