Beispiel #1
0
def common_factor_attack(n1, n2):
    p = gmpy2.gcd(n1, n2)
    if p == 1:
        print("n1 and n2 are not common. \nAttack failed...")
    else:
        print("n1 and n2 are common! \nAttack success")
    return p, gmpy2.divexact(n1,p), gmpy2.divexact(n2,p)
Beispiel #2
0
def is_factor_base_compatible(a, fac_base):
  ''' returns true iff a can be completely factorised by the primes in fac_base'''
  factorisation = [0]*len(fac_base)
  for ind, p in enumerate(fac_base):
    while a%p == 0: # p is a factor of a
      factorisation[ind] +=1
      a = gmpy2.divexact(a,p)
      if a == 1:
        return (True, factorisation)
  return (False, None)
Beispiel #3
0
 def matrix_entry_after_pivot(self, i, j, pivotRow, pivotColumn,
                              pivotElement):
     if self.drop_objective_value and i == 0 and j == 0:
         return mpz(0)
     if i == pivotRow:
         if j == pivotColumn:
             return self.det
         if pivotElement > 0:
             return self.matrix[i][j] * mpz(-1)
         else:
             return self.matrix[i][j]
     if j == pivotColumn:
         if pivotElement < 0:
             return self.matrix[i][j] * mpz(-1)
         else:
             return self.matrix[i][j]
     nominator = self.matrix[i][j] * pivotElement - self.matrix[i][
         pivotColumn] * self.matrix[pivotRow][j]
     return divexact(nominator, self.det)
Beispiel #4
0
    def __init__(self, EFp, EFpk, E, P, Q, r, Qp=None, frob=None, gam=None, bet = None):
        self.E = E #Elliptic Curve (equation) over EFp
        self.EFp = EFp # Elliptic Curve Group
        self.Fp = EFp.F # Field of the ECG
        self.Fp1 = self.Fp.one()
        self.Fp0 = self.Fp.zero()
        self.EFpk = EFpk
        self.Fpk = EFpk.F
        self.Fpk1 = self.Fpk.one()
        self.Fpk0 = self.Fpk.zero()

        self.frobenius = frob
        self.gamma = gam
        #self.beta = bet

        self.P = P # Generator of G1
        self.Q = Q # Generator of G2
        #self.Qp = Qp
        self.r = r # This is the order of the subgroups G1, G2
        def degext(M,L):
            '''Return the degree of the extension of M over L (provided M,L are Fields)
            Assuming M is an extension of L
            '''
            assert isinstance(M,field.Field) and isinstance(L,field.Field)
            k = 1
            while not M.F == M:
                k = k*(M.deg-1)
                M = M.F
                if M == L :
                    return k
        k = degext(self.Fpk,self.Fp) # This is the degree of the extension EFpk over EFp
        q = self.Fp.char-1

        self.e = gmpy.divexact(q**(k)-1,self.r)


        self.to_fingerprint = ["E","EFp","EFpk","r"]
        self.to_export = {"fingerprint": [],"value": ["E","EFp","EFpk","r"]}
