Пример #1
0
def decryption():
    with open('pubkey.pem') as handle:
        r = handle.read()

    ne = RSA.import_key(r)
    modulus = ne.n
    exponent = ne.e
    factor_n = primefac.factorint(modulus)
    primes = list(factor_n)
    primes = [int(i) for i in primes]
    p = primes[0]
    phi = (p**2) * (p - 1)
    d = inverse(exponent, phi)

    with open('key') as handle1:
        r1 = bytes.fromhex(handle1.read())

    aes_key = pow(bytes_to_long(r1), d, modulus)
    ltb = long_to_bytes(aes_key)
    aes = AES.new(ltb, AES.MODE_ECB)

    with open("flag.txt.aes", 'rb') as handle2:
        flag = handle2.read().strip()

    print("Flag: ", aes.decrypt(flag))
def crack_key(e, n):
    write_with_indent('Crack key: -e {} -n {}'.format(e, n))
    print()
    write_then_dots('Cracking Public_Key')
    factors_list = []
    for i in primefac.factorint(n):
        factors_list.append(i)

    p = 0
    q = 0

    if len(factors_list) == 2:
        p = factors_list[0]
        q = factors_list[1]

    n = p * q
    phi = (p - 1) * (q - 1)

    d = primefac._primefac.modinv(e, phi)

    privatekey = (d, p, q)
    write_with_indent()
    print()

    write_with_indent(
        'Private Key found: -d {} -p {} -q {}'.format(*privatekey))
Пример #3
0
def table_stats(max_val, prime_factors=True):
    """Return some statistics on a pythagoras table of size max_val
    
    Returns a tuple with two dictioaries.
    Count the number of occurences of number is a pythagoras table of size max_val.
    This is returnes as a dictionary with the number as key and its occurence as value.
    Also return a the prime factors of the numbers as a dictionary, whem prime_factors
    is True. Otherwise returns an empty dictionary.
    """
    count_num = { }
    prime_fac = { }

    # initialize count of occurrences of a certain number
    for i in range(1, max_val*max_val+1):
        count_num[i] = 0;

    # calculate the pythagorean square and count occurrence of each number
    for i in range(1, max_val+1):
        for j in range(1, max_val+1):
            count_num[i*j] += 1

    # make a dictionary of prime factors of all the numbers
    if(prime_factors):
        for tuple in count_num.items():
            prime_fac[tuple[0]] = primefac.factorint(tuple[0]) 
    
    return (count_num, prime_fac)
Пример #4
0
        def factor_n():
            # if n is given but p and q are not, try TO factor n.
            if self.p == -1 and self.q == -1 and self.n != -1:
                factors = list([int(x) for x in primefac.factorint(self.n)])
                if len(factors) == 2:
                    self.p, self.q = factors
                elif len(factors) == 1:
                    raise NotImplemented("factordb could not factor this!")
                else:
                    # This is the case for Multi-factor RSA!
                    # raise NotImplemented("We need support for multifactor RSA!")

                    # Multiply all factors together to get phi

                    self.phi = reduce(mul, [factor - 1 for factor in factors],
                                      1)

                    # Calulate the new d private key
                    self.d = inverse(self.e, self.phi)

                    # Now calculate the plaintext
                    self.m = pow(self.c, self.d, self.n)

                    # Grab the result and give it to Katana
                    print(self.m)
                    result = long_to_bytes(self.m).decode()
                    self.manager.register_data(self, result)
                    return
Пример #5
0
def factor_N(N):
    f = primefac.factorint(N)
    r = []
    for p, alpha in f.items():
        for i in range(alpha):
            r.append(p)
    return sorted(r)
Пример #6
0
def factors(num):
    primedict = primefac.factorint(house)
    primelist = reduce(lambda x, y: x + [y[0]] * y[1], primedict.iteritems(), [])
    combos = reduce(
        operator.or_, (set(itertools.combinations(primelist, n)) for n in range(1, len(primelist) + 1)), set()
    )
    return [reduce(operator.mul, c, 1) for c in combos] + [1]
Пример #7
0
def hasExDistinctPrimeFactors(number, x):
    # pad("Looking for prime factors of "+str(number))
    primeFactors = primefac.factorint(number).keys()
    if len(primeFactors) >= x:
        # pad(str(number)+" has "+str(len(primeFactors))+">="+str(x)+" prime factors")
        # pad(str(primeFactors))
        return True
    # pad(str(number)+" does not have "+str(x)+" distinct prime factors")
    return False
