Example #1
0
def main():
	print('----------------Lluís----------------')
	prime = decrypt(nLluis)
	print("P: ")
	print(prime)
	print("Q: ")
	prime2 = nLluis//prime
	print(prime2)
	phi_n = (prime - 1) * (prime2 - 1)
	dLluis = sympy.gcdex(e, phi_n)[0]
	privateLluis = RSA.construct((nLluis, e, int(dLluis)))
	outputLluis = open('keyLluis.pem', 'wb')
	outputLluis.write(privateLluis.exportKey('PEM'))
	outputLluis.close()
	
	print('----------------Toni----------------')
	prime3 = decrypt(nToni)
	print("P: ")
	print(prime3)
	print("Q: ")
	prime4 = nToni//prime3
	print(prime4)
	phi_n = (prime3 - 1) * (prime4 - 1)
	dToni = sympy.gcdex(e, phi_n)[0]
	privateToni = RSA.construct((nToni, e, int(dToni)))
	outputToni = open('keyToni.pem', 'wb')
	outputToni.write(privateToni.exportKey('PEM'))
	outputToni.close()
	
	print('-------------------------------------DONETTE-------------------------------------')
Example #2
0
    def __init__(self, equations, field):
        def genus(self):
            """ The arithmetic genus of H """
            f = equations[0].subs(y**2, 0)
            if degree(f) == 3:
                return 1
            else:
                return 2

        self.genus = self.genus()

        def operation((u1, v1), (u2, v2)):
            """ Addition of two divisors using cantor's algorithm """

            f = equations[0].subs(y**2, 0)
            g = self.genus
            e1, e2, d1 = sp.gcdex(u1, u2)
            c1, c2, d = sp.gcdex(d1, v1 + v2)
            s1, s2, s3 = c1 * e1, c1 * e2, c2
            u = u1 * u2 / d**2
            v = sp.rem((s1 * u1 * v2 + s2 * u2 * v1 + s3 * (v1 * v2 + f)) / d,
                       u)

            while sp.degree(u) > g:
                u = (f - v**2) / u
                v = sp.rem(-v, u)

            if u.coeffs()[len(u.coeffs()) - 1] != 1:
                u = u / u.coeffs()[len(u.coeffs()) - 1]

            return (u, v)
Example #3
0
 def sympy_extended_gcd(self, p, q):
     sympy_p = self.sympy_from_upolynomial(p)
     sympy_q = self.sympy_from_upolynomial(q)
     if (p.ring().modulus() is None):
         (u, v, d) = sympy.gcdex(sympy_p, sympy_q)
     else:
         (u, v, d) = sympy.gcdex(sympy_p, sympy_q, modulus=p.ring().modulus())
     return (d.simplify(), u.simplify(), v.simplify())
Example #4
0
def main():
    print('----------------Lluís----------------')
    print(sympy.factorint(nLluis))
    #115281056474331054700251942688513962925044855473544908166056180479356817897219  4 veces
    #3347812451 32 veces
    print("phi(p): ")
    p = 115281056474331054700251942688513962925044855473544908166056180479356817897219**4
    p_1 = (p - 1) * (p**3)
    print(p_1)
    print("phi(q): ")
    q = 3347812451**32
    q_1 = (q - 1) * (q**31)
    print(q_1)
    print("phi(n): ")
    phi_n = p_1 * q_1
    print(phi_n)
    dLluis = sympy.gcdex(e, phi_n)[0]
    privateLluis = RSA.construct((nLluis, e, int(dLluis)))

    outputLluis = open('keyLluis2.pem', 'wb')
    outputLluis.write(privateLluis.exportKey('PEM'))
    outputLluis.close()

    #openssl rsautl -decrypt -inkey keyLluis2.pem -in lluis.marques_RSA_pseudo.enc -out decLluis2

    print('----------------Toni----------------')
    print(sympy.factorint(nToni))
    #3916392617 32 veces
    #238276963031717718724382324364818146621 8 veces
    p2 = 3916392617**32
    p2_1 = (p2 - 1) * (p2**31)
    print("phi(p2): ")
    print(p2_1)
    print("phi(q2): ")
    q2 = 238276963031717718724382324364818146621**8
    q2_1 = (q2 - 1) * (q2**7)
    print(q2_1)
    print("phi(n2): ")
    phi_n2 = p2_1 * q2_1
    print(phi_n2)
    dToni = sympy.gcdex(e, phi_n2)[0]
    dToni = dToni % phi_n2  # dona negatiu, cal fer modul
    privateToni = RSA.construct((nToni, e, int(dToni)))

    outputToni = open('keyToni2.pem', 'wb')
    outputToni.write(privateToni.exportKey('PEM'))
    outputToni.close()

    #openssl rsautl -decrypt -inkey keyToni2.pem -in antonio.guilera_RSA_pseudo.enc -out decToni2

    print(
        '-------------------------------------DONETTE-------------------------------------'
    )