Beispiel #5
0
def main(cert_path, data_path):
  mod = get_modulus(cert_path)
  mod = int(mod, 16)
  key_size = int(mod.bit_length() / 16)
  print('Key size: %d'%key_size)
  with open(data_path, 'rb') as f:
    data = f.read()
  print('Data length: %d'%len(data))
  length = len(data) - key_size
  for i in range(length):
    if i % 100000 == 0:
      sys.stdout.write(chr(27) + '[%dG'%(1) + chr(27) + '[0K')
      sys.stdout.write('Progress: %d%%'%(100.0*i/length))
      sys.stdout.flush()
    if data[i] % 2 == 0:
      continue
    p = long(data, i, key_size)
    mod
    if p != 0 and p != 1 and p != mod and mod % p == 0:
      sys.stdout.write(chr(27) + '[%dG'%(1) + chr(27) + '[0K')
      q = gmpy2.divexact(mod,p)
      print('%s Offset 0x%x:\nq = %s\np = %d\n'%(data_path, i, p, q))
      n = gmpy2.mpz(mod)
      q2 = gmpy2.mpz(p)
      e = gmpy2.mpz(65537)
      p2 = gmpy2.mpz(q)
      phi = (p2-1) * (q2-1)
      d = gmpy2.invert(e, phi)
      dp = d % (p2 - 1)
      dq = d % (q2 - 1)
      qinv = gmpy2.invert(q2, p2)
      seq = Sequence()
      for x in [0, mod, e, d, p2, q2, dp, dq, qinv]:
        seq.setComponentByPosition (len (seq), Integer (x))
      print("\n\n-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n\n"%base64.encodebytes(encoder.encode(seq)).decode('ascii'))
      sys.exit(0)
  sys.stdout.write(chr(27) + '[%dG'%(1) + chr(27) + '[0K')
Beispiel #6
0
 def divide_by(self, div):
     self.a = np.array([divexact(a_i, div) for a_i in self.a])
     self.b = divexact(self.b, div)
     self.matrix = self.as_matrix()
     self.a_norm = np.linalg.norm([float(a_i) for a_i in self.a])
Beispiel #7
0
            pp = pp * p
    g = gmpy2.gcd(c - 1, n)
    #print("g = ",g)
    if (1 < g < n):
        return g
    return 1


numtofactor = mpz(int(input("Enter number to factor: ")))
bfac = mpz(int(input("Enter b: ")))
#numtofactor = 87463
#bfac = 120
print("Factors: [", end="")

primelist = primes(bfac)
#print("primelist = ",primelist)
while (True):
    if (numtofactor != 1): print("numtofactor = ", numtofactor)
    factor = pminus1(numtofactor, bfac)
    if gmpy2.is_prime(factor):
        print(str(factor) + ",", flush=True, end="")
        numtofactor = gmpy2.divexact(numtofactor, factor)
        if gmpy2.is_prime(numtofactor):
            # We are done.  All prime factors found
            print(str(numtofactor) + "]")
            exit(0)
    else:
        realfactor = gmpy2.divexact(numtofactor, factor)
        print(str(realfactor) + ",", flush=True, end="")
        numtofactor = factor
Beispiel #8
0
B = gmpy2.isqrt(24*N) + 1

tmp = B*B-24*N

woop = gmpy2.iroot(tmp,2)
if woop[1] == True:
  x = woop[0]
else:
  print("not a square")
  quit()

tmp = B - x

if not tmp%3:
  p = gmpy2.divexact(tmp,6)
  q = gmpy2.divexact(B+x,4)
else:
  p = gmpy2.divexact(tmp,4)
  q = gmpy2.divexact(B+x,6)

if p*q == N:
  print("third factoring challenge")
  print("p=",p)

# fourth assignment

print("-----------------")

