예제 #1
0
def ECMTrial(N, A, bound, sieve, P):

    # Is always on the curve according to https://www.uam.es/personal_pdi/ciencias/fchamizo/asignaturas/cripto1011/lenstra.pdf

    if u.gcd(N, 6) != 1:
        print('Input is not valid, gcd(N,6) != 1')

    # Preparatory steps before Stage 1
    alpha = u.gcd(A**2 - 4, N)
    if alpha != 1 and alpha != N:
        print("Returning alpha biatch")
        return alpha

    Q = P
    a24 = ((A + 2) / 4) % N

    #print("Calculating, for " + str(len(sieve)) + " primes")

    #Q = ladder.ladder(N, a24, m, Q)
    for l in sieve:
        k = long(math.floor(math.log(bound, l)))
        Q = ladder.ladder(N, a24, (l**k) % N, Q)

    beta = u.gcd(Q[1], N)
    if beta != 1:
        if beta == N:
            print("Found N again ...")
        else:
            print("Nope this time we found " + str(beta) + " when N is " +
                  str(N))
            return beta

    return False
예제 #2
0
    def __new__(cls, num, denom):
        if denom == 0:
            raise ValueError('Denominator cannot be null')
        if denom < 0:
            num, denom = -num, -denom

        return super().__new__(cls, num // gcd(denom, num),
                               denom // gcd(denom, num))
예제 #3
0
def rsa_keygen(n):
    # choose random primes p,q on the order of n / 2 bits
    p = primegen(n // 2)
    q = primegen(n // 2)

    # compute N as product of p,q
    N = p*q

    # compute phi(n)
    pN = (p - 1) * (q - 1)

    # choose public exponent e:
    # must be relatively prime with phi(N)
    e = 3
    while gcd(pN, e) != 1:
        e += 1

    # compute private exponent d:
    # the multiplicative inverse of e, modulo phi(N)
    d = modinv(e, pN)
    while d < 0:   # we want a positive value for d; working modulo phi(N),
        d += pN    # all values d_i = d + k*phi(N) for integer k are equivalent

    # return the components of RSA key
    return (e, d, N)
예제 #4
0
def get_factorization_from_known_roots(number, known_roots):
    """
    Factorizes number to (p x q), where p and q are primes by using known_roots.
    :param number: Number to be factorized
    :type number: int
    :param known_roots: 4 square roots of some x in modulo "number"
    :type known_roots: list[int]
    :return: prime factorization of the number as list
    """
    if len(known_roots) != 4:
        raise ValueError('Wrong number of known roots, expected 4')

    root1 = known_roots[0]
    root2 = None
    for i in known_roots:
        if i != root1 and root1 + i != number:
            root2 = i
            break

    if root2 is None:
        raise ValueError('Root values are wrong!')

    p = gcd(abs(root1 - root2), number)
    q = number / p
    return p, q
예제 #5
0
def p39(n=1000):
    max_p = 0
    max_solutions = 0
    for i in xrange(4, n + 1):
        num_solutions = 0
        divs = getDivisors(i / 2)
        k = [1, i / 2]
        primitives = set()
        for pair in divs:
            k += [pair[0], pair[1]]
        for j in k:
            divs = getDivisors(i / 2 / j)
            for pair in divs:
                if 2 * pair[0] > pair[1]:
                    primitive = sorted([
                        2 * pair[0] * (pair[1] - pair[0]),
                        pair[0]**2 - (pair[1] - pair[0])**2
                    ])
                    temp = gcd(primitive[0], primitive[1])
                    primitive = (primitive[0] / temp, primitive[1] / temp)
                    primitives.add(primitive)
        if len(primitives) > max_solutions:
            max_solutions = len(primitives)
            max_p = i
    print max_p
예제 #6
0
 def __new__(cls, num, denom):
     if denom == 0:
         raise ValueError('Denominator cannot be null')
     factor = gcd(num, denom)
     if denom < 0:
         num, denom = -num, -denom
     return super().__new__(cls, num // factor, denom // factor)
예제 #7
0
def GM_encrypt(msg, pub_key):
    """
    GM message encryption
    """
    x, N = pub_key[0], pub_key[1]
    # msg_binary = format(msg,'b')
    """
    Generating random y_i for every bit in m 
    such that gcd(y_i,N)=1
    """
    count = 0
    y = []
    while count < len(msg):
        yi = random.SystemRandom().randint(1, N - 1)
        if util.gcd(yi, N) == 1:
            count += 1
            y.append(yi)

    c = []
    for i in range(0, len(msg)):
        c_i = (pow(y[i], 2) * pow(x, int(msg[i], 2))) % N
        c.append(c_i)
    """
    Homomorphic property: 
    Note that the values for E[c0].E[c1] may not be
    equal to E[m0^m1]. It just gives both the answers
    as either QRs or QNR.
    """

    return c
def get_coprimes(num):
    """
    Returns a list of integers which are between (0-num) and co-prime with num
    :param num: limit
    :type num: int
    :return: list[int]
    """
    return [x for x in range(num) if x != 0 and gcd(x, num) == 1]
def get_coprime_quadratic_residues(num):
    """
    Returns a list of integers which have square roots in modulo num and are relatively prime with num
    :param num: modulo
    :type num: int
    :return: list[int]
    """
    return [x for x in get_quadratic_residues(num) if gcd(x, num) == 1]
예제 #10
0
def gen_multi_prime_keys():
    p = getPrime(512)
    q = getPrime(512)
    r = getPrime(512)
    #print("primes are :" + str(p) + " " + str(q) + " " + str(r))
    print(p, q, r)
    n = p * q * r
    phi = (p-1) * (q-1) * (r-1)
    e = randrange(1, phi)
    g = gcd(e, phi)
    while g != 1:
        e = randrange(1, phi)
        g = gcd(e, phi)
    e = 41
    d = inv(e, phi)
    #print("d is: " + str(d))
    return [(n, e), (n, d), (p, q, r)]
예제 #11
0
def make_rat(n, d):
    # return cons(n, d)
    g = gcd(abs(n), abs(d))

    sign = 1

    if n < 0 and d >= 0 or d < 0 and n >= 0:
        sign = -1

    return cons(int(abs(n / g) * sign), int(abs(d / g)))
예제 #12
0
def gen_keys():
    p = getPrime(512)
    q = getPrime(512)
    p_s = p**2
    n = p_s * q
    phi = (p_s - p) * (q - 1)
    e = randrange(1, phi)
    g = gcd(e, phi)
    while g != 1:
        e = randrange(1, phi)
        g = gcd(e, phi)
    e = 41
    d = inv(e, phi)

    dp = d % (p - 1)
    dq = d % (q - 1)

    p2_inv_q = inv(p_s, q)
    e_inv_p = inv(e, p)
    #public, private
    return [(n, e), (p, q, dp, dq, p2_inv_q, e_inv_p), d]
예제 #13
0
def get_directions(asteroid):
    directions = defaultdict(lambda: {"location": None, "distance": inf})
    for a in asteroids:
        if a != asteroid:
            # y = 0 at top so invert y change
            direction = (a[0] - asteroid[0], -(a[1] - asteroid[1]))
            distance = sqrt((a[0] - asteroid[0])**2 + (a[1] - asteroid[1])**2)
            distance_gcd = gcd(direction[0], direction[1])
            direction = (direction[0] // distance_gcd,
                         direction[1] // distance_gcd)
            if directions[direction]["distance"] > distance:
                directions[direction] = {"location": a, "distance": distance}
    return directions
예제 #14
0
def sm_note_data(notes, columns):
	if len(notes) == 0: return "" # Some Malody charts are weird
	
	# key = measure number, value = list of notes
	bars = {}
	for note in notes:
		if note.row.bar in bars:
			bars[note.row.bar].append(note)
		else:
			bars[note.row.bar] = [note]
	
	bar_texts = []
	for i in range(max(bars) + 1):
		bar_notes = bars.get(i, None)
		if bar_notes is None:
			# The following generates e.g. for 6k
			# "000000\n000000\n000000\n000000"
			bar_texts.append("\n".join(["0" * columns] * 4))
			continue
		
		snaps = [note.row.snap for note in bar_notes]
		beats = [note.row.beat for note in bar_notes]
		snap = lcm(snaps)
		snap = snap // gcd([snap, *beats]) # Snap is unneccesarily big sometimes
		snap = min(192, snap) # Limit snap to 192nds
		
		rows = [[0] * columns for _ in range(snap)]
		
		for note in bar_notes:
			row_pos = round(note.row.beat / note.row.snap * snap)
			
			# Sometimes we have, say, a beat on 383 when the snap is 384
			# Snapping to 192nds makes that beat become 191.5, which is
			# rounded to 192 and boom, we have an out-of-bounds beat.
			# So we clamp this to snap-1 (191 in this example) to avoid
			row_pos = min(row_pos, snap - 1)
			
			try:
				rows[row_pos][note.column] = note.note_type.to_sm()
			except Exception as e:
				print(row_pos, note.column)
				print("Columns", columns, "Snap", snap)
				raise e
		
		bar_texts.append("\n".join("".join(map(str, row)) for row in rows))
	
	return "\n,\n".join(bar_texts)
def solve(a, b, n):
    """
    Finds and returns all the solutions for x that satisfies ax = b mod n. If no solution exists MathError is raised
    :type a: int
    :type b: int
    :type n: int
    :return: All solutions of x
    :raises MathError if x no solution
    """
    d = gcd(a, n)

    if d == 1:
        return [(b * multiplicative_inverse(a, n)) % n]
    elif b % d == 0:  # d divides b
        x_tilda = (b / d * multiplicative_inverse(a / d, n / d) % n / d)
        return [x_tilda + i * n / d for i in range(d)]
    else:
        raise MathError('No x solves the equation!')
예제 #16
0
def to_EIGamal_DigitalSignature_as_sender(p, g, r, R, M):
    """
    Return the signature of M

    params: p, integer, prime number
            g, integer
            r, integer, random number [1, p-1]
            R, integer, random number [1, p-2]
            m, integer, the message that sender want to send
    return (M, X, Y) , (X, Y) is the signature such that
            compute X = g ^ R mod p
            find Y such that M = r * X + R * Y mod (p-1)
            Y = (M - r * X) * R^-1 mod (p - 1)
    """
    assert gcd(R, p-1) == 1, '{%d , %d} is not coprime.'%(R, p-1)
    X = g ** R % p
    R_inv = get_multiplicative_inverse(R, p-1)
    Y = (M - r * X) * R_inv % (p - 1)
    return M, X, Y
예제 #17
0
def p33(n=2):
    numerators=[]
    denominators=[]
    for i in xrange(10**(n-2),10**(n-1)):
        for j in xrange(10**(n-2),10**(n-1)):
            if i==j:
                continue
            for k in xrange(1,10):
                numerator=10*i+k
                denominator=j+10**(n-1)*k
                if numerator >= denominator:
                    continue
                if numerator/(denominator+0.0)==i/(j+0.0):
                    numerators.append(i)
                    denominators.append(j)
    numerator=reduce(lambda a,b:a*b,numerators)
    denominator=reduce(lambda a,b:a*b,denominators)
    divisor=gcd(numerator, denominator)
    numerator/=divisor
    denominator/=divisor
    print numerator,denominator
예제 #18
0
"""
This file contains a solution for the first Project Euler problem.
https://projecteuler.net/problem=1

Author: Clinton Morrison
File:   001.py
"""
import util

print sum([x for x in xrange(1, 1001) if util.gcd(x, 15) > 1])
예제 #19
0
import math
from PIL import Image, ImageDraw

imageDimensions = (1920,1080)
#imageDimensions = (2048,2048)
numSubdivisions = 2160

center = (imageDimensions[0] / 2, imageDimensions[1] / 2)
radius = [270, 270]

start = 1
end = 21

for j in range(start, end):
    for k in range(j+1, end):
        if util.gcd(j, k) != 1:
            continue
        canvas = Image.new('RGBA', imageDimensions, (0, 0, 0, 255))
        painter = ImageDraw.Draw(canvas)

        tInc = 1 / numSubdivisions
        points = []
        for i in range(numSubdivisions + 1):
            t = i * tInc
            angleRad = t * 2 * math.pi * j
            point = ( center[0] + radius[0] * math.cos(angleRad),
                center[1] + radius[0] * math.sin(angleRad) )
            angleRad = (-t * 2 * math.pi) * k
            point = ( point[0] + radius[1] * math.cos(angleRad),
                point[1] + radius[1] * math.sin(angleRad) )
            points.append(point)
예제 #20
0
    def is_gcd(i):
        if i < n and gcd(i, n) == 1:
            return True

        return False
예제 #21
0
def denom(x):
    g = gcd(car(x), cdr(x))

    return int(cdr(x) / g)
import util
import math
from PIL import Image, ImageDraw

imageDimensions = (1920,1080)
canvas = Image.new('RGBA', imageDimensions, (0, 0, 0, 255))

painter = ImageDraw.Draw(canvas)

center = (imageDimensions[0] / 2, imageDimensions[1] / 2)

radius = 270
kNum = 3
kDen = 1
kDenReduced = int(kDen / util.gcd(kNum, kDen))
maxAngleRad = math.pi * kDenReduced
numSubdivisions = 360 * kDenReduced
angleRadInc = maxAngleRad / numSubdivisions
points = []
colors = util.color_gradient(numSubdivisions)

for t in range(numSubdivisions + 1):
    angleRad = t * angleRadInc
    r = radius * math.cos(kNum / kDen * angleRad)
    x = center[0] + r * math.cos(angleRad)
    y = center[1] + r * math.sin(angleRad)
    points.append((x, y))

print("Number of points: %d" % len(points))
for i in range(len(points) - 1):
    painter.line([points[i], points[i+1]], fill=colors[i], width=2)
예제 #23
0
def numer(x):
    g = gcd(car(x), cdr(x))

    return int(car(x) / g)
예제 #24
0
from util import gcd

stop = 12000
answer = 0

for i in xrange(1, stop + 1):
    xx = i / 3
    yy = i / 2 + 2
    for j in xrange(xx, yy):
        if gcd(i, j) != 1: continue  #counted earlier
        if 3 * j > i and 2 * j < i: answer += 1

print answer
예제 #25
0
 def reduce(self):
     x = gcd(self.num, self.denom)
     self.num /= x
     self.denom /= x
예제 #26
0
def make_rat(n, d):
    # return cons(n, d)
    g = gcd(n, d)
    
    return cons(int(n / g), int(d / g))