Пример #8
0
def factor_N_with_multiplicative_group(N):
    f = primefac.factorint(N)
    r = []
    phi_hint = {}
    for p, alpha in f.items():
        for i in range(alpha):
            r.append(p)
        phi_hint[p] = factor_N(p - 1)
    return sorted(r), phi_hint
Пример #9
0
def solve4(n1, n2, n3, n4, n5, n6):
    t1 = n2 - n1
    t2 = n3 - n2
    t3 = n4 - n3
    t4 = n5 - n4
    t5 = n6 - n5
    N = GCD(t3*t1 - t2**2, t5*t2 - t4*t3)
    factors = primefac.factorint(N)
    while not isPrime(N):
        for prime, order in factors.items():
            if prime.bit_length() > 128:
                continue
            N = N / prime**order
    return solve3(N, n1, n2, n3)
Пример #10
0
def find_discrete_log(g, h, p):
    """
	Tries to find discrete logarithm for g^x=h mod p
	chooses optimal algorithm
	"""
    d = primefac.factorint(p)
    if (len(d.keys()) == 1):
        for div in d.keys():
            if (d[div] == 1):
                return baby_step_giant_step(g, h, p)
            else:
                return prime_power_groups(g, h, div, d[div])
            return -1
    else:
        return Pohlig_Hellman(d, g, h, p)
Пример #11
0
def lcm(nums):
    factors = Counter()
    for n in nums:
        factors |= factorint(n)
    return reduce(operator.mul, factors.elements(), 1)
Пример #12
0
def factor(n):
    if log2(n) > 128:
        return yafu.factor(n, silent=factor_silent)
    else:
        return primefac.factorint(n)
Пример #13
0
                r.sendline('%d' % point[0])
                r.sendline('%d' % point[1])
                r.sendline('%d' % point[2])
            print "ROUND 3 DONE"

            # Part Four
            log.info('GOURN 4')
            point = handle(lambda x: not isPrime(x))
            if not DEBUG:
                r.sendline('%d' % point[0])
                r.sendline('%d' % point[1])
                r.sendline('%d' % point[2])
            print "ROUND 4 DONE"

            # Part Four
            log.info('GOURN 5')
            point = handle(lambda x: len(primefac.factorint(x)) == 3)
            # point = handle(lambda x: reduce(lambda a,b: a+b, primefac.factorint(x).values()) == 3)
            if not DEBUG:
                r.sendline('%d' % point[0])
                r.sendline('%d' % point[1])
                r.sendline('%d' % point[2])
            print "ROUND 5 DONE"

            r.interactive()
        except Exception, e:
            print 'F**K!!! {}'.format(e)
            r.close()
        else:
            r.interactive()