cb=mpz(22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256465839967942889460764542040581564748988013734864120452325229320176487916666402997509188729971690526083222067771600019329260870009579993724077458967773697817571267229951148662959627934791540)
def main():

    # Test local versions of libraries

    utils.test_python_version()
    utils.test_gmpy2_version()

    # Parse command line arguments

    parser = argparse.ArgumentParser(description="Generate BBS parameters.")

    parser.add_argument(
        "input_file",
        help=
        """JSON file containing the seed used for generating the pseudo strong 
                                              strong prime (the name is "seed"). The required
                                              quantity of entropy it should contain depends on bitsize. As a rule of
                                              thumb the seed should contain at least 4*bitsize bits of entropy."""
    )
    parser.add_argument(
        "output_file",
        help=
        """Output JSON file where this script will write the two generated strong
                                               strong primes "p" and "q". The output file should not exist already."""
    )
    parser.add_argument(
        "min_prime_bitsize",
        type=int,
        help="minimum strong strong prime bit size (e.g. 2048).")

    args = parser.parse_args()

    # Check arguments

    output_file = args.output_file
    if os.path.exists(output_file):
        utils.exit_error("The output file '%s' already exists. Exiting." %
                         (output_file))

    # Declare a few important variables

    min_prime_bitsize = args.min_prime_bitsize

    input_file = args.input_file
    with open(input_file, "r") as f:
        data = json.load(f)
    seed = int(data["seed"])
    seed_upper_bound = int(data["seed_upper_bound"])
    approx_seed_entropy = math.floor(gmpy2.log2(seed_upper_bound))

    utils.colprint("Minimum strong strong prime size:", str(min_prime_bitsize))
    utils.colprint("Approximate seed entropy:", str(approx_seed_entropy))

    # Precomputations

    first_primes = [2]  # List of the first primes
    PI = 2  # Product of the primes in "first_primes"
    strong_strong_integers = [
        [1]
    ]  # strong_strong_integers[i] is the list of all strong strong integers modulo
    # first_primes[i]
    number_of_strong_strong_integers = [
        1
    ]  # number_of_strong_strong_integers[i] is the number of elements of the list
    # strong_strong_integers[i]
    C = 1  # Product of the elements of "number_of_strong_strong_integers"

    while not 2**(min_prime_bitsize - 2) < PI:
        p = int(gmpy2.next_prime(first_primes[-1]))
        first_primes.append(p)
        PI *= p
        ssi = [c for c in range(p) if is_strong_strong_basis(c, p)]
        strong_strong_integers.append(ssi)
        number_of_strong_strong_integers.append(len(ssi))
        C *= len(ssi)

    utils.colprint("Number of primes considered:", str(len(first_primes)))
    utils.colprint("Number of strong strong integers to choose from:",
                   "about 2^%f" % (gmpy2.log2(C)))

    # Check that the seed is long enough

    if seed_upper_bound < C**2 * (1 << (2 * min_prime_bitsize)):
        utils.exit_error("The seed does not contain the required entropy.")

    # Precomputations for the CRT

    mu = [gmpy2.divexact(PI, p) for p in first_primes]
    delta = [gmpy2.invert(x, y) for x, y in zip(mu, first_primes)]
    gamma = [gmpy2.mul(x, y) for x, y in zip(mu, delta)]

    # Generate the first strong prime

    print("Generating the first strong strong prime...")
    (p, seed) = generate_strong_strong_prime(seed, min_prime_bitsize,
                                             strong_strong_integers,
                                             number_of_strong_strong_integers,
                                             gamma, PI)
    utils.colprint("\tThis is the first strong strong prime:", str(p))

    # Generate the second strong prime

    print("Generating the second strong strong prime...")
    (q, seed) = generate_strong_strong_prime(seed, min_prime_bitsize,
                                             strong_strong_integers,
                                             number_of_strong_strong_integers,
                                             gamma, PI)
    utils.colprint("\tThis is the second strong strong prime:", str(q))

    # Generate the BBS start

    print("Generating the BBS starting point...")
    n = p * q
    s = seed % n
    while s == 0 or s == 1 or s == p or s == q:
        s = (s + 1) % n
    s0 = (s**2) % n
    utils.colprint("\tThis is the starting point s0 of BBS:", str(s0))

    # Save p,q, and s to the output_file

    print("Saving p,q, and s0 to %s" % (output_file))
    with open(output_file, "w") as f:
        json.dump({
            "bbs_p": int(p),
            "bbs_q": int(q),
            "bbs_s": int(s0)
        },
                  f,
                  sort_keys=True)