Example #5
0
	def __init__(self, bits_module=2048, e=2**16+1):
		'''
		genera clau RSA de 2048 bits i exponent 2**16+1 per defecte
		'''
		self.bits_module = bits_module
		self.publicExponent = e #enter
		self.generate_primePQ()
		phi_n = (self.primeP - 1) * (self.primeQ - 1)
		self.modulus = self.primeP * self.primeQ #enter -> n = p*q
		#sympy gcdex(a,b) a la pos 0 retorna a**-1 mod (b)
		self.privateExponent = sympy.gcdex(self.publicExponent, phi_n)[0] #enter equivalent a d (referencia a les diapos)
		self.privateExponentModulusPhiP = self.privateExponent % (self.primeP - 1) #congruent amb privateExponent modul prime P - 1, enter
		self.privateExponentModulusPhiQ = self.privateExponent % (self.primeQ - 1)  #congruent amb privatExponent modul Prime Q - 1, enter
		self.inverseQModulusP = sympy.gcdex(self.primeQ, self.primeP)[0] #invers de primeQ^-1 modul primeP, enter
Example #6
0
def _bezout(q,m):
    """
    Given two coprime integers `q,m` with `q>0` returns `u,v` such that
    `uq+mv=1`.
    """
    u,v,g = sympy.gcdex(q,m)
    if u*q+v*m != 1: raise ValueError("Bezout algorithm failed.")
    return u,v
Example #7
0
def find_gh(d, s, r, z):
    f0 = ffx(d, s, z)
    fr = f0.subs(z, z - r)
    g, _h, one = gcdex(f0, fr)
    h = -_h
    assert one == 1

    if not g.is_number:
        assert LC(g) > 0
        assert LC(h) > 0
    else:
        assert g > 0

    return g, h
Example #8
0
 def generate_key(self):
     """
     Генерация RSA-ключа
     :return: кортеж из открытой и закрытой частей
     """
     p = get_random_prime()  # инициализация
     q = get_random_prime()
     n = p * q  # модуль
     phi = euler(p, q)  # функция Эйлера
     e = find_exponent(phi)  # открытая экспонента
     public_key = (e, n)  # открытый ключ
     d, _, gcd = gcdex(e, phi)  # уравнение Евклида
     assert gcd == 1
     d = int((d + phi) % phi)  # секретная экспонента
     private_key = (d, n)  # закрытый ключ
     self.steps = locals()
     return public_key, private_key
from sympy import gcdex
from sympy.abc import x

print(gcdex(x**6 + x**3 + x, x**8 + x**4 + x**3 + x + 1))
Example #10
0
# Problem 1

## Part A

s, k, Q = sp.symbols('s k Q')
P = (4 * (s - 2)) / (s**2 - 2 * s + 2)

# Transform $P(s)$ to $\bar{P}(k)$ under the mapping $s = \frac{1-k}{k}$

P_bar = P.subs({s: (1 - k) / k}).factor().cancel()

n = P_bar.as_numer_denom()[0]
d = P_bar.as_numer_denom()[1]

# Using Euclid’s algorithm, find polynomials $x(k)$, $y(k)$ such that $nx + dy = 1$
x, y, _ = gcdex(n.as_poly(), d.as_poly())

x = (35 / 8) * k - 13 / 8
y = (21 / 2) * k + 1

N = n.subs({k: 1 / (s + 1)}).simplify()
D = d.subs({k: 1 / (s + 1)}).simplify()

X = x.subs({k: 1 / (s + 1)}).simplify()
Y = y.subs({k: 1 / (s + 1)}).simplify()

# by the Youla-Kucera parametrization theorem:
_C = (X + D * Q) / (Y - N * Q)
C = _C.cancel().simplify().collect(Q)

## Part B
        if k < 1:
            return Product(1, (i,0,0))
        
        return Product(n-2*i, (i,0,k-1))
    def IIo(n, k):
        i = sympy.abc.i
        if k < 1:
            return Product(1, (i,0,0))
        return Product(n-2*i-1, (i,0,k-1))

    for k in range(5):
        fe = IIe(n,k).doit()
        fo = IIo(n,k).doit()
        print('IIe(n,{k})= {f} = {ef}'.format(k=k, f=fe, ef=fe.expand()))
        print('IIo(n,{k})= {f} = {ef}'.format(k=k, f=fo, ef=fo.expand()))
        s,t, g = gcdex(fe, fo)
        assert (s*fe + t*fo).expand() == g.expand() == 1

        s = gcd_terms(s)
        _t = gcd_terms(-t)
        print('({s})*IIe(n,{k}) - ({_t})*IIo(n,{k}) = {g}\n'.format(s=s,_t=_t,g=g,k=k))
        c = (-2 d!/(-2)**d)




    
