def rsa(): p = gmpy2.mpz(int(request.values.get('p'))) # print(p) q = gmpy2.mpz(int(request.values.get('q'))) e = gmpy2.mpz(int(request.values.get('e'))) operator = request.values.get('operator') try: if p and q and e and operator: if not gmpy2.is_prime(p) or not gmpy2.is_prime(q): resu = {'code': 9999, 'message': 'p和q必须是素数'} return json.dumps(resu, ensure_ascii=False) n = gmpy2.mul(p, q) if operator == 'decode': c = gmpy2.mpz(int(request.values.get('c'))) phi_n = gmpy2.mul(gmpy2.sub(p, 1), gmpy2.sub(q, 1)) d = gmpy2.invert(e, phi_n) # private key m = gmpy2.powmod(c, d, n) print(m) print(d) resu = {'code': 200, 'm': str(m), 'd': str(d)} return json.dumps(resu, ensure_ascii=False) elif operator == 'encode': m = gmpy2.mpz(int(request.values.get('m'))) c = gmpy2.powmod(m, e, n) resu = {'code': 201, 'c': str(c)} return json.dumps(resu, ensure_ascii=False) else: resu = {'code': 10001, 'message': '参数不能为空!'} return json.dumps(resu, ensure_ascii=False) except: resu = {'code': 10002, 'message': '异常。'} return json.dumps(resu, ensure_ascii=False)
def subtraction(self, interval): reset_default_precision() res_inc_left = False res_inc_right = False if self.include_lower and interval.include_lower: res_inc_left = True if self.include_upper and interval.include_upper: res_inc_right = True with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundDown, precision=mpfr_proxy_precision) as ctx: res_left = gmpy2.sub(mpfr(self.lower), mpfr(interval.upper)) with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundUp, precision=mpfr_proxy_precision) as ctx: res_right = gmpy2.sub(mpfr(self.upper), mpfr(interval.lower)) if res_left <= res_right: res_right = round_number_up_to_digits(res_right, self.digits) res_left = round_number_down_to_digits(res_left, self.digits) return Interval(res_left, res_right, res_inc_left, res_inc_right, self.digits) else: res_right = round_number_down_to_digits(res_right, self.digits) res_left = round_number_up_to_digits(res_left, self.digits) return Interval(res_right, res_left, res_inc_right, res_inc_left, self.digits)
def breakKey(N,e): P,Q = bruteSmall(N) phi = g.mul( g.sub(P,1), g.sub(Q,1) ) D = g.invert(e,phi) checkD(e,D,phi) return (P,Q,D)
def Q1Q4(): N = mpz('17976931348623159077293051907890247336179769789423065727343008115\ 77326758055056206869853794492129829595855013875371640157101398586\ 47833778606925583497541085196591615128057575940752635007475935288\ 71082364994994077189561705436114947486504671101510156394068052754\ 0071584560878577663743040086340742855278549092581') A = isqrt(N) + 1 x = isqrt(sub(mul(A, A), N)) p = sub(A, x) q = add(A, x) print("Q1:") print(p) fiN = mul(sub(p, 1), sub(q, 1)) e = mpz(65537) d = gmpy2.invert(e, fiN) ct = mpz('22096451867410381776306561134883418017410069787892831071731839143\ 67613560012053800428232965047350942434394621975151225646583996794\ 28894607645420405815647489880137348641204523252293201764879166664\ 02997509188729971690526083222067771600019329260870009579993724077\ 458967773697817571267229951148662959627934791540') pt = gmpy2.powmod(ct, d, N) ptstr = pt.digits(16) pos = ptstr.find('00') payload = ptstr[pos + 2:] print("Q4:") print(binascii.unhexlify(payload))
def generate_keys(n_bits=1024): """ Generates keys necessary to Pailler's Cryptossystem Parameters: Kwargs: n_bits: Size of the key, in bits (default=1024) Returns: Tuple: Tuple containing two tuples: t0: Tuple containing the public key (n,g) t1: Tuple containing the private key (lambda,mu) """ one = gmpy2.mpz(1) p = new_prime(n_bits=n_bits) q = new_prime(n_bits=n_bits) # public key n = gmpy2.mul(p, q) g = gmpy2.add(n, one) #private key lbd = gmpy2.mul(gmpy2.sub(p, one), gmpy2.sub(q, one)) mu = gmpy2.powmod(lbd, -1, n) return ((n, g), (lbd, mu))
def adjust_ret_list(retlist): retlist[0].cdf_low="0.0" retlist[-1].cdf_up="1.0" with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundUp, precision=mpfr_proxy_precision) as ctx: min_value=gmpy2.exp10(-digits_for_input_cdf) current=min_value for pbox in retlist: with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundDown, precision=mpfr_proxy_precision) as ctx: if gmpy2.is_zero(gmpy2.mpfr(pbox.cdf_low)) or gmpy2.mpfr(pbox.cdf_low)<current: pbox.cdf_low=round_number_down_to_digits(current, digits_for_input_cdf) with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundUp, precision=mpfr_proxy_precision) as ctx: current=current+min_value if gmpy2.is_zero(gmpy2.mpfr(pbox.cdf_up)) or gmpy2.mpfr(pbox.cdf_up)<current: pbox.cdf_up=round_number_down_to_digits(current, digits_for_input_cdf) with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundDown, precision=mpfr_proxy_precision) as ctx: current=gmpy2.sub(gmpy2.mpfr("1.0"), min_value) for pbox in retlist[::-1]: with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundDown, precision=mpfr_proxy_precision) as ctx: if gmpy2.mpfr(pbox.cdf_up)==gmpy2.mpfr("1.0") or gmpy2.mpfr(pbox.cdf_up)>current: pbox.cdf_up=round_number_up_to_digits(current, digits_for_input_cdf) current=gmpy2.sub(current, min_value) if gmpy2.mpfr(pbox.cdf_low)==gmpy2.mpfr("1.0") or gmpy2.mpfr(pbox.cdf_low)>current: pbox.cdf_low=round_number_up_to_digits(current, digits_for_input_cdf) retlist[0].cdf_low = "0.0" retlist[-1].cdf_up = "1.0" return retlist
def factor_n1(): ''' Factoring challenge #1: The following modulus N is a products of two primes p and q where |p−q| < 2N^(1/4). Find the smaller of the two factors and enter it as a decimal integer. ''' N = gmpy2.mpz( '179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581' ) A = gmpy2.add(gmpy2.isqrt(N), one) x = gmpy2.isqrt(gmpy2.sub(gmpy2.mul(A, A), N)) print 'Calculating first factors...' ticks = 0 while True: p = gmpy2.sub(A, x) q = gmpy2.add(A, x) if gmpy2.is_prime(p) and gmpy2.is_prime(q) and gmpy2.mul(p, q) == N: print "p =", p, "q =", q, "ticks =", ticks return else: x = gmpy2.add(x, one) ticks += 1 if ticks % 10000 == 0: print 'ticks:', ticks
def runPart3(N): A2 = add(isqrt(mul(24, N)), 1) x2 = isqrt(sub(mul(A2, A2), mul(24, N))) p = div(sub(A2, x2), 6) q = div(add(A2, x2), 4) return p, q
def calc_near6(self): """ Solves the Extra Credit question Q3 See: Uses only integer arithmetic to avoid issues with rounding errors Solution credit to Francois Degros: https://class.coursera.org/crypto-011/forum/thread?thread_id=517#post-2279 :return: the prime factors of ```self.n```, p and q :rtype: tuple """ # A = ceil(sqrt(24 N)) - the use of isqrt() won't matter, as we seek the ceil A = add(isqrt(mul(self.n, mpz(24))), mpz(1)) # D = A^2 - 24 N D = sub(mul(A, A), mul(24, self.n)) # E = sqrt(D) - note D is a perfect square and we can use integer arithmetic E = isqrt(D) assert sub(mul(E, E), D) == mpz(0) p = div(sub(A, E), 6) q = div(add(A, E), 4) if self._check_sol(p, q): return p, q # The above is the right solution, however, there is another possible solution: p = div(add(A, E), 6) q = div(sub(A, E), 4) if self._check_sol(p, q): return p, q print 'Could not find a solution' return 0, 0
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 generate_random(bit_size, include_negative_range, seeded, full_range): global global_random_state if not seeded or global_random_state is None: global_random_state = gmpy2.random_state() x = zero if full_range: x = gmpy2.mul_2exp(one, bit_size - 1) tmp = 0 if bit_size < 33: tmp = gmpy2.mpz_random(global_random_state, RAND_MAX) temp = (1 << bit_size) x = gmpy2.f_mod(tmp, temp) if include_negative_range: tmp = gmpy2.mul_2exp(one, bit_size - 1) x = gmpy2.sub(x, tmp) return x for i in range(bit_size - 32, 0 - 1, -32): tmp = gmpy2.mpz_random(global_random_state, RAND_MAX) tmp = gmpy2.mul_2exp(tmp, i) x = gmpy2.add(x, tmp) x = gmpy2.add(x, gmpy2.mpz_random(global_random_state, RAND_MAX)) if include_negative_range: tmp = gmpy2.mul_2exp(one, bit_size - 1) x = gmpy2.sub(x, tmp) return mpz(x)
def breakKey(N,e): P,Q = FermatFactor(N) phi = gmpy2.mul( gmpy2.sub(P,1), gmpy2.sub(Q,1) ) D = gmpy2.invert(e,phi) checkD(e,D,phi) return (P,Q,D)
def runPart1(N): A = isqrt(N) A = add(A, 1) #couldn't find default ceil function x = isqrt(sub(mul(A,A), N)) p = sub(A, x) q = add(A, x) return p, q
def solve_quadratic(a, b, c): """ Solves the quadratic equation ```a x2 + b x + c = 0``` :return: the GMP result of solving the quadratic equation usign multi-precision numbers """ bb = sqrt(sub(mul(b, b), mul(mpz(4), mul(a, c)))) x1 = gmpy2.div(sub(-b, bb), mul(mpz(2), a)) x2 = gmpy2.div(add(-b, bb), mul(mpz(2), a)) return x1, x2
def three(): N = mpz('720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929') A = mul(isqrt(mul(6,N)),2) A = add(A,1) x = isqrt(sub(mul(A,A),mul(24,N))) p = t_div(sub(A,x),6) q = t_div(add(A,x),4) if mul(p,q) == N: print "3. " + str(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 eea(a, b): r, r1 = a, b s, s1 = 1, 0 t, t1 = 0, 1 while r1 != 0: q = gmpy2.div(r, r1) r2 = gmpy2.f_mod(r, r1) r, s, t, r1, s1, t1 = r1, s1, t1, r2, gmpy2.sub(s, gmpy2.mul(s1, q)), gmpy2.sub(t, gmpy2.mul(t1, q)) d = r return d, s, t
def create_primes_index(list_primes): list_start_index = [] for i in range(0, n_smooth + 1): p = list_primes[i] sqr1 = sqrt_modulo.sqrt_modular(N, p) sqr2 = p - sqr1 start_index1 = gmpy2.f_mod(gmpy2.sub(sqr1 - start), p) start_index2 = gmpy2.f_mod(gmpy2.sub(sqr2 - start), p) list_start_index.append([start_index1, start_index2]) return list_start_index
def one(): N = mpz('179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581') A = isqrt(N) A = add(A,1) x = isqrt(sub(mul(A,A),N)) p = sub(A,x) q = add(A,x) if mul(p,q) == N: print "1. " + str(p) return p, q, N
def three(): N = mpz( '720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929' ) A = mul(isqrt(mul(6, N)), 2) A = add(A, 1) x = isqrt(sub(mul(A, A), mul(24, N))) p = t_div(sub(A, x), 6) q = t_div(add(A, x), 4) if mul(p, q) == N: print "3. " + str(p)
def extract_at(pwd, features, index): index += 1 pwd = mpz(crypt.get_bit_str_from_byte(pwd), base=2) if features[index - 1] >= config.ti: # pick the other column of the table x = crypt.p(mpz(index << 1), config.r) y = gmpy2.sub(table[index - 1][0], crypt.g(mpz(index << 1), config.r ^ pwd)) return x, y else: x = crypt.p(mpz((index << 1) + 1), config.r) y = gmpy2.sub(table[index - 1][1], crypt.g(mpz((index << 1) + 1), config.r ^ pwd)) return x, y
def four(): ct = mpz('22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256465839967942889460764542040581564748988013734864120452325229320176487916666402997509188729971690526083222067771600019329260870009579993724077458967773697817571267229951148662959627934791540') p,q,N = one() p = sub(p,mpz('1')) q = sub(q,mpz('1')) e = mpz('65537') fi = mul(p,q) d = invert(e,fi) pkcs = to_binary(powmod(ct,d,N)) #Big-endian representation print "4. " + pkcs[::-1].encode('hex').split('00')[-1].decode('hex')
def two(): N = mpz('648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877') A = isqrt(N) while True: A = add(A,1) x = isqrt(sub(mul(A,A),N)) p = sub(A,x) q = add(A,x) if mul(p,q) == N: print "2. " + str(p) break
def computeN2Factors(): p = 0 q = 0 A = computeA(N2) while not confirmed(N2, p, q): A2 = pow(A, 2) assert A2 > N2 x = gmpy2.sqrt(gmpy2.sub(A2, N2)) p = gmpy2.sub(A, x) q = gmpy2.add(A, x) A += 1
def one(): N = mpz( '179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581' ) A = isqrt(N) A = add(A, 1) x = isqrt(sub(mul(A, A), N)) p = sub(A, x) q = add(A, x) if mul(p, q) == N: print "1. " + str(p) return p, q, N
def runPart2(N): A = isqrt(N) maxVal = add(isqrt(N), 2**20) p = 0 q = 0 while mul(p, q) != N and A <= maxVal: A = add(A, 1) x = isqrt(sub(mul(A,A), N)) p = sub(A, x) q = add(A, x) return p, q
def two(): N = mpz( '648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877' ) A = isqrt(N) while True: A = add(A, 1) x = isqrt(sub(mul(A, A), N)) p = sub(A, x) q = add(A, x) if mul(p, q) == N: print "2. " + str(p) break
def four(): ct = mpz( '22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256465839967942889460764542040581564748988013734864120452325229320176487916666402997509188729971690526083222067771600019329260870009579993724077458967773697817571267229951148662959627934791540' ) p, q, N = one() p = sub(p, mpz('1')) q = sub(q, mpz('1')) e = mpz('65537') fi = mul(p, q) d = invert(e, fi) pkcs = to_binary(powmod(ct, d, N)) #Big-endian representation print "4. " + pkcs[::-1].encode('hex').split('00')[-1].decode('hex')
def find_factors(n): a = gmp.isqrt(n) p = 0 q = 0 while not check(n, p, q): a = gmp.add(a, 1) a2 = gmp.mul(a, a) x = gmp.isqrt(gmp.sub(a2, n)) p = gmp.mpz(gmp.sub(a, x)) q = gmp.mpz(gmp.add(a, x)) return (p, q)
def decrypt(n, p, q, ciphertext): euler = gmp.mul(gmp.sub(gmp.mpz(p), 1), gmp.sub(gmp.mpz(q), 1)) e = gmp.mpz(65537) d = gmp.invert(e, gmp.mpz(euler)) msg = gmp.powmod(ciphertext, d, gmp.mpz(n)) msg = hex(msg) if msg.startswith('0x2'): header = msg.index('00') + 2 msg = msg[header:] return msg.decode('hex') return ""
def computeN3Factors(): A = gmpy2.ceil(gmpy2.mul(2, gmpy2.sqrt(gmpy2.mul(6, N3)))) X = gmpy2.ceil( gmpy2.sqrt( gmpy2.sub( pow(A, 2), gmpy2.mul(24, N3) ) ) ) p = gmpy2.ceil(gmpy2.div(gmpy2.sub(A, X), 6)) # Only round one. q = gmpy2.div(N3, p) confirmed(N3, p, q)
def decrypt(): n = mpz(N1) p, q = Factoring(n).calc_near() fi_n = mul(sub(p, 1), sub(q, 1)) e = mpz(65537) d = gmpy2.invert(e, fi_n) dec = gmpy2.powmod(mpz(CIPHER), d, n) dec_hex = hex(dec) if dec_hex.startswith('0x2'): msg_starts = dec_hex.index('00') + 2 msg_hex = dec_hex[msg_starts:] return msg_hex.decode('hex') print 'Decryption failed'
def q3(): N = 720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929 rt = gmpy2.sqrt(gmpy2.mul(N, 6)) A = gmpy2.ceil(rt) A2 = pow(A, 2) assert A2 > N x = gmpy2.sqrt(gmpy2.sub(A2, N)) x = gmpy2.mul(x, 3 / 2) p = gmpy2.sub(A, x) q = gmpy2.add(A, x) gotcha(N, p, q)
def q3(): N = 720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929 rt = gmpy2.sqrt(gmpy2.mul(N, 6)) A = gmpy2.ceil(rt) A2 = pow(A, 2) assert A2 > N x = gmpy2.sqrt(gmpy2.sub(A2, N)) x = gmpy2.mul(x, 3/2) p = gmpy2.sub(A, x) q = gmpy2.add(A, x) gotcha(N, p, q)
def q1(): N = 179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581 rt = gmpy2.sqrt(N) A = gmpy2.ceil(rt) A2 = pow(A, 2) assert A2 > N x = gmpy2.sqrt(gmpy2.sub(A2, N)) p = gmpy2.sub(A, x) q = gmpy2.add(A, x) gotcha(N, p, q)
def FermatFactor(N): A = gmpy2.mpz( gmpy2.ceil( gmpy2.sqrt(N) ) ) B2 = gmpy2.sub( gmpy2.square(A), N ) while not gmpy2.is_square(B2): A = gmpy2.add( A, gmpy2.mpz("1") ) B2 = gmpy2.sub( gmpy2.square(A), N ) B = gmpy2.sqrt(B2) P = gmpy2.mpz( gmpy2.sub( A, B ) ) Q = gmpy2.mpz( gmpy2.add( A, B ) ) if not checkFactors(P,Q,N): raise Exception("Bad factors generated") return ( P, Q )
def find_factors_6n(n): n24 = gmp.mul(n, 24) a = gmp.isqrt(n24) p = 0 q = 0 while not check(n, p, q): a = gmp.add(a, 1) a2 = gmp.mul(a, a) x = gmp.isqrt(gmp.sub(a2, n24)) p = gmp.mpz(gmp.div(gmp.sub(a, x), 6)) q = gmp.mpz(gmp.div(gmp.add(a, x), 4)) return (p, q)
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 verify(A,x,N): p = gmpy2.sub(A,x) q = gmpy2.add(A,x) if gmpy2.mul(p, q) == N: return [True,p,q] else: return [False,p,q]
def generate_sparse_matrix(u_1, modified_secret_key, x_p): global global_random_state seed = mpz(time.time()) global_random_state = gmpy2.random_state(seed) Theta_vector = [0 for _ in range(Theta)] for i in range(1, Theta): Theta_vector[i] = generate_random(kappa + 1, False, True, False) modified_secret_key[0] = True for i in range(1, Theta): modified_secret_key[i] = False count = theta - 1 gmpy2.random_state() while count > 0: index = gmpy2.mpz_random(global_random_state, RAND_MAX) % Theta if not modified_secret_key[index]: modified_secret_key[index] = True count -= 1 sum_ = zero temp = gmpy2.mul_2exp(one, kappa + 1) for i in range(1, Theta): if modified_secret_key[i]: sum_ = gmpy2.add(sum_, Theta_vector[i]) sum_ %= temp u_1 = gmpy2.sub(x_p, sum_) if u_1 < zero: u_1 = gmpy2.add(temp, u_1) return mpz(seed), mpz(u_1)
def get_ord(p): """求循环群的阶""" if gmpy2.is_prime(p): return gmpy2.sub(p, 1) else: print('输入错误,不是素数!') sys.exit(-1)
def decrypt(priv, pub, cipher): one = gmpy2.mpz(1) x = gmpy2.sub(gmpy2.powmod(cipher, priv.l, pub.n_sq), one) plain = gmpy2.f_mod(gmpy2.mul(gmpy2.f_div(x, pub.n), priv.m), pub.n) if plain >= gmpy2.f_div(pub.n, 2): plain = plain - pub.n return plain
def compute_uncertainty_given_interval(low, upper): coefficients = {} with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundDown, precision=mpfr_proxy_precision) as ctx: res_left = gmpy2.sub(gmpy2.div(mpfr(upper), mpfr("2.0")), gmpy2.div(mpfr(low), mpfr("2.0"))) with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundUp, precision=mpfr_proxy_precision) as ctx: res_right = gmpy2.sub(gmpy2.div(mpfr(upper), mpfr("2.0")), gmpy2.div(mpfr(low), mpfr("2.0"))) coefficients[AffineManager.get_new_error_index()]=\ Interval(round_number_down_to_digits(res_left, digits_for_range), round_number_up_to_digits(res_right, digits_for_range), True, True, digits_for_range) return coefficients
def verify(A, x, N): p = gmpy2.sub(A, x) q = gmpy2.add(A, x) if gmpy2.mul(p, q) == N: return [True, p, q] else: return [False, p, q]
def evaluate_error_at_sample(self, tree): """ Sample from the leaf then evaluate tree in the tree's working precision""" if tree.left is not None or tree.right is not None: if tree.left is not None: sample_l, lp_sample_l = self.evaluate_error_at_sample( tree.left) if tree.right is not None: sample_r, lp_sample_r = self.evaluate_error_at_sample( tree.right) if tree.root_name == "+": return (sample_l + sample_r), gmpy2.add( mpfr(str(lp_sample_l)), mpfr(str(lp_sample_r))) elif tree.root_name == "-": return (sample_l - sample_r), gmpy2.sub( mpfr(str(lp_sample_l)), mpfr(str(lp_sample_r))) elif tree.root_name == "*": return (sample_l * sample_r), gmpy2.mul( mpfr(str(lp_sample_l)), mpfr(str(lp_sample_r))) elif tree.root_name == "/": return (sample_l / sample_r), gmpy2.div( mpfr(str(lp_sample_l)), mpfr(str(lp_sample_r))) elif tree.root_name == "exp": return np.exp(sample_l), gmpy2.exp(mpfr(str(sample_l))) elif tree.root_name == "sin": return np.sin(sample_l), gmpy2.sin(mpfr(str(sample_l))) elif tree.root_name == "cos": return np.cos(sample_l), gmpy2.cos(mpfr(str(sample_l))) elif tree.root_name == "abs": return np.abs(sample_l), abs(mpfr(str(sample_l))) else: print("Operation not supported!") exit(-1) else: sample = tree.root_value[0].getSampleSet(n=1)[0] return sample, mpfr(str(sample))
def Q3(): N = mpz('72006226374735042527956443552558373833808445147399984182665305798191\ 63556901883377904234086641876639384851752649940178970835240791356868\ 77441155132015188279331812309091996246361896836573643119174094961348\ 52463970788523879939683923036467667022162701835329944324119217381272\ 9276147530748597302192751375739387929') A = isqrt(mul(6, N)) + 1 # (3 * p + 2 * q) / 2 is not an integer. or, A - 0.5 = (3p + 2q) / 2 # so, x = sqrt((A-0.5)^2 - 6N) = sqrt(A^2 - A + 0.25 - 6N). the 0.25 term can be thrown away. x = isqrt(sub(sub(mul(A, A), A), mul(6, N))) p = div(sub(A, x), 3) q = div(add(A, x), 2) if mul(p, q) == N: print("Q3:") print(p)
def factor_n2(): ''' Factoring challenge #2: The following modulus N is a products of two primes p and q where |p−q| < 2^11 N^(1/4). Find the smaller of the two factors and enter it as a decimal integer. Hint: In this case A−sqrt(N)<2^20 so try scanning for A from sqrt(N) upwards, until you succeed in factoring N. ''' N = gmpy2.mpz( '648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877' ) A = gmpy2.add(gmpy2.isqrt(N), one) x = gmpy2.isqrt(gmpy2.sub(gmpy2.mul(A, A), N)) print 'Calculating second factors...' ticks = 0 q = gmpy2.mpz(A) while True: q = gmpy2.next_prime(q) #gmpy2.add(A, x) p = gmpy2.sub(A, gmpy2.sub(q, A)) #gmpy2.sub(A, x) #print "p is prime?", gmpy2.is_prime(p) #print "q is prime?", gmpy2.is_prime(q) #print "p*q:" #print gmpy2.mul(p,q) #print "N:" #print N #return if gmpy2.is_prime(p) and gmpy2.is_prime(q): print "p =", p, "q =", q, "ticks =", ticks if gmpy2.mul(p, q) == N: print 'Done!' return else: ticks += 1 if ticks % 10000 == 0: print 'ticks:', ticks
def Q2(): N = mpz('6484558428080716696628242653467722787263437207069762630604390703787\ 9730861808111646271401527606141756919558732184025452065542490671989\ 2428844841839353281972988531310511738648965962582821502504990264452\ 1008852816733037111422964210278402893076574586452336833570778346897\ 15838646088239640236866252211790085787877') for d in range(1, 1<<20): A = isqrt(N) + d x = isqrt(sub(mul(A, A), N)) p = sub(A, x) q = add(A, x) if mul(p, q) == N: print("Q2:") print(p) break
def calculate_shared_secret(self): val = powmod(self.generator, self.get_identity_hash(), self.modulus) val2 = mul(self.get_multiplier(), val) val3 = sub(self.get_server_public_value(), val2) val4 = mul(self.get_scrambler(), self.get_identity_hash()) val5 = add(self.get_private_value(), val4) val6 = t_mod(val3, self.modulus) val7 = t_mod(val5, self.modulus) self.shared_secret = powmod(val6, val7, self.modulus)
def q2(): N = 648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877 rt = gmpy2.sqrt(N) A = gmpy2.ceil(rt) q = 0 p = 0 while not gotcha(N, p, q): A2 = pow(A, 2) assert A2 > N x = gmpy2.sqrt(gmpy2.sub(A2, N)) p = gmpy2.sub(A, x) q = gmpy2.add(A, x) assert N == gmpy2.mul(p, q) A += 1
def main(): dlog = DLog(p, g, h) print 'Computing dlog:' result = dlog.compute() diff = gmpy2.sub(h, gmpy2.powmod(g, result, p)) if not result: print "Not found" else: print "Found value: {}".format(result) print "Diff with given solution: {}".format(diff)
def __d_encryption(self, m): d = list() self.__a = list() for i in range(m): di = random.randint(0, 2**255) di = gmpy2.mpz(di) d.append(di) d[i] = gmpy2.f_mod(d[i], q) self.__a.append(gmpy2.sub(d[i], self.__f[0])) self.__a[i] = gmpy2.f_mod(self.__a[i], q)
def factorize(N,ran): for i in ran: A = gmpy2.add(gmpy2.isqrt(N),i) Asq = gmpy2.mul(A,A) diff = gmpy2.sub(Asq, N) x = gmpy2.isqrt_rem(diff)[0] [correct,p,q] = verify(A,x,N) if(correct): print p return [p,q] print "Not Found"
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 factorize(N, ran): for i in ran: A = gmpy2.add(gmpy2.isqrt(N), i) Asq = gmpy2.mul(A, A) diff = gmpy2.sub(Asq, N) x = gmpy2.isqrt_rem(diff)[0] [correct, p, q] = verify(A, x, N) if (correct): print p return [p, q] print "Not Found"
def powers_of_two_spacing(): exp_spacing=[] with gmpy2.local_context(gmpy2.context(), round=gmpy2.RoundToNearest, precision=mpfr_proxy_precision) as ctx: exponent=gmpy2.mpfr("0") while abs(exponent)<discretization_points: value=gmpy2.exp2(exponent) exp_spacing.insert(0, round_number_nearest_to_digits(value, digits_for_input_discretization)) exponent=gmpy2.sub(exponent,gmpy2.mpfr("1")) exp_spacing.insert(0, "0.0") for index, value in enumerate(exp_spacing[:-1]): if value==exp_spacing[index+1]: print("Problem with digits in powers of 2") exit(-1) return exp_spacing
def question3(): N = gmpy2.mul( gmpy2.mpz( "720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929" ), 6) A = gmpy2.ceil(gmpy2.sqrt(N)) #A-N^(1/6)<neg k = gmpy2.sub(gmpy2.square(A), N) print(k) x = gmpy2.ceil(gmpy2.sqrt( k)) #same trick to calculate the other half to recover p,q (3p-2q)/2 print("x:", x) p = (A - x) / 2 q = (A + x) / 3 print("p:", p, "q:", q)
def safe_prime(exponent): for k in range(0, 10000000): p = 10**exponent + k # checks to see if p is prime a = gmpy2.powmod(2, p - 1, p) if (a == 1): # since p is prime, check to see if # p is a safe prime safe_p = gmpy2.c_div(gmpy2.sub(p, 1), 2) if (gmpy2.is_prime(int(safe_p))): print "k = %i \nsafe prime = %i\n" % (k, safe_p) return