def main():

    # Test local versions of libraries

    utils.test_python_version()
    utils.test_gmpy2_version()

    # Parse command line arguments
    
    parser = argparse.ArgumentParser(description="Generate BBS parameters.")
    
    parser.add_argument("input_file", help="""JSON file containing the seed used for generating the pseudo strong 
                                              strong prime (the name is "seed"). The required
                                              quantity of entropy it should contain depends on bitsize. As a rule of
                                              thumb the seed should contain at least 4*bitsize bits of entropy.""")
    parser.add_argument("output_file", help="""Output JSON file where this script will write the two generated strong
                                               strong primes "p" and "q". The output file should not exist already.""")
    parser.add_argument("min_prime_bitsize", type=int, help="minimum strong strong prime bit size (e.g. 2048).")
    
    args = parser.parse_args()

    
    # Check arguments
    
    output_file = args.output_file
    if os.path.exists(output_file):
        utils.exit_error("The output file '%s' already exists. Exiting."%(output_file))


    # Declare a few important variables
        
    min_prime_bitsize = args.min_prime_bitsize

    input_file = args.input_file
    with open(input_file, "r") as f:
        data = json.load(f)        
    seed = int(data["seed"])
    seed_upper_bound = int(data["seed_upper_bound"])
    approx_seed_entropy = math.floor(gmpy2.log2(seed_upper_bound))

    utils.colprint("Minimum strong strong prime size:", str(min_prime_bitsize))
    utils.colprint("Approximate seed entropy:", str(approx_seed_entropy))

    
    # Precomputations

    first_primes = [2]                     # List of the first primes
    PI = 2                                 # Product of the primes in "first_primes"
    strong_strong_integers = [[1]]         # strong_strong_integers[i] is the list of all strong strong integers modulo
                                           # first_primes[i]
    number_of_strong_strong_integers = [1] # number_of_strong_strong_integers[i] is the number of elements of the list
                                           # strong_strong_integers[i]
    C = 1                                  # Product of the elements of "number_of_strong_strong_integers"
    
    while not 2**(min_prime_bitsize-2) < PI:
        p = int(gmpy2.next_prime(first_primes[-1]))
        first_primes.append(p)
        PI *= p
        ssi = [c for c in range(p) if is_strong_strong_basis(c, p)]
        strong_strong_integers.append(ssi)
        number_of_strong_strong_integers.append(len(ssi))
        C *= len(ssi)

    utils.colprint("Number of primes considered:", str(len(first_primes)))
    utils.colprint("Number of strong strong integers to choose from:", "about 2^%f"%(gmpy2.log2(C)))

    
    # Check that the seed is long enough

    if seed_upper_bound < C**2 * (1 << (2 * min_prime_bitsize)):
        utils.exit_error("The seed does not contain the required entropy.")

        
    # Precomputations for the CRT

    mu    = [gmpy2.divexact(PI,p) for p in first_primes]
    delta = [gmpy2.invert(x,y) for x,y in zip(mu,first_primes)]
    gamma = [gmpy2.mul(x,y) for x,y in zip(mu,delta)]


    # Generate the first strong prime
    
    print("Generating the first strong strong prime...")
    (p,seed) = generate_strong_strong_prime(seed,
                                            min_prime_bitsize,
                                            strong_strong_integers,
                                            number_of_strong_strong_integers,
                                            gamma,
                                            PI)
    utils.colprint("\tThis is the first strong strong prime:", str(p))

    
    # Generate the second strong prime
    
    print("Generating the second strong strong prime...")
    (q,seed) = generate_strong_strong_prime(seed,
                                            min_prime_bitsize,
                                            strong_strong_integers,
                                            number_of_strong_strong_integers,
                                            gamma,
                                            PI)
    utils.colprint("\tThis is the second strong strong prime:", str(q))

    
    # Generate the BBS start

    print("Generating the BBS starting point...")    
    n = p*q
    s = seed % n
    while s == 0 or s == 1 or s == p or s == q:
        s = (s+1) % n
    s0 = (s**2) % n
    utils.colprint("\tThis is the starting point s0 of BBS:", str(s0))

    
    # Save p,q, and s to the output_file

    print("Saving p,q, and s0 to %s"%(output_file))
    with open(output_file, "w") as f:
        json.dump({"bbs_p": int(p), 
                   "bbs_q": int(q), 
                   "bbs_s": int(s0)}, 
                  f,
                  sort_keys=True)