'''
T d z = sum z**i C(i,d) {~i} for [NN d]
u = z/(1-z)
T d z / u**d = \i:(C - z**i/(1-z) sum C(i, k) / u**k {k=0..d})
Example #12
0
b = int(input('b:'))
c = int(input('c:'))
d = int(input('d:'))
e = int(input('e:'))
f = int(input('f:'))
mod = int(input('mod:'))
print()

A = sympy.Matrix([[a, b], [c, d]])
A_det = A.det()
A_inv = A.inv()

A_goudou = A_det % mod
A_inv2 = A_det * A_inv

x, y, t = sympy.gcdex(A_goudou, mod)
A5 = x * A_inv2

a, b, c, d = A5
a %= mod
b %= mod
c %= mod
d %= mod

# A6:求める逆行列
A6 = sympy.Matrix([[a, b], [c, d]])
# a,b,c,d = A6

print('求めるx,yは、')
B1 = sympy.Matrix([e, f])
B2 = A6 * B1
Example #13
0
def inductive_solver(max_n, primes, waiting, run_id, existence, interval,
                     offset):

    #######
    #profiling to track efficiency
    #uncomment this and code at bottom of function
    #######
    #pr = cProfile.Profile()
    #pr.enable()

    global conn
    global c

    #holds self-square data to commit to sql
    commits = []

    #preparing our database
    global conn
    conn = sqlite3.connect('selfsquares.db')
    conn.row_factory = lambda cursor, row: row[0]
    global c
    c = conn.cursor()

    #tracking the sum which will be added to the total at the end
    local_sum = 0

    #x is our n value
    x = 0

    #finding our last completed solution in the database to avoid redundancy
    good = 0
    while not good:
        try:
            start_x = c.execute(
                '''SELECT MAX(modulo) from selfsquares WHERE modulo%{} = {}'''.
                format(interval, offset)).fetchall()
            if start_x[0] != None:
                x = start_x[0] + interval
            good = 1
        except:
            pass

    #handling base case modulos, i.e. n < 4
    #4 is a somewhat arbitrary number
    #this is also where we set up offset counting for each of the multiprocesses
    if x == 0:
        start_val = 0
        while (start_val * interval + offset < 4):
            if start_val * interval + offset > 2:
                local_sum += 1
            start_val += 1

        x = start_val * interval + offset

    ##
    #Beginning the loop through n values
    ##

    #looping through all values of n
    while x < max_n + 1:

        #occasionally update sql database with our current solns
        #offset is also the process identifier in the set of waiting flags
        if len(commits) > 10000 or (waiting[offset] == 1 and len(commits) > 0):
            commits = push_commits(commits, existence)

        #finding the smallest prime divisor
        smallest_prime = x

        upper_bound = int(sqrt(x)) + 1
        for cur_prime in primes:
            if cur_prime > upper_bound:
                break
            if x % cur_prime == 0:
                smallest_prime = cur_prime
                break

        #getting the power of the smallest prime divisor
        smallest_prime_power = smallest_prime
        while (x // smallest_prime_power) % smallest_prime == 0:
            smallest_prime_power *= smallest_prime

        #handling edge cases where our n is a prime power or a power of 2
        #if n is prime power, solns are x-1 or 1
        if smallest_prime_power == x:
            if smallest_prime != 2:
                commits.append([x, x - 1])
                commits.append([x, 1])
                local_sum += 1
                x += interval
                continue
            #if it's a power of two, we just brute force it by checking every possible number for self-squareness
            #powers of two are weird
            #we probably don't have to do this, but whatever
            else:
                max_val = 1
                commits.append([x, x - 1])
                commits.append([x, 1])
                for cur_val in range(int(sqrt(x)), int((x / 2)) + 1):
                    if (cur_val**2) % x == 1:
                        if (-cur_val) % x > max_val:
                            max_val = (-cur_val) % x
                        commits.append([x, cur_val])
                        commits.append([x, (-cur_val) % x])
                local_sum += max_val
                x += interval
                continue

        #so now we have some p^s and this is k. we should technically already have solutions for these
        k = x // smallest_prime_power

        #we have to wait until k, p^n are in our database. other processes might not have done them yet
        #this ugly chunk of code is making sure we have the k, p^n values we need
        good = False
        prime_power_self_squares = []
        k_self_squares = []

        while not existence[smallest_prime_power] == 1:
            #telling the responsible process to hurry up
            waiting[smallest_prime_power % interval] = 1
            #watching in case someone is telling us to hurry up
            if waiting[offset] == 1 and len(commits) > 0:
                commits = push_commits(commits, existence)
        while not existence[k] == 1:
            waiting[k % interval] = 1
            if waiting[offset] == 1 and len(commits) > 0:
                commits = push_commits(commits, existence)

        #we're no longer waiting, update flags
        waiting[smallest_prime_power % interval] = 0
        waiting[k % interval] = 0

        #grab the data we need
        k_self_squares = pull_data(k)
        prime_power_self_squares = pull_data(smallest_prime_power)

        #recall our desired number must satisfy a^2 = 1 mod kp^s
        #where kp^s = n
        #thus it satisfies a^2=1 mod p^s
        #and it satifies a^2=1 mod k
        #so our solution must be modularly equivalent to previous solutions for mod p^s and mod k

        #now we're just leveraging chinese remainder theorem
        #we do crt on every pair of solutions from p^s and k

        max_val = 1
        gcd = sp.gcdex(smallest_prime_power, k)
        for a in prime_power_self_squares:
            for b in k_self_squares:
                #this is the crt part. note the use of extended euclidean algorithm
                next_sol = ((gcd[0] * smallest_prime_power * (b)) +
                            (gcd[1] * k * (a))) % x
                commits.append([x, next_sol])
                if next_sol > max_val and next_sol < x - 1:
                    max_val = next_sol

        local_sum += max_val

        #continuing on this process's share of the n values
        x += interval

    ######
    #cleanup code; submitting remaining data
    ######

    #push any remaining self-squares that have not been updated
    if len(commits) > 0:
        commits = push_commits(commits, existence)

    #update the total sum for this run with our local count
    good = False
    while not good:
        try:
            c.execute(
                '''UPDATE sums SET cursum = cursum + {} WHERE rowid = {}'''.
                format(local_sum, run_id))
            conn.commit()
            good = True
        except:
            pass

    #######
    #profiling to track efficiency
    #uncomment this and code at bottom of function
    #######
    #pr.disable()
    #pr.print_stats(sort='time')

    return
def inductive_solver(max_n):

    #prime sieve for breaking apart solutions
    print("Calculating all necessary primes...")
    primes = [i for i in sieve.primerange(2, int(sqrt(max_n)) + 1)]
    print("Solving...")

    #dictionary for holding previous solution sets
    solutions = dict([(2, [1]), (3, [1, 2])])

    #value for holding our sum solution
    #mod 3 is already included
    sum_sol = 1

    #iterating through all possible modulo
    for x in range(4, max_n + 1):

        #finding the smallest prime divisor
        smallest_prime = x

        upper_bound = int(sqrt(x)) + 1
        for cur_prime in primes:
            if cur_prime > upper_bound:
                break
            if x % cur_prime == 0:
                smallest_prime = cur_prime
                break

        smallest_prime_power = smallest_prime
        while (x / smallest_prime_power) % smallest_prime == 0:
            smallest_prime_power *= smallest_prime

        #handling edge cases where we have a prime power or a power of 2
        if smallest_prime_power == x:
            if smallest_prime != 2:
                solutions.update([(x, [1, x - 1])])
                sum_sol += 1
                continue
            else:
                max_val = 1
                cur_solutions = [1, x - 1]
                for cur_val in range(int(sqrt(x)), int((x / 2)) + 1):
                    if (cur_val**2) % x == 1:
                        if (-cur_val) % x > max_val:
                            max_val = (-cur_val) % x
                        cur_solutions.append(cur_val)
                        cur_solutions.append((-cur_val) % x)
                sum_sol += max_val
                solutions.update([(x, cur_solutions)])
                continue

        k = x / smallest_prime_power

        #once we've found the smallest prime divisor power, our desired number satisfies a^2 = 1 mod lp^k
        #where lp^k = n
        #thus it satisfies a^2=1 mod p^k
        #and it satifies a^2=1 mod l
        #so our solution must be modularly equivalent to solutions mod p^k and solutions mod l

        #now we're just leveraging chinese remainder theorem
        #using an algorithm to find all solutions for each pair of solutions

        cur_sols = []
        #smaller_val = min(smallest_prime_power, k)
        #other_val = max(smallest_prime_power, k)
        max_val = 1
        gcd = sp.gcdex(smallest_prime_power, k)
        for a in solutions[smallest_prime_power]:
            for b in solutions[k]:
                next_sol = ((gcd[0] * smallest_prime_power * (b)) +
                            (gcd[1] * k * (a))) % x
                cur_sols.append(next_sol)
                if next_sol > max_val and next_sol < x - 1:
                    max_val = next_sol
        #print(cur_sols)

        sum_sol += max_val
        #saving our solutions
        solutions.update([(x, cur_sols)])
    return solutions, sum_sol