Пример #14
0
def grog(kx,
         ky,
         k,
         N,
         M,
         Gx,
         Gy,
         precision=2,
         radius=.75,
         Dx=None,
         Dy=None,
         coil_axis=-1,
         ret_image=False,
         ret_dicts=False,
         use_primefac=False,
         remove_os=True,
         inverse=False):
    '''GRAPPA operator gridding.

    Parameters
    ----------
    kx, ky : array_like
        k-space coordinates (kx, ky) of measured data k.  kx, ky
        should each be a 1D array.  Must both be either float or
        double.
    k : array_like
        Measured  k-space data at points (kx, ky).
    N, M : int
        Desired resolution of Cartesian grid.
    Gx, Gy : array_like
        Unit GRAPPA operators.
    precision : int, optional
        Number of decimal places to round fractional matrix powers to.
    radius : float, optional
        Radius of ball in k-space to from Cartesian targets from
        which to select source points.
    Dx, Dy : dict, optional
        Dictionaries of precomputed fractional matrix powers.
    coil_axis : int, optional
        Axis holding coil data.
    ret_image : bool, optional
        Return image space result instead of k-space.
    ret_dicts : bool, optional
        Return dictionaries of fractional matrix powers.
    use_primefac : bool, optional
        Use prime factorization to speed-up fractional matrix
        power precomputations.
    remove_os : bool, optional
        Remove oversampling factor.
    inverse : bool, optional
        Do the inverse gridding operation, i.e., Cartesian points to
        (kx, ky).

    Returns
    -------
    res : array_like
        Cartesian gridded k-space (or image).
    Dx, Dy : dict, optional
        Fractional matrix power dictionary for both Gx and Gy.

    Raises
    ------
    AssertionError
        When (kx, ky) have different types.
    AssertionError
        When (kx, ky) and k do not have matching types, i.e.,
        if (kx, ky) are float32, k must be complex64.

    Notes
    -----
    Implements the GROG algorithm as described in [1]_.

    References
    ----------
    .. [1] Seiberlich, Nicole, et al. "Self‐calibrating GRAPPA
           operator gridding for radial and spiral trajectories."
           Magnetic Resonance in Medicine: An Official Journal of the
           International Society for Magnetic Resonance in Medicine
           59.4 (2008): 930-935.
    '''

    # Make sure types are consistent before calling grog funcs
    assert kx.dtype == ky.dtype, (
        '(kx, ky) must both be either double or float!')
    assert (k.dtype == np.complex64 if kx.dtype == np.float32 else k.dtype
            == np.complex128), ('(kx, ky) and k must have matching types!')

    # Coils to the back
    k = np.moveaxis(k, coil_axis, -1)
    _ns, nc = k.shape[:]

    if not inverse:
        # We have samples at (kx, ky).  We want new samples on a
        # Cartesian grid at, say, (tx, ty). Let's also oversample:
        N, M = 2 * N, 2 * M

    # Create the target grid (or source grid for inverse gridding)
    tx, ty = np.meshgrid(
        np.linspace(np.min(kx), np.max(kx), N, dtype=kx.dtype),
        np.linspace(np.min(ky), np.max(ky), M, dtype=kx.dtype))
    tx, ty = tx.flatten(), ty.flatten()

    # We only want to do work inside the region of support:
    # estimate as a circle for now, works well with radial
    outside = np.argwhere(np.sqrt(tx**2 + ty**2) > np.max(kx)).squeeze()
    inside = np.argwhere(np.sqrt(tx**2 + ty**2) <= np.max(kx)).squeeze()
    tx = np.delete(tx, outside)
    ty = np.delete(ty, outside)

    if inverse:
        # We want to fill all non-cartesian locations, so the region
        # of support is the whole thing (all indices)
        k = np.delete(k, outside, axis=0)
        inside = np.arange(kx.size, dtype=int)

    # Swap coordinates if doing inverse (cartesian to radial)
    if inverse:
        kx, tx = tx, kx
        ky, ty = ty, ky
    kxy = np.concatenate((kx[:, None], ky[:, None]), axis=-1)
    txy = np.concatenate((tx[:, None], ty[:, None]), axis=-1)

    # Find all targets within radius of source points
    kdtree = cKDTree(kxy)
    idx = kdtree.query_ball_point(txy, r=radius)

    # The result will be shaped different if we are doing inverse
    # gridding:
    if inverse:
        res = np.zeros((tx.size, nc), dtype=k.dtype)
    else:
        res = np.zeros((N * M, nc), dtype=k.dtype)

    t0 = time()
    # Handle both single and double floating point calculations,
    # have to do it in separate functions because Cython...
    if tx.dtype == np.float32:
        key_x, key_y = grog_powers_float(tx, ty, kx, ky, idx, precision)
    else:
        key_x, key_y = grog_powers_double(tx, ty, kx, ky, idx, precision)
    print('Took %g seconds to find required powers' % (time() - t0))

    # If we have provided dictionaries, whitle down the work to only
    # those powers not already computed
    t0 = time()
    if Dx:
        key_x = key_x - set(Dx.keys())
    else:
        Dx = {}
    if Dy:
        key_y = key_y - set(Dy.keys())
    else:
        Dy = {}

    # Precompute deficient matrix powers
    if use_primefac:
        # Precompute matrix powers using prime factorization
        from primefac import factorint  # pylint: disable=E0401
        scale_fac = 10**precision

        # Start a dictionary of fractional matrix powers
        frac_mats_x = {}
        frac_mats_y = {}

        # First thing we need is the scale factor, note that we will
        # assume the inverse!
        lscale_fac = np.log(scale_fac)
        frac_mats_x[lscale_fac] = np.linalg.pinv(fmp(Gx, lscale_fac)).astype(
            k.dtype)
        frac_mats_y[lscale_fac] = np.linalg.pinv(fmp(Gy, lscale_fac)).astype(
            k.dtype)

        for keyx0, keyy0 in tqdm(zip(key_x, key_y),
                                 total=len(key_x),
                                 leave=False,
                                 desc='Dxy'):

            dx0 = np.exp(np.abs(keyx0)) * scale_fac
            dy0 = np.exp(np.abs(keyy0)) * scale_fac
            rx = factorint(int(dx0))
            ry = factorint(int(dy0))

            # Component fractional powers are log of prime factors;
            # add in the scale_fac term here so we get it during the
            # multi_dot later.  We explicitly cast to integer because
            # sometimes we run into an MPZ object that doesn't play
            # nice with numpy
            lpx = np.log(np.array([int(r) for r in rx.keys()] +
                                  [scale_fac])).squeeze()
            lpy = np.log(np.array([int(r) for r in ry.keys()] +
                                  [scale_fac])).squeeze()
            lpx_unique = np.unique(lpx)
            lpy_unique = np.unique(lpy)

            # Compute new fractional matrix powers we haven't seen
            for lpxu in lpx_unique:
                if lpxu not in frac_mats_x:
                    frac_mats_x[lpxu] = fmp(Gx, lpxu)
            for lpyu in lpy_unique:
                if lpyu not in frac_mats_y:
                    frac_mats_y[lpyu] = fmp(Gy, lpyu)

            # Now compose all the matrices together for this point
            nx = list(rx.values()) + [1]  # +1 to account for scale_fac
            ny = list(ry.values()) + [1]
            Dx[np.abs(keyx0)] = np.linalg.multi_dot([
                np.linalg.matrix_power(frac_mats_x[lpx0], n0).astype(k.dtype)
                for lpx0, n0 in zip(lpx, nx)
            ])
            Dy[np.abs(keyy0)] = np.linalg.multi_dot([
                np.linalg.matrix_power(frac_mats_y[lpy0], n0).astype(k.dtype)
                for lpy0, n0 in zip(lpy, ny)
            ])

            if np.sign(keyx0) < 0:
                Dx[keyx0] = np.linalg.pinv(Dx[np.abs(keyx0)]).astype(k.dtype)
            if np.sign(keyy0) < 0:
                Dy[keyy0] = np.linalg.pinv(Dy[np.abs(keyy0)]).astype(k.dtype)

    else:
        for key0 in tqdm(key_x, leave=False, desc='Dx'):
            Dx[np.abs(key0)] = fmp(Gx, np.abs(key0)).astype(k.dtype)
            if np.sign(key0) < 0:
                Dx[key0] = np.linalg.pinv(Dx[np.abs(key0)]).astype(k.dtype)
        for key0 in tqdm(key_y, leave=False, desc='Dy'):
            Dy[np.abs(key0)] = fmp(Gy, np.abs(key0)).astype(k.dtype)
            if np.sign(key0) < 0:
                Dy[key0] = np.linalg.pinv(Dy[np.abs(key0)]).astype(k.dtype)
    print('Took %g seconds to precompute fractional matrix powers' %
          (time() - t0))

    # res is modified inplace
    if res.dtype == np.complex64:
        grog_gridding_float(tx, ty, kx, ky, k, idx, res, inside, Dx, Dy,
                            precision)
    else:
        grog_gridding_double(tx, ty, kx, ky, k, idx, res, inside, Dx, Dy,
                             precision)

    if inverse:
        retVal = res
    else:
        # Remove the oversampling factor and return in kspace or
        # imspace
        ax = (0, 1)
        im = None
        if remove_os:
            N4, M4 = int(N / 4), int(M / 4)
            im = np.fft.fftshift(np.fft.ifft2(np.fft.ifftshift(res.reshape(
                (N, M, nc), order='F'),
                                                               axes=ax),
                                              axes=ax),
                                 axes=ax)[N4:-N4, M4:-M4, :]
            res = np.fft.ifftshift(np.fft.fft2(np.fft.fftshift(im, axes=ax),
                                               axes=ax),
                                   axes=ax)

        if ret_image:
            if im is None:
                retVal = np.fft.fftshift(np.fft.ifft2(np.fft.ifftshift(
                    res.reshape((N, M, nc), order='F'), axes=ax),
                                                      axes=ax),
                                         axes=ax)
            else:
                retVal = im
        else:
            retVal = res

    # If the user asked for the precomputed dictionaries back, add
    # them to the tuple of returned values
    if ret_dicts:
        retVal = (retVal, Dx, Dy)

    return retVal