Beispiel #11
0
n1 = 432392930987450813283722533691710471639791473905431411294422812680756059949490692752875940898283336354461864884367734026785241346129070442248412780693537140560773322402969517700925527579740683508840314300447096080073192208933558154937691810086107491733836827299512462259912221275201109718958299074633000499623440421040143963104420051385605854252248867123433634295390585186828253120863809228241733292139298105094701347702544088317801642266242067133482727786530822718765087789363482995507281709424162756711939795927271454560739347412817394971294525699507322243012757524776508763041144277237805450059749429275583978526920254876287602685393371308963777741407781687881759517910815475529722022156196422492207441469630389516583012482349342676487037424824491336214500358408341603133648118963532274769154562712459317724710468787266997127544995452621261999638308703482143237827695610582427901997818556478678622692719873547639783786326267655086073215766478090203819268036774156269115051885820643961995346825139596078343240305269625072013892835377846140920835534830699221086011664740822794506801515773509685918509255970874660577412413013082901402223037135209213424501835949006236665465839172104928609091664832148404799835006667798625083702202233
n2 = 587352203597414738591602713648322506709565023811865128539829977150224842443109789355241067780017557104203309185211099135760720695098526516430906191145034700195064161116661384068714724405712616476833138349553353734476857313002892535857021132384816143833829866569863544074617198598282028775798047967026029343917720715255092190528673897767786453437854894610296870427263732300925481202747236911016359813167755521534063290783769619808097218066693838752922206907922674956938342136820654120249471093055362841354147216981044807020436226076763925791202952569937084670667847784401517249827854202767823304216269817447354378269105404140948569082723117786248795393077859592887105486252114651174710576137604711606470660779841115268338281243239981393025380799851069654268516883518918597754310300053889061850266635223448855158538878839417198847586851106236199204072636513222521518089791514487352894811239525040518309171371155737270659319157101985569038982203950699018204316900116409532944173129092666933080754152634367412154805344844650121402577506547775707418297375596096498761267790555591843196092275779436130993153083074335542175482544324719067295252900579350697746523113159284088954469553795143934184248871730394281841625405936476833478684660181
n3 = 253966940835424110371060934444877624479916684708798201066188695233344349658054455953310223468546217796100695697931776242638869923048439359017623186526474782867338459263498253894522156946712877312310784382916007656025170459852692814578570957396256618824238440005703177519684618193701564950636936578841798939325772718756674176234987466402497837152072953633430876253858464509875749285845605449118532758629626201703196843330034246655914307672394001399614749044648825030177219478148650516436631938238511364477497365150865792302483787675901527767328295365965920054900565794136202347779920351827502929543603141235195334612780481680242180896195453515002702724802848207569700570221971365301454942213417215146736183562533267171349711241863062266258176279809656026231955226364711510691175143961821961538996349805318412205295819319820491530447387214896368780283586802952216236930589182914655321771763585708140369159536084376528398484195831953437176062578639887047945357635059754739907561665205203281144212342426974849555557179398189601043212541232215802310269023864792307707421294737959517088991710020002288313084327010723688324739322015568710153316881501545927957631699484417864491625131009890130841647565846849747590501229509874563111792909186529299459498603767514124650454823290451105677800120537941346486558376642860815481803588774038808664372144839016416321886654468598462737403431337976447939405360691389869468755793006036447453013095749767052012048757729582274392578791289856240675643306612232207304045160677435091951341939961624595613632981654956099078098012141779955916210630792851114511358314111107705581439477416066001852682599750333993536646651542369777516191909394426662740795081556067697605461397031682916836365748327360301315644451857264781645126013044438517874696729838735370775019619467284546083451110591844170567129083381610546323583279971866683988314790970561772059299398282152905686450814954253636840711226443746268939223715380642705606578926428605889585075837835227973738667854844699633094087335324374704037117933576183449223872696690444525398999104906905626930008419442296775907723357533708516202675947929180938276011173829421533614467941392579125540796746745022921082245660937608000104680753586023491241913641568804988306091316699862320344921277599214913874270523741369508751270726206273560239470231209244308298415829253422757314384515566661465572350284548940660177853719277052716232230083362429181983803204614875578166843318523381630816379446304944384173