Пример #15
0
def totient(n):
    totient = n
    for factor in factorint(n):
        totient -= totient // factor
    return totient
import python23_encoding

c = gmpy2.mpz(
    5499541793182458916572235549176816842668241174266452504513113060755436878677967801073969318886578771261808846567771826513941339489235903308596884669082743082338194484742630141310604711117885643229642732544775605225440292634865971099525895746978617397424574658645139588374017720075991171820873126258830306451326541384750806605195470098194462985494
)

d = gmpy2.mpz(
    15664449102383123741256492823637853135125214807384742239549570131336662433268993001893338579081447660916548171028888182200587902832321164315176336792229529488626556438838274357507327295590873540152237706572328731885382033467068457038670389341764040515475556103158917133155868200492242619473451848383350924192696773958592530565397202086200003936447
)

phi = gmpy2.mpz(
    25744472610420721576721354142700666534585707423276540379553111662924462766649397845238736588395849560582824664399879219093936415146333463826035714360316647265405615591383999147878527778914526369981160444050742606139799706884875928674153255909145624833489266194817757115584913491575124670523917871310421296173148930930573096639196103714702234087492
)

start_time = time.time()
factors_ = primefac.factorint(phi)

print('[DEBUG] complete integer factorization in %f s' %
      (time.time() - start_time))