e = 65537

diff_xy = int(
    b64decode(
        "MTgwOTE5Njk0MzYwNDUzNTM4NzA0MzQzMDI2MzUwNTA5MjY1ODYyNjg2NTUyODgxMjYwOTY1MjY5MTU0NzYwNjAyMjI3MzM2Nzg0MDEwMzk0NDE2MDg2OTc2NDU4MTM0MTQxMjUzMDk3NDg2MzI3NTY4NzMyNzkyNDg3Nzk5NTMwMzQ4OTIzMDg0NDIzNTE0OTc4MzM3NTExODk1NTQ0MjMyOTA2Nzc0ODY1Njc2ODMzODQ5MjczMjk2OTQwNzE3Nzk2NzA4Mzg4NTM3MDc5ODA4NTU0ODM1NjQzNDk2MDE1Nzc3NDA4MTMyMDg4NzE0NTQwNDkyNTAzOTk0NjMxODc0ODA2MjQ5MTM2MjM0OTAyNDU5MjM0ODY1NTQwNzU0MDkwMjM0NDM0MTc0NDExMzM1NTQ="
    ).decode())

sum_xy = gmpy2.iroot(diff_xy**2 + 4 * n, 2)
assert sum_xy[1]

sum_xy = sum_xy[0]
x = gmpy2.divexact(diff_xy + sum_xy, 2)
y = x - diff_xy

tot_xy = (x - 1) * (y - 1)

d_hint = gmpy2.invert(e, tot_xy)
print(bytes.fromhex(hex(pow(ct_hint, d_hint, n))[2:]).decode("utf-8"))
# https://pastebin.com/Ss2RBhVN

diff_pq = 1242254675415543503766895259645948956714565032314250524137831358209708821235656498568430715669433767267932849541878017070288450179946709465045989670967018664210510249524337371370194547615415463025339620947231767209068732717430495760349314268551548766308784014198416595085792538559604304511204343591110575966133411683494405581283707510216996645953704755030009685705598286875623318644696137632011886800339620903367486743178531224878773137291025036671073484661382147243850459058814557865200213432899144037919525943152724499373048644942059816246177492327411881290878242343351064106920857862403657075984791138952343067648
sum_rq = 42586529994337243194594377547592760240086486028023740254425823469718813679975915502231955918323718835882222049323701867968652256315221185961367892844011306331592144711636470848175554548789329171719808343017960868421271177298276565596919161553043629866916804224794067993887169815975501872828652912660595467444117226917978816760167520113510193812597514339079391849704994946666438188636725168245833136374679832893838578803430257564660326875785366074158859721507370632997652618843009207468965641349574727141875293709085091812931425610936131487776887932443004650024160535276113074323157342494176103553301253459146310813328
sum_rp = 41344275318921699690827482287946811283371920995709489730287992111509104858740259003663525202654285068614289199781823850898363806135274476496321903173044287667381634462112133476805360001173913708694468722070729101212202444580846069836569847284492081100608020210595651398801377277415897568317448569069484891477983815234484411178883812603293197166643809584049382163999396659790814869992029030613821249574340211990471092060251726339781553738494341037487786236845988485753802159784194649603765427916675583103955767765932367313558376965994071671530710440115592768733282292932762010216236484631772446477316462320193967745680

sum_pq = gmpy2.iroot(diff_pq**2 + 4 * n1, 2)

assert sum_pq[1]