## parse factors into list

factors = []

for k, v in factors_.items():
    for i in range(v):
        factors.append(k)

## generate all 2-subsets of factors

indices = range(len(factors))
Пример #17
0
#!/usr/bin/env python2

import primefac

from trmr import *

Modulus = 0xD546AA825CF61DE97765F464FBFE4889AD8BF2F25A2175D02C8B6F2AC0C5C27B67035AEC192B3741DD1F4D127531B07AB012EB86241C09C081499E69EF5AEAC78DC6230D475DA7EE17F02F63B6F09A2D381DF9B6928E8D9E0747FEBA248BFFDFF89CDFAF4771658919B6981C9E1428E9A53425CA2A310AA6D760833118EE0D71

p, q = primefac.factorint(Modulus)

e = 65537
d = modinv(e, (p - 1) * (q - 1))
print rsapem(d, e, Modulus)
Пример #18
0
con.sendline(is_feasible)
if is_feasible == "Y":
	con.recv()
	n = int(p)*int(q)
	con.sendline(str(n))


# t.sleep(0.5)
if context.log_level != 50:
	print("#### Q2")
output = con.recvuntil("IS THIS POSSIBLE and FEASIBLE? (Y/N):")
p = int(re.findall(r"p : (.*)", output)[0])
n = int(re.findall(r"n : (.*)", output)[0])

# we already have p
newp, q = primefac.factorint(n).keys()
is_feasible = "Y" if newp == p else "N"
con.sendline(is_feasible)

if is_feasible == "Y":
	con.recv()
	con.sendline(str(q))




# t.sleep(0.5)
if context.log_level != 50:
	print("#### Q3")
output = con.recvuntil("IS THIS POSSIBLE and FEASIBLE? (Y/N):")
e = int(re.findall(r"e : (.*)", output)[0])
Пример #19
0
def smooth(i, b):
    f = primefac.factorint(i)
    for j in f.keys():
        if j > b:
            return False
    return True
Пример #20
0
def primefac_library(n):
    primes_and_exps = factorint(n)
    values = [[(f ** e) for e in range(exp + 1)] for (f, exp) in primes_and_exps.iteritems()]
    return set(functools.reduce(operator.mul, v, 1) for v in product(*values))
Пример #21
0
def get_prime_factors(x):
    """
    Factorizes a give number into a list of prime factors
    """
    return primefac.factorint(x)
Пример #22
0
    2281, 2287, 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
    2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423, 2437, 2441,
    2447, 2459, 2467, 2473, 2477
]

f = open('output.txt', 'r')
s = []

inp = f.readlines()

N = int(inp[1][3:])
e = 65537

for sig in inp[3:]:
    s.append(int(sig[48:]))

p2s = dict(zip(prime_list, s))
forged_sig = 1

challenge = int(input('Enter Challenge Number: '))

for fac, mult in primefac.factorint(challenge).iteritems():
    try:
        forged_sig *= p2s[fac]**mult
    except KeyError:
        print 'One or more prime factor signatures not computed.'
        print 'Factorization: ' + str(primefac.factorint(challenge))
        sys.exit(0)

print 'Final sig: ' + str(forged_sig % N)