コード例 #1
0
ファイル: sollution.py プロジェクト: PKlimo/CryptoChallenge
def main():
    x = None
    test_extract_k()
    d = load_data()
    print('=== Computing private key x ===')
    for r in d:
        if len(d[r]) > 1:
            s1, h1 = d[r][0]
            s2, h2 = d[r][1]
            k = extract_k((r, s1), (r, s2), h1, h2)
            hi1 = int.from_bytes(h1, byteorder='big')
            hi2 = int.from_bytes(h2, byteorder='big')
            x1 = ((s1*k - hi1) * number.inverse(r, q)) % q
            x2 = ((s2*k - hi2) * number.inverse(r, q)) % q
            assert x1 == x2
            if x is None:
                x = x1
            else:
                assert x == x1
    print('x:', x)
    print('=== Verifying SHA hash of private key x ===')
    xh = hex(x)[2:]
    ch = SHA.new(xh.encode('ascii')).digest()
    print('SHA-1 hash of x:', hex(int.from_bytes(ch, byteorder='big'))[2:])
    assert hex(int.from_bytes(ch, byteorder='big'))[2:] == "ca8f6f7c66fa362d40760d135b763eb8527d3d52"
    print('Hash is OK')
コード例 #2
0
ファイル: _ECDSA.py プロジェクト: paulswartz/pycrypto
 def __add__(self, other):
     # XXX use implementation on T instead of on this when we support 2**m
     # curves
     if not isinstance(other, Point):
         raise NotImplementedError
     if other.x is None and other.y is None:
         return self
     if self.x is None and self.y is None:
         return other
     if self.T != other.T:
         raise NotImplementedError
     if other.x == self.x:
         if other.y == self.y and self.y != 0:
             # double
             s_num = (3 * self.x ** 2 + self.T.a) % self.T.p
             s_dem = (2 * self.y) % self.T.p
             s = s_num * number.inverse(s_dem, self.T.p)
             x = (s ** 2 - (2 * self.x)) % self.T.p
             y = (s * (self.x - x) - self.y) % self.T.p
             return Point(x, y, self.T)
         else:
             return INFINITY
     else:
         # add
         s_num = (self.y - other.y) % self.T.p
         s_dem = (self.x - other.x) % self.T.p
         s = s_num * number.inverse(s_dem, self.T.p)
         x = (s ** 2 - self.x - other.x) % self.T.p
         y = s * (self.x - x) - self.y
         return Point(x, y % self.T.p, self.T)
コード例 #3
0
ファイル: znp.py プロジェクト: VarunMohan/Apollo
def decrypt_proof(pk, sk, cipher, chall):
    n = pk.n
    msg = paillier.decrypt(pk, sk, cipher)
    rn = (cipher * pycrypto.inverse(pow(pk.g, msg, n * n), n * n)) % (n * n)
    r = pow(rn, pycrypto.inverse(n, sk.l), n * n) # generates bogus if r^n not nth power
    
    a = pycrypto.getRandomInteger(PRIME_SIZE * 2)
    an = pow(a, n, n * n)
    
    z = a * pow(r, chall, n * n)
    
    return (an, z)
コード例 #4
0
ファイル: test_RSA.py プロジェクト: shubhanus/taiga
    def setUp(self):
        global RSA, Random, bytes_to_long
        from Crypto.PublicKey import RSA
        from Crypto import Random
        from Crypto.Util.number import bytes_to_long, inverse
        self.n = bytes_to_long(a2b_hex(self.modulus))
        self.p = bytes_to_long(a2b_hex(self.prime_factor))

        # Compute q, d, and u from n, e, and p
        self.q = self.n // self.p
        self.d = inverse(self.e, (self.p-1)*(self.q-1))
        self.u = inverse(self.p, self.q)    # u = e**-1 (mod q)

        self.rsa = RSA
コード例 #5
0
ファイル: sollution.py プロジェクト: PKlimo/CryptoChallenge
def main():
    print("=== Test of my implementation of DSA signer/verifyier ===")
    test_MyDSASigner()
    print("=== Verifying signature ===")
    msg = b"""For those that envy a MC it can be hazardous to your health\nSo be friendly, a matter of life and death, just like a etch-a-sketch\n"""
    hb = SHA.new(msg).digest()
    hi = int.from_bytes(hb, byteorder="big")
    assert hi == 0xD2D0714F014A9784047EAECCF956520045C45265  # check from website
    y = number.bytes_to_long(
        b"\x08\x4a\xd4\x71\x9d\x04\x44\x95\x49\x6a\x32\x01\xc8\xff\x48\x4f\xeb\x45\xb9\x62\xe7\x30\x2e\x56\xa3\x92\xae\xe4\xab\xab\x3e\x4b\xde\xbf\x29\x55\xb4\x73\x60\x12\xf2\x1a\x08\x08\x40\x56\xb1\x9b\xcd\x7f\xee\x56\x04\x8e\x00\x4e\x44\x98\x4e\x2f\x41\x17\x88\xef\xdc\x83\x7a\x0d\x2e\x5a\xbb\x7b\x55\x50\x39\xfd\x24\x3a\xc0\x1f\x0f\xb2\xed\x1d\xec\x56\x82\x80\xce\x67\x8e\x93\x18\x68\xd2\x3e\xb0\x95\xfd\xe9\xd3\x77\x91\x91\xb8\xc0\x29\x9d\x6e\x07\xbb\xb2\x83\xe6\x63\x34\x51\xe5\x35\xc4\x55\x13\xb2\xd3\x3c\x99\xea\x17"
    )
    r = 548099063082341131477253921760299949438196259240
    s = 857042759984254168557880549501802188789837994940
    myDSA = MyDSASigner()
    print("Verification:", myDSA.verify((r, s), hb, y))
    print("=== Breaking x from k ===")
    k = find_k(r)
    x = (s * k - hi) * number.inverse(r, q)
    x = x % q
    print("x:", x)
    print("=== Verifying x by signer ===")
    sig = myDSA.sign(hb, x, k)
    assert (r, s) == sig
    print("OK")
    print("=== Verifying x by hash ===")
    xh = hex(x)[2:]
    print("encoded x:", xh)
    ch = SHA.new(xh.encode("ascii")).digest()
    print("SHA-1 hash of x:", hex(int.from_bytes(ch, byteorder="big"))[2:])
    assert hex(int.from_bytes(ch, byteorder="big"))[2:] == "954edd5e0afe5542a4adf012611a91912a3ec16"
コード例 #6
0
ファイル: RSA.py プロジェクト: GunioRobot/pycrypto-1
    def exportKey(self, format='PEM'):
        """Export the RSA key. A string is returned
        with the encoded public or the private half
        under the selected format.

        format:		'DER' (PKCS#1) or 'PEM' (RFC1421)
        """
        der = DerSequence()
        if self.has_private():
            keyType = "RSA PRIVATE"
            der[:] = [ 0, self.n, self.e, self.d, self.p, self.q,
                   self.d % (self.p-1), self.d % (self.q-1),
                   inverse(self.q, self.p) ]
        else:
            keyType = "PUBLIC"
            der.append(b('\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00'))
            bitmap = DerObject('BIT STRING')
            derPK = DerSequence()
            derPK[:] = [ self.n, self.e ]
            bitmap.payload = b('\x00') + derPK.encode()
            der.append(bitmap.encode())
        if format=='DER':
            return der.encode()
        if format=='PEM':
            pem = b("-----BEGIN %s KEY-----\n" % keyType)
            binaryKey = der.encode()
            # Each BASE64 line can take up to 64 characters (=48 bytes of data)
            chunks = [ binascii.b2a_base64(binaryKey[i:i+48]) for i in range(0, len(binaryKey), 48) ]
            pem += b('').join(chunks)
            pem += b("-----END %s KEY-----" % keyType)
            return pem
        return ValueError("Unknown key format '%s'. Cannot export the RSA key." % format)
コード例 #7
0
ファイル: RSA.py プロジェクト: GunioRobot/pycrypto-1
 def _importKeyDER(self, externKey):
     der = DerSequence()
     der.decode(externKey, True)
     if len(der)==9 and der.hasOnlyInts() and der[0]==0:
         # ASN.1 RSAPrivateKey element
         del der[6:]	# Remove d mod (p-1), d mod (q-1), and q^{-1} mod p
         der.append(inverse(der[4],der[5])) # Add p^{-1} mod q
         del der[0]	# Remove version
         return self.construct(der[:])
     if len(der)==2:
         # The DER object is a SEQUENCE with two elements:
         # a SubjectPublicKeyInfo SEQUENCE and an opaque BIT STRING.
         #
         # The first element is always the same:
         # 0x30 0x0D     SEQUENCE, 12 bytes of payload
         #   0x06 0x09   OBJECT IDENTIFIER, 9 bytes of payload
         #     0x2A 0x86 0x48 0x86 0xF7 0x0D 0x01 0x01 0x01
         #               rsaEncryption (1 2 840 113549 1 1 1) (PKCS #1)
         #   0x05 0x00   NULL
         #
         # The second encapsulates the actual ASN.1 RSAPublicKey element.
         if der[0]==b('\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00'):
             bitmap = DerObject()
             bitmap.decode(der[1], True)
             if bitmap.typeTag==b('\x03')[0] and bitmap.payload[0]==b('\x00')[0]:
                 der.decode(bitmap.payload[1:], True)
                 if len(der)==2 and der.hasOnlyInts():
                     return self.construct(der[:])
     raise ValueError("RSA key format is not supported")
コード例 #8
0
ファイル: test_RSA.py プロジェクト: shubhanus/taiga
    def test_construct_bad_key6(self):
        tup = (self.n, self.e, self.d, self.p, self.q, 10)
        self.assertRaises(ValueError, self.rsa.construct, tup)

        from Crypto.Util.number import inverse
        tup = (self.n, self.e, self.d, self.p, self.q, inverse(self.q, self.p))
        self.assertRaises(ValueError, self.rsa.construct, tup)
コード例 #9
0
ファイル: Paillier.py プロジェクト: kmcneelyshaw/pycrypto
def generate(bits, randfunc=None, progress_func=None):
    obj = Paillierobj()
    # Generate the prime factors of n
    if progress_func:
        progress_func("p,q\n")
    p = q = 1L
    assert bits % 2 == 0, "Not an even number of bits"
    while number.size(p * q) < bits:
        p = number.getPrime(bits >> 1, randfunc)
        q = number.getPrime(bits >> 1, randfunc)

    obj.p = p
    obj.q = q
    obj.n = p * q
    obj.n_sq = obj.n * obj.n

    if progress_func:
        progress_func("l\n")
    obj.l = number.LCM(obj.p - 1, obj.q - 1)

    if progress_func:
        progress_func("g\n")

    obj.g = obj._getRandomMult() * obj.n + 1  # TODO: check
    gExp = L(pow(obj.g, obj.l, obj.n_sq), obj.n)
    while not number.GCD(gExp, obj.n) == 1:
        obj.g = obj._getRandomMult() * obj.n + 1  # TODO: check
        gExp = L(pow(obj.g, obj.l, obj.n_sq), obj.n)
    obj.m = number.inverse(gExp, obj.n)

    assert bits <= 1 + obj.size(), "Generated key is too small"

    return obj
コード例 #10
0
ファイル: TD.py プロジェクト: El-gitano/TD-SECU
def DSAverif(p, q, g, pk, message, messageHash, signature):

	# Préconditions
	if p == None or p == None or pk == None or g == None or message == None or messageHash == None or signature == None:
	
		raise ValueError("L'ensemble des paramètres n'est pas renseigné")
		
	if (p-1)%q != 0:
	
		raise ValueError("Erreur dans le renseignement des nombres p et q")
	
	# Traitement
	r = signature[0]
	s = signature[1]
	
	invS = number.inverse(s, q)  # Modulo inverse de S
	 
	a = (messageHash * invS) % q
	b = (r * invS) % q
	
	comp = ((pow(g, a, p) * pow(pk, b, p)) % p) % q
	
	if comp == r:
	 
	 	return True
	 	
	else:
	 
		return False
コード例 #11
0
def generatePrivkey (self):
  #r = Randomizer()
  k = RSA.generate(2048, os.urandom)
  s = univ.Sequence()
  s.setComponentByPosition(0, univ.Integer('0'))
  s.setComponentByPosition(1, univ.Integer(k.n))
  s.setComponentByPosition(2, univ.Integer(k.e))
  s.setComponentByPosition(3, univ.Integer(k.d))
  s.setComponentByPosition(4, univ.Integer(k.p))
  s.setComponentByPosition(5, univ.Integer(k.q))
  s.setComponentByPosition(6, univ.Integer(k.d % (k.p-1)))
  s.setComponentByPosition(7, univ.Integer(k.d % (k.q-1)))
  s.setComponentByPosition(8, univ.Integer(inverse(k.q, k.p)))

  data = encoder.encode(s)
  bdata = b64encode(data)
  maxlen = 64

  privkey = "-----BEGIN RSA PRIVATE KEY-----\n"
  while len(bdata) > maxlen:
    x = bdata[:maxlen]
    privkey += x+"\n"
    bdata = bdata[maxlen:]
  privkey += bdata
  privkey += "\n-----END RSA PRIVATE KEY-----"
  return privkey
コード例 #12
0
ファイル: znp.py プロジェクト: VarunMohan/Apollo
def gen_proof(pk, u, esum, real, v):
    a = []
    z = []
    e = []
    n = pk.n
    r = None

    for i in range(len(u)):
        if i != real:
            newz = pycrypto.getRandomInteger(PRIME_SIZE*2)
            newe = pycrypto.getRandomInteger(PRIME_SIZE)
            newa = (pow(newz, n, n * n) * pycrypto.inverse(pow(u[i], newe, n * n), n * n)) % (n * n)
            z.append(newz)
            e.append(newe)
            a.append(newa)
        else:
            r = pycrypto.getRandomInteger(PRIME_SIZE*2)
            newa = pow(r, n, n * n)

            a.append(newa)
            z.append(None)
            e.append(0)

    e[real] = (esum - sum(e)) % (pow(2, PRIME_SIZE))
    z[real] = (r * pow(v, e[real], n * n)) % (n * n)

    return (u, a, e, z, esum)
コード例 #13
0
ファイル: _slowmath.py プロジェクト: Magdno1/Arianrhod
def rsa_construct(n, e, d=None, p=None, q=None, u=None):
    """Construct an RSAKey object"""
    assert isinstance(n, int)
    assert isinstance(e, int)
    assert isinstance(d, (int, type(None)))
    assert isinstance(p, (int, type(None)))
    assert isinstance(q, (int, type(None)))
    assert isinstance(u, (int, type(None)))
    obj = _RSAKey()
    obj.n = n
    obj.e = e
    if d is None:
        return obj
    obj.d = d
    if p is not None and q is not None:
        obj.p = p
        obj.q = q
    else:
        # Compute factors p and q from the private exponent d.
        # We assume that n has no more than two factors.
        # See 8.2.2(i) in Handbook of Applied Cryptography.
        ktot = d * e - 1
        # The quantity d*e-1 is a multiple of phi(n), even,
        # and can be represented as t*2^s.
        t = ktot
        while t % 2 == 0:
            t = divmod(t, 2)[0]
        # Cycle through all multiplicative inverses in Zn.
        # The algorithm is non-deterministic, but there is a 50% chance
        # any candidate a leads to successful factoring.
        # See "Digitalized Signatures and Public Key Functions as Intractable
        # as Factorization", M. Rabin, 1979
        spotted = 0
        a = 2
        while not spotted and a < 100:
            k = t
            # Cycle through all values a^{t*2^i}=a^k
            while k < ktot:
                cand = pow(a, k, n)
                # Check if a^k is a non-trivial root of unity (mod n)
                if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
                    # We have found a number such that (cand-1)(cand+1)=0 (mod n).
                    # Either of the terms divides n.
                    obj.p = GCD(cand + 1, n)
                    spotted = 1
                    break
                k = k * 2
            # This value was not any good... let's try another!
            a = a + 2
        if not spotted:
            raise ValueError("Unable to compute factors p and q from exponent d.")
        # Found !
        assert (n % obj.p) == 0
        obj.q = divmod(n, obj.p)[0]
    if u is not None:
        obj.u = u
    else:
        obj.u = inverse(obj.p, obj.q)
    return obj
コード例 #14
0
def egGen(p, a, x, m):
	while 1:
		k = random.randint(1,p-2)
		if num.GCD(k,p-1)==1: break
	r = pow(a,k,p)
	l = num.inverse(k, p-1)
	s = l*(m-x*r)%(p-1)
	return r,s
コード例 #15
0
ファイル: solve.py プロジェクト: 47um/public-writeup
def chinese_remainder(n, a):
    sum = 0
    prod = reduce(lambda a, b: a*b, n)
 
    for n_i, a_i in zip(n, a):
        p = prod / n_i
        sum += a_i * inverse(p, n_i) * p
    return sum % prod
コード例 #16
0
ファイル: helpers.py プロジェクト: nccgroup/featherduster
def derive_d_from_pqe(p,q,e):
   '''
   Given p, q, and e from factored RSA modulus, derive the private component d
   
   p - The first of the two factors of the modulus
   q - The second of the two factors of the modulus
   e - The public exponent
   '''
   return long(number.inverse(e,(p-1)*(q-1)))
コード例 #17
0
ファイル: _ECDSA.py プロジェクト: paulswartz/pycrypto
 def _sign(self, e, k):   # alias for _decrypt
     R = self.Q.T.G * k
     if R.x == 0:
         raise ValueError('invalid k value')
     s_num = (e + self.d * R.x) % self.Q.T.n
     s = (s_num * number.inverse(k, self.Q.T.n)) % self.Q.T.n
     if s == 0:
         raise ValueError('invalid k value')
     return (R.x, s)
コード例 #18
0
def sign_message(modulus, base, order, key, message):
    while 1:
        w = number.getRandomRange(3, order)
        r = pow(base, w, modulus) % order
        w = number.inverse(w, order)
        s = w * (message + r*key)
        if s != 0:
            break
    return {'r': r, 's': s, 'm': message}
コード例 #19
0
ファイル: _slowmath.py プロジェクト: Magdno1/Arianrhod
 def _verify(self, m, r, s):
     # SECURITY TODO - We _should_ be computing SHA1(m), but we don't because that's the API.
     if not (0 < r < self.q) or not (0 < s < self.q):
         return False
     w = inverse(s, self.q)
     u1 = (m * w) % self.q
     u2 = (r * w) % self.q
     v = (pow(self.g, u1, self.p) * pow(self.y, u2, self.p) % self.p) % self.q
     return v == r
コード例 #20
0
ファイル: eidtools.py プロジェクト: AlfiyaZi/eddystone
 def ScalarMult(n, q=BASE_POINT):
   """Return the point nq."""
   n = FromBinary(Curve25519.ToPrivate(n))
   # The reference implementation ignores the most significative bit.
   q = FromBinary(q) % (2**255)
   nq = Curve25519._Multiple(n, q)
   nq = (nq.x * number.inverse(nq.z, Curve25519.P)) % Curve25519.P
   ret = ToBinary(nq, 32)
   return ret
コード例 #21
0
ファイル: RSA.py プロジェクト: adoll/crypto-challenges
 def __init__(s, numBits, e):
     s.e = e
     coprime = False
     while (not coprime):
         p = number.getPrime(numBits)
         q = number.getPrime(numBits)
         et = (p-1) * (q-1)
         s.d = number.inverse(s.e, et)
         coprime = s.d != 1
     s.n = p * q
コード例 #22
0
def invmod(a, b):
    from Crypto.Util import number
    return number.inverse(a, b)
    # https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
    gcd, x, y = egcd(a, b)
    if gcd == 1:
        return (x % b)
    else:
        if debug:
            print('invmod', a, b)
コード例 #23
0
ファイル: _slowmath.py プロジェクト: Magdno1/Arianrhod
 def _sign(self, m, k):  # alias for _decrypt
     # SECURITY TODO - We _should_ be computing SHA1(m), but we don't because that's the API.
     if not self.has_private():
         raise TypeError("No private key")
     if not (1 < k < self.q):
         raise ValueError("k is not between 2 and q-1")
     inv_k = inverse(k, self.q)  # Compute k**-1 mod q
     r = pow(self.g, k, self.p) % self.q  # r = (g**k mod p) mod q
     s = (inv_k * (m + self.x * r)) % self.q
     return (r, s)
コード例 #24
0
ファイル: schnorr.py プロジェクト: ineiti/prifi
 def sign(self, secret, data):
     p1 = self.p - 1
     while True:
         k = random.randrange(1 << (p1.bit_length() - 1), p1)
         if GCD(k, p1) == 1:
             break
     r = self.multiply(self.generator(), k)
     k_inv = inverse(k, p1)
     s = ((self._hash(data, p1) - secret * r) * k_inv) % p1
     return (r, s)
コード例 #25
0
ファイル: dsa_key.py プロジェクト: manisero/SemesterIX
    def sign(self, message):
        if not self.is_private():
            raise TypeError('Could not sign message with public key')

        m = bytes_to_long(SHA.new(message).digest())
        k = randint(1, self.q - 1)
        inverse_k = inverse(k, self.q)
        r = pow(self.g, k, self.p) % self.q
        s = (inverse_k * (m + self.x * r)) % self.q

        return r, s
コード例 #26
0
def generate(bits, randfunc, progress_func=None):
    """generate(bits:int, randfunc:callable, progress_func:callable)

    Generate an ElGamal key of length 'bits', using 'randfunc' to get
    random data and 'progress_func', if present, to display
    the progress of the key generation.
    """
    obj=ElGamalobj()
    # Generate a safe prime p
    # See Algorithm 4.86 in Handbook of Applied Cryptography
    if progress_func:
        progress_func('p\n')
    while 1:
        q = bignum(getPrime(bits-1, randfunc))
        obj.p = 2*q+1
        if number.isPrime(obj.p, randfunc=randfunc):
            break
    # Generate generator g
    # See Algorithm 4.80 in Handbook of Applied Cryptography
    # Note that the order of the group is n=p-1=2q, where q is prime
    if progress_func:
        progress_func('g\n')
    while 1:
        # We must avoid g=2 because of Bleichenbacher's attack described
        # in "Generating ElGamal signatures without knowning the secret key",
        # 1996
        #
        obj.g = number.getRandomRange(3, obj.p, randfunc)
        safe = 1
        if pow(obj.g, 2, obj.p)==1:
            safe=0
        if safe and pow(obj.g, q, obj.p)==1:
            safe=0
        # Discard g if it divides p-1 because of the attack described
        # in Note 11.67 (iii) in HAC
        if safe and divmod(obj.p-1, obj.g)[1]==0:
            safe=0
        # g^{-1} must not divide p-1 because of Khadir's attack
        # described in "Conditions of the generator for forging ElGamal
        # signature", 2011
        ginv = number.inverse(obj.g, obj.p)
        if safe and divmod(obj.p-1, ginv)[1]==0:
            safe=0
        if safe:
            break
    # Generate private key x
    if progress_func:
        progress_func('x\n')
    obj.x=number.getRandomRange(2, obj.p-1, randfunc)
    # Generate public key y
    if progress_func:
        progress_func('y\n')
    obj.y = pow(obj.g, obj.x, obj.p)
    return obj
コード例 #27
0
ファイル: Dryer21Client.py プロジェクト: dannybd/dryer21
def gen_bond(protobond):
	"""
	Given the encoded version of the long which represents the protobond,
	convert it back into a long, and multiply it by nonce_inv to get the bond.
	"""
	protobond = long_decode(protobond)
	# Generate nonce's inverse, r^-1, from the stored nonce
	nonce_inv = CryptoNumber.inverse(CryptoVars.nonce, CryptoVars.n)
	# BOND = (PROTOBOND * r^-1) = (m^d * r * r^-1) = (m^d) mod n
	bond = (protobond * nonce_inv) % CryptoVars.n
	# Encode the long for storage / display to the user
	return long_encode(bond)
コード例 #28
0
ファイル: sollution.py プロジェクト: PKlimo/CryptoChallenge
 def verify(self, sig, h, pub_key=None):
     y = self.y if pub_key is None else pub_key
     r, s = sig
     if not 0 < r < q:
         return False
     if not 0 < s < q:
         return False
     w = number.inverse(s, q)
     u1 = (number.bytes_to_long(h) * w) % q
     u2 = (r * w) % q
     v = ((pow(g, u1, p) * pow(y, u2, p)) % p) % q
     return v == r
コード例 #29
0
    a = gmpy2.isqrt(n)
    b2 = gmpy2.square(a) - n

    while not gmpy2.is_square(b2):
        a += 1
        b2 = gmpy2.square(a) - n

    p = a + gmpy2.isqrt(b2)
    q = a - gmpy2.isqrt(b2)

    return int(p), int(q)


if __name__ == "__main__":
    (p, q) = fermat_factor(n)

    print("p = {}".format(p))
    print("q = {}".format(q))

    phi = (p - 1) * (q - 1)
    d = inverse(e, phi)
    m = pow(c, d, n)

    print(m)
    print(hex(m))

    hex_string = str(hex(m))[2:]
    bytes_object = bytes.fromhex(hex_string)
    ascii_string = bytes_object.decode("ASCII")

    print(ascii_string)
コード例 #30
0
ファイル: solve.py プロジェクト: TIwase/myCTF-writeup
G = 1
cnt = 0
M = 1
while(G<=1): 
    M = M + 1
    # print("M: ", M)
    if M >= B:
        break
    if M % B == 0:
        print("M=" + str(M))
    # print("a = a ^ M mod n = ", a, "^", M, " mod ", n)
    a = pow(a, M, n)    # a^M mod n
    # print("= ", a)
    G = gcd(a-1, n)     # (a^M mod p) - 1 はpで割り切れる
    # print("G = gcd( a-1, n ) = ", "gcd(" , a-1, ", ", n, ") = ", G)
if G > 1 and G < n:
    # print("factor is " + str(G) + ", M = " + str(M))
else:
    print("try new seed")

# print("p: " + str(G))
# print("q: " + str(n//G))

########## 秘密鍵生成 ##########
p = G
q = n//G
d = inverse(e, (p-1)*(q-1))
key = RSA.construct(map(int, (n, e, d)))
open("prikey", "bw").write(key.exportKey())

コード例 #31
0
ファイル: solution.py プロジェクト: KUAN-HSUN-LI/CTF
import sage.all
from sage.rings.finite_rings.integer_mod import square_root_mod_prime, Mod
from Crypto.Util.number import long_to_bytes, inverse
import gmpy2

n = 27772857409875257529415990911214211975844307184430241451899407838750503024323367895540981606586709985980003435082116995888017731426634845808624796292507989171497629109450825818587383112280639037484593490692935998202437639626747133650990603333094513531505209954273004473567193235535061942991750932725808679249964667090723480397916715320876867803719301313440005075056481203859010490836599717523664197112053206745235908610484907715210436413015546671034478367679465233737115549451849810421017181842615880836253875862101545582922437858358265964489786463923280312860843031914516061327752183283528015684588796400861331354873
e = 16
ct = 11303174761894431146735697569489134747234975144162172162401674567273034831391936916397234068346115459134602443963604063679379285919302225719050193590179240191429612072131629779948379821039610415099784351073443218911356328815458050694493726951231241096695626477586428880220528001269746547018741237131741255022371957489462380305100634600499204435763201371188769446054925748151987175656677342779043435047048130599123081581036362712208692748034620245590448762406543804069935873123161582756799517226666835316588896306926659321054276507714414876684738121421124177324568084533020088172040422767194971217814466953837590498718
d = inverse(e, n-1)
pt = pow(ct, d, n)
print(pt)
ans = []
pt = square_root_mod_prime(Mod(pt, n), n)
ans.append(pt)
ans.append(n-pt)
ans1 = []
for a in ans:
    pt = square_root_mod_prime(Mod(a, n), n)
    ans1.append(pt)
    ans1.append(n-pt)
ans2 = []
for a in ans1:
    pt = square_root_mod_prime(Mod(a, n), n)
    ans2.append(pt)
    ans2.append(n-pt)
for a in ans2:
    print(long_to_bytes(a))
コード例 #32
0
    return ct


s = socket(AF_INET, SOCK_STREAM)
s.connect(('crypto.byteband.it', 7001))

s.recv(1024)
s.send('2\n')
x = s.recv(1024)
while ']' not in x:
    x += s.recv(1024)
m, l2 = x.split('\n')[:-1]

m = int(m, 16)
d = inverse(65536, m - 1)
g = gcd(65536, m - 1)

l2 = eval(l2)
l2 = [tostr(eval(i)) for i in l2]

l = []
key = ''

for i in l2:
    key += i[:8]
    l.append(int(i[8:].encode('hex'), 16))

for i in l:
    assert i in [_ for _ in range(0, 1024, 8)]
コード例 #33
0
sys.setrecursionlimit(10**6)

g = P(g)
z = P(z)

print(g)
print(z)

CALC_1 = GETLOG(g, SS)
CALC_2 = GETLOG(z, SS)
'''
CALC_1 = 19597093303200477157781664624163126769
CALC_2 = 40483060082070127030444832815647636291
'''

p = (2**127) - 1

tt = (CALC_1 * inverse(CALC_2, p)) % p

print(power_mod(z, tt, POL) - g)

ans = GF(p)(tt).log(GF(p)(69))
ans = (int)(ans)
flag = bytes.fromhex(flag)

for i in range(100):
    cipher = AES.new(long_to_bytes(ans), AES.MODE_ECB)
    ans += (p - 1)
    print(cipher.decrypt(flag))
コード例 #34
0
ファイル: exp.py プロジェクト: soreatu/My-CTF-Challenge
# solve HNP
print("\nSolving HNP...")
cmd = "sage solver.sage"
try:
    res = subprocess.check_output(cmd.split(' '))
except:
    print("Can't find x...")
    exit(1)
x = int(res)

# check
assert (y == pow(g, x, p))
print(f"find x: {x}")

# forge signature
admin = b"admin"
Hm = int.from_bytes(sha256(admin).digest(), 'big')
k = 0xdeadbeef
k_inv = inverse(k, q)
sig_r = pow(g, k, p) % q
sig_s = (k_inv * (Hm + x * sig_r)) % q

# sign in
sig = admin + sig_r.to_bytes(20, 'big') + sig_s.to_bytes(20, 'big')
print(f"Sending signature: {sig.hex().upper()}")
r.sendlineafter(b'$ ', b"2")
r.sendlineafter(b'Please send me your signature: ', sig.hex().upper().encode())

r.interactive()
コード例 #35
0
def recover_d(n, e, p):
    q = n // p
    phi = (p - 1) * (q - 1)
    return inverse(e, phi)
コード例 #36
0
    #Generate p such (p-1) is co-prime with e
    while True:
        p = halib_getprime(n)
        if (p - 1) % e:
            break

    #Generate q such (q-1) is co-prime with e
    while True:
        q = halib_getprime(n)
        if (q - 1) % e:
            break

    #Compute N and d
    N = p * q
    d = number.inverse(e, (p - 1) * (q - 1))

    #Open files
    public_file = open(args.p, 'w')
    private_file = open(args.s, 'w')

    #Write Public Key File
    public_file.write(str(2 * n) + '\n')
    public_file.write(str(N) + '\n')
    public_file.write(str(e))

    #Write Private Key File
    private_file.write(str(2 * n) + '\n')
    private_file.write(str(N) + '\n')
    private_file.write(str(d))
コード例 #37
0
class ImportKeyTests(unittest.TestCase):
    # 512-bit RSA key generated with openssl
    rsaKeyPEM = u'''-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+TLr7UkvEtFrRhDDKMtuII
q19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQJACUSDEp8RTe32ftq8IwG8
Wojl5mAd1wFiIOrZ/Uv8b963WJOJiuQcVN29vxU5+My9GPZ7RA3hrDBEAoHUDPrI
OQIhAPIPLz4dphiD9imAkivY31Rc5AfHJiQRA7XixTcjEkojAiEAyh/pJHks/Mlr
+rdPNEpotBjfV4M4BkgGAA/ipcmaAjcCIQCHvhwwKVBLzzTscT2HeUdEeBMoiXXK
JACAr3sJQJGxIQIgarRp+m1WSKV1MciwMaTOnbU7wxFs9DP1pva76lYBzgUCIQC9
n0CnZCJ6IZYqSt0H5N7+Q+2Ro64nuwV/OSQfM6sBwQ==
-----END RSA PRIVATE KEY-----'''

    # As above, but this is actually an unencrypted PKCS#8 key
    rsaKeyPEM8 = u'''-----BEGIN PRIVATE KEY-----
MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvx4nkAqgiyNRGlwS
ga5tkzEsPv6RP5MuvtSS8S0WtGEMMoy24girX0WsvilQgzKY8xIsGfeEkt7fQPDj
wZAzhQIDAQABAkAJRIMSnxFN7fZ+2rwjAbxaiOXmYB3XAWIg6tn9S/xv3rdYk4mK
5BxU3b2/FTn4zL0Y9ntEDeGsMEQCgdQM+sg5AiEA8g8vPh2mGIP2KYCSK9jfVFzk
B8cmJBEDteLFNyMSSiMCIQDKH+kkeSz8yWv6t080Smi0GN9XgzgGSAYAD+KlyZoC
NwIhAIe+HDApUEvPNOxxPYd5R0R4EyiJdcokAICvewlAkbEhAiBqtGn6bVZIpXUx
yLAxpM6dtTvDEWz0M/Wm9rvqVgHOBQIhAL2fQKdkInohlipK3Qfk3v5D7ZGjrie7
BX85JB8zqwHB
-----END PRIVATE KEY-----'''

    # The same RSA private key as in rsaKeyPEM, but now encrypted
    rsaKeyEncryptedPEM = (

        # PEM encryption
        # With DES and passphrase 'test'
        ('test', u'''-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: DES-CBC,AF8F9A40BD2FA2FC

Ckl9ex1kaVEWhYC2QBmfaF+YPiR4NFkRXA7nj3dcnuFEzBnY5XULupqQpQI3qbfA
u8GYS7+b3toWWiHZivHbAAUBPDIZG9hKDyB9Sq2VMARGsX1yW1zhNvZLIiVJzUHs
C6NxQ1IJWOXzTew/xM2I26kPwHIvadq+/VaT8gLQdjdH0jOiVNaevjWnLgrn1mLP
BCNRMdcexozWtAFNNqSzfW58MJL2OdMi21ED184EFytIc1BlB+FZiGZduwKGuaKy
9bMbdb/1PSvsSzPsqW7KSSrTw6MgJAFJg6lzIYvR5F4poTVBxwBX3+EyEmShiaNY
IRX3TgQI0IjrVuLmvlZKbGWP18FXj7I7k9tSsNOOzllTTdq3ny5vgM3A+ynfAaxp
dysKznQ6P+IoqML1WxAID4aGRMWka+uArOJ148Rbj9s=
-----END RSA PRIVATE KEY-----'''),

        # PKCS8 encryption
        ('winter', u'''-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIBpjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIeZIsbW3O+JcCAggA
MBQGCCqGSIb3DQMHBAgSM2p0D8FilgSCAWBhFyP2tiGKVpGj3mO8qIBzinU60ApR
3unvP+N6j7LVgnV2lFGaXbJ6a1PbQXe+2D6DUyBLo8EMXrKKVLqOMGkFMHc0UaV6
R6MmrsRDrbOqdpTuVRW+NVd5J9kQQh4xnfU/QrcPPt7vpJvSf4GzG0n666Ki50OV
M/feuVlIiyGXY6UWdVDpcOV72cq02eNUs/1JWdh2uEBvA9fCL0c07RnMrdT+CbJQ
NjJ7f8ULtp7xvR9O3Al/yJ4Wv3i4VxF1f3MCXzhlUD4I0ONlr0kJWgeQ80q/cWhw
ntvgJwnCn2XR1h6LA8Wp+0ghDTsL2NhJpWd78zClGhyU4r3hqu1XDjoXa7YCXCix
jCV15+ViDJzlNCwg+W6lRg18sSLkCT7alviIE0U5tHc6UPbbHwT5QqAxAABaP+nZ
CGqJGyiwBzrKebjgSm/KRd4C91XqcsysyH2kKPfT51MLAoD4xelOURBP
-----END ENCRYPTED PRIVATE KEY-----'''),
    )

    rsaPublicKeyPEM = u'''-----BEGIN RSA PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+T
Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQ==
-----END RSA PUBLIC KEY-----'''

    # Obtained using 'ssh-keygen -i -m PKCS8 -f rsaPublicKeyPEM'
    rsaPublicKeyOpenSSH = b(
        '''ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQC/HieQCqCLI1EaXBKBrm2TMSw+/pE/ky6+1JLxLRa0YQwyjLbiCKtfRay+KVCDMpjzEiwZ94SS3t9A8OPBkDOF comment\n'''
    )

    # The private key, in PKCS#1 format encoded with DER
    rsaKeyDER = a2b_hex(
        '''3082013b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe
    913f932ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f312
    2c19f78492dedf40f0e3c190338502030100010240094483129f114dedf6
    7edabc2301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c
    54ddbdbf1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f
    2f3e1da61883f62980922bd8df545ce407c726241103b5e2c53723124a23
    022100ca1fe924792cfcc96bfab74f344a68b418df578338064806000fe2
    a5c99a023702210087be1c3029504bcf34ec713d877947447813288975ca
    240080af7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53b
    c3116cf433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07
    e4defe43ed91a3ae27bb057f39241f33ab01c1
    '''.replace(" ", ""))

    # The private key, in unencrypted PKCS#8 format encoded with DER
    rsaKeyDER8 = a2b_hex(
        '''30820155020100300d06092a864886f70d01010105000482013f3082013
    b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe913f932
    ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f3122c19f78
    492dedf40f0e3c190338502030100010240094483129f114dedf67edabc2
    301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c54ddbdb
    f1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f2f3e1da
    61883f62980922bd8df545ce407c726241103b5e2c53723124a23022100c
    a1fe924792cfcc96bfab74f344a68b418df578338064806000fe2a5c99a0
    23702210087be1c3029504bcf34ec713d877947447813288975ca240080a
    f7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53bc3116cf
    433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07e4defe4
    3ed91a3ae27bb057f39241f33ab01c1
    '''.replace(" ", ""))

    rsaPublicKeyDER = a2b_hex(
        '''305c300d06092a864886f70d0101010500034b003048024100bf1e27900a
    a08b23511a5c1281ae6d93312c3efe913f932ebed492f12d16b4610c328c
    b6e208ab5f45acbe2950833298f3122c19f78492dedf40f0e3c190338502
    03010001
    '''.replace(" ", ""))

    n = long(
        'BF 1E 27 90 0A A0 8B 23 51 1A 5C 12 81 AE 6D 93 31 2C 3E FE 91 3F 93 2E BE D4 92 F1 2D 16 B4 61 0C 32 8C B6 E2 08 AB 5F 45 AC BE 29 50 83 32 98 F3 12 2C 19 F7 84 92 DE DF 40 F0 E3 C1 90 33 85'
        .replace(" ", ""), 16)
    e = 65537L
    d = long(
        '09 44 83 12 9F 11 4D ED F6 7E DA BC 23 01 BC 5A 88 E5 E6 60 1D D7 01 62 20 EA D9 FD 4B FC 6F DE B7 58 93 89 8A E4 1C 54 DD BD BF 15 39 F8 CC BD 18 F6 7B 44 0D E1 AC 30 44 02 81 D4 0C FA C8 39'
        .replace(" ", ""), 16)
    p = long(
        '00 F2 0F 2F 3E 1D A6 18 83 F6 29 80 92 2B D8 DF 54 5C E4 07 C7 26 24 11 03 B5 E2 C5 37 23 12 4A 23'
        .replace(" ", ""), 16)
    q = long(
        '00 CA 1F E9 24 79 2C FC C9 6B FA B7 4F 34 4A 68 B4 18 DF 57 83 38 06 48 06 00 0F E2 A5 C9 9A 02 37'
        .replace(" ", ""), 16)

    # This is q^{-1} mod p). fastmath and slowmath use pInv (p^{-1}
    # mod q) instead!
    qInv = long(
        '00 BD 9F 40 A7 64 22 7A 21 96 2A 4A DD 07 E4 DE FE 43 ED 91 A3 AE 27 BB 05 7F 39 24 1F 33 AB 01 C1'
        .replace(" ", ""), 16)
    pInv = inverse(p, q)

    def testImportKey1(self):
        """Verify import of RSAPrivateKey DER SEQUENCE"""
        key = RSA.importKey(self.rsaKeyDER)
        self.failUnless(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    def testImportKey2(self):
        """Verify import of SubjectPublicKeyInfo DER SEQUENCE"""
        key = RSA.importKey(self.rsaPublicKeyDER)
        self.failIf(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)

    def testImportKey3unicode(self):
        """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode"""
        key = RSA.importKey(self.rsaKeyPEM)
        self.assertEqual(key.has_private(), True)  # assert_
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    def testImportKey3bytes(self):
        """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as byte string"""
        key = RSA.importKey(b(self.rsaKeyPEM))
        self.assertEqual(key.has_private(), True)  # assert_
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    def testImportKey4unicode(self):
        """Verify import of RSAPrivateKey DER SEQUENCE, encoded with PEM as unicode"""
        key = RSA.importKey(self.rsaPublicKeyPEM)
        self.assertEqual(key.has_private(), False)  # failIf
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)

    def testImportKey4bytes(self):
        """Verify import of SubjectPublicKeyInfo DER SEQUENCE, encoded with PEM as byte string"""
        key = RSA.importKey(b(self.rsaPublicKeyPEM))
        self.assertEqual(key.has_private(), False)  # failIf
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)

    def testImportKey5(self):
        """Verifies that the imported key is still a valid RSA pair"""
        key = RSA.importKey(self.rsaKeyPEM)
        idem = key._encrypt(key._decrypt(89L))
        self.assertEqual(idem, 89L)

    def testImportKey6(self):
        """Verifies that the imported key is still a valid RSA pair"""
        key = RSA.importKey(self.rsaKeyDER)
        idem = key._encrypt(key._decrypt(65L))
        self.assertEqual(idem, 65L)

    def testImportKey7(self):
        """Verify import of OpenSSH public key"""
        key = RSA.importKey(self.rsaPublicKeyOpenSSH)
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)

    def testImportKey8(self):
        """Verify import of encrypted PrivateKeyInfo DER SEQUENCE"""
        for t in self.rsaKeyEncryptedPEM:
            key = RSA.importKey(t[1], t[0])
            self.failUnless(key.has_private())
            self.assertEqual(key.n, self.n)
            self.assertEqual(key.e, self.e)
            self.assertEqual(key.d, self.d)
            self.assertEqual(key.p, self.p)
            self.assertEqual(key.q, self.q)

    def testImportKey9(self):
        """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE"""
        key = RSA.importKey(self.rsaKeyDER8)
        self.failUnless(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    def testImportKey10(self):
        """Verify import of unencrypted PrivateKeyInfo DER SEQUENCE, encoded with PEM"""
        key = RSA.importKey(self.rsaKeyPEM8)
        self.failUnless(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    def testImportKey11(self):
        """Verify import of RSAPublicKey DER SEQUENCE"""
        der = asn1.DerSequence([17, 3]).encode()
        key = RSA.importKey(der)
        self.assertEqual(key.n, 17)
        self.assertEqual(key.e, 3)

    def testImportKey12(self):
        """Verify import of RSAPublicKey DER SEQUENCE, encoded with PEM"""
        der = asn1.DerSequence([17, 3]).encode()
        pem = der2pem(der)
        key = RSA.importKey(pem)
        self.assertEqual(key.n, 17)
        self.assertEqual(key.e, 3)

    def test_import_key_windows_cr_lf(self):
        pem_cr_lf = "\r\n".join(self.rsaKeyPEM.splitlines())
        key = RSA.importKey(pem_cr_lf)
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
        self.assertEqual(key.d, self.d)
        self.assertEqual(key.p, self.p)
        self.assertEqual(key.q, self.q)

    ###
    def testExportKey1(self):
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        derKey = key.exportKey("DER")
        self.assertEqual(derKey, self.rsaKeyDER)

    def testExportKey2(self):
        key = RSA.construct([self.n, self.e])
        derKey = key.exportKey("DER")
        self.assertEqual(derKey, self.rsaPublicKeyDER)

    def testExportKey3(self):
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        pemKey = key.exportKey("PEM")
        self.assertEqual(pemKey, b(self.rsaKeyPEM))

    def testExportKey4(self):
        key = RSA.construct([self.n, self.e])
        pemKey = key.exportKey("PEM")
        self.assertEqual(pemKey, b(self.rsaPublicKeyPEM))

    def testExportKey5(self):
        key = RSA.construct([self.n, self.e])
        openssh_1 = key.exportKey("OpenSSH").split()
        openssh_2 = self.rsaPublicKeyOpenSSH.split()
        self.assertEqual(openssh_1[0], openssh_2[0])
        self.assertEqual(openssh_1[1], openssh_2[1])

    def testExportKey7(self):
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        derKey = key.exportKey("DER", pkcs=8)
        self.assertEqual(derKey, self.rsaKeyDER8)

    def testExportKey8(self):
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        pemKey = key.exportKey("PEM", pkcs=8)
        self.assertEqual(pemKey, b(self.rsaKeyPEM8))

    def testExportKey9(self):
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        self.assertRaises(ValueError, key.exportKey, "invalid-format")

    def testExportKey10(self):
        # Export and re-import the encrypted key. It must match.
        # PEM envelope, PKCS#1, old PEM encryption
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        outkey = key.exportKey('PEM', 'test')
        self.failUnless(tostr(outkey).find('4,ENCRYPTED') != -1)
        self.failUnless(tostr(outkey).find('BEGIN RSA PRIVATE KEY') != -1)
        inkey = RSA.importKey(outkey, 'test')
        self.assertEqual(key.n, inkey.n)
        self.assertEqual(key.e, inkey.e)
        self.assertEqual(key.d, inkey.d)

    def testExportKey11(self):
        # Export and re-import the encrypted key. It must match.
        # PEM envelope, PKCS#1, old PEM encryption
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        outkey = key.exportKey('PEM', 'test', pkcs=1)
        self.failUnless(tostr(outkey).find('4,ENCRYPTED') != -1)
        self.failUnless(tostr(outkey).find('BEGIN RSA PRIVATE KEY') != -1)
        inkey = RSA.importKey(outkey, 'test')
        self.assertEqual(key.n, inkey.n)
        self.assertEqual(key.e, inkey.e)
        self.assertEqual(key.d, inkey.d)

    def testExportKey12(self):
        # Export and re-import the encrypted key. It must match.
        # PEM envelope, PKCS#8, old PEM encryption
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        outkey = key.exportKey('PEM', 'test', pkcs=8)
        self.failUnless(tostr(outkey).find('4,ENCRYPTED') != -1)
        self.failUnless(tostr(outkey).find('BEGIN PRIVATE KEY') != -1)
        inkey = RSA.importKey(outkey, 'test')
        self.assertEqual(key.n, inkey.n)
        self.assertEqual(key.e, inkey.e)
        self.assertEqual(key.d, inkey.d)

    def testExportKey13(self):
        # Export and re-import the encrypted key. It must match.
        # PEM envelope, PKCS#8, PKCS#8 encryption
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        outkey = key.exportKey('PEM',
                               'test',
                               pkcs=8,
                               protection='PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC')
        self.failUnless(tostr(outkey).find('4,ENCRYPTED') == -1)
        self.failUnless(
            tostr(outkey).find('BEGIN ENCRYPTED PRIVATE KEY') != -1)
        inkey = RSA.importKey(outkey, 'test')
        self.assertEqual(key.n, inkey.n)
        self.assertEqual(key.e, inkey.e)
        self.assertEqual(key.d, inkey.d)

    def testExportKey14(self):
        # Export and re-import the encrypted key. It must match.
        # DER envelope, PKCS#8, PKCS#8 encryption
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        outkey = key.exportKey('DER', 'test', pkcs=8)
        inkey = RSA.importKey(outkey, 'test')
        self.assertEqual(key.n, inkey.n)
        self.assertEqual(key.e, inkey.e)
        self.assertEqual(key.d, inkey.d)

    def testExportKey15(self):
        # Verify that that error an condition is detected when trying to
        # use a password with DER encoding and PKCS#1.
        key = RSA.construct(
            [self.n, self.e, self.d, self.p, self.q, self.pInv])
        self.assertRaises(ValueError, key.exportKey, 'DER', 'test', 1)

    def test_import_key(self):
        """Verify that import_key is an alias to importKey"""
        key = RSA.import_key(self.rsaPublicKeyDER)
        self.failIf(key.has_private())
        self.assertEqual(key.n, self.n)
        self.assertEqual(key.e, self.e)
コード例 #38
0
#!/usr/bin/env python3
from math import gcd
from Crypto.PublicKey import RSA
from Crypto.Util.number import inverse, bytes_to_long, long_to_bytes

with open('pub1.pub') as data:
    n1 = RSA.importKey(data.read()).n

with open('pub2.pub') as data:
    n2 = RSA.importKey(data.read()).n

g = gcd(n1, n2)

N = n1
p = g
q = N // p

r = (p - 1) * (q - 1)
e = 65537
d = inverse(e, r)

with open('cipher', 'rb') as data:
    c = bytes_to_long(data.read())

plain = pow(c, d, N)

print(long_to_bytes(plain))
コード例 #39
0
def main():
    logging.info("main!!")

    _ = target.recvuntil(gomi)

    ### N
    target.sendline("4")
    _ = target.recvuntil("input the data:")
    target.sendline("a")
    aN = s2n("a")**e - int(target.recvline(), 16)
    target.sendline("4")
    _ = target.recvuntil("input the data:")
    target.sendline("b")
    bN = s2n("b")**e - int(target.recvline(), 16)

    N = gmpy2.gcd(aN, bN)
    logging.info("modulus N = " + hex(N))

    ### q
    _ = target.recvuntil(gomi)
    target.sendline("3")
    fake_flag_CRT = target.recvline()

    _ = target.recvuntil(gomi)
    target.sendline("4")
    _ = target.recvuntil("input the data:")
    target.sendline(fake_flag_CRT)
    fake_flag_CRT_pow = int(target.recvline(), 16)

    _ = target.recvuntil(gomi)
    target.sendline("4")
    _ = target.recvuntil("input the data:")
    target.sendline("TEST")
    test = int(target.recvline(), 16)

    logging.info("fake_flag_CRT_pow = " + hex(fake_flag_CRT_pow))

    for i in range(1000):
        logging.info("[*] i = " + str(i))
        fake_flag = 'fake_flag{%s}' % (('%X' % i).rjust(32, '0'))
        logging.info(fake_flag)
        #logging.info((s2n(fake_flag) % N - fake_flag_CRT_pow) % N)
        q = gmpy2.gcd((s2n(fake_flag) - fake_flag_CRT_pow), N)
        p = N / q
        phi = (p - 1) * (q - 1)
        d = inverse(e, phi)
        if q == 0x01:
            logging.info("q = 0x01 continue")
            continue

        logging.info("q = " + hex(q))
        logging.info("p = " + hex(p))
        logging.info("d = " + hex(d))

        dec_test = n2s(decrypt(test, d, N))
        logging.info("decrypt_test = " + dec_test)
        if dec_test == "TEST":
            _ = target.recvuntil(gomi)
            target.sendline("1")
            encrypted_flag = int(target.recvline(), 16)
            decrypted_flag = n2s(decrypt(encrypted_flag, d, N))

            print(decrypted_flag)
            break
コード例 #40
0
def logic(conn, addr):
    global privKeys
    global publicKeys
    global factors
    global votesTally
    global factors
    global ctf_e
    global ctf_d
    global ctf_n
    voterE = None
    voterD = None
    voterN = None

    while True:
        output = conn.recv(4096)
        data = output.strip()
        data = data.decode()
        if data == "disconnect":
            conn.close()
            sys.exit("Received disconnect message. Shutting down.")
            conn.send("dack")

        try:
            data = json.loads(data)
            if data["choice"] == "register":
                if not (voterE is None or voterE is None or voterD is None):
                    conn.sendall(b"Voter already registered!")
                    continue
                p = getPrime(1024)
                q = getPrime(1024)
                phi = (p - 1) * (q - 1)
                n = p * q
                found = False
                while not found:
                    e = random.randint(2, phi - 1)
                    if gcd(e, phi) == 1:
                        found = True

                d = inverse(e, phi)
                factors[n] = (p, q)
                voterE = e
                voterD = d
                voterN = n
                ctfE = ctf_e
                ctfN = ctf_n
                payload = '{"voterE": "' + str(
                    voterE) + '", "voterD": "' + str(
                        voterD) + '", "voterN": "' + str(
                            voterN) + '", "ctfE": "' + str(
                                ctf_e) + '", "ctfN": "' + str(ctf_n) + '"}'
                conn.sendall(payload.encode())
                privKeys.append((voterD, voterN))
                publicKeys.append((voterE, voterN))
                print("Voter registered!")

            elif data["choice"] == "vote":
                print("Vote received")
                print(data)
                message = int(data["vote"])
                e = int(data["e"])
                N = int(data["N"])
                if (e, N) in publicKeys:
                    f1, f2 = factors[N]
                    d = inverse(e, (f1 - 1) * (f2 - 1))
                    print("ctf_e", ctf_e)
                    print("ctf_d", ctf_d)
                    print("ctf_n", ctf_n)
                    print("voterE", voterE)
                    print("voterN", voterN)

                    if (d, N) in voted.keys() and voted[(d, N)]:
                        conn.sendall(b"You have already voted!")
                        continue

                    signedBlindMessage_temp = signature(message, d, N)
                    signedBlindMessage = pow(signedBlindMessage_temp, ctf_d,
                                             ctf_n)
                    to_send = '{"signedBlindMessage": "' + str(
                        signedBlindMessage) + '"}'
                    conn.sendall(to_send.encode())
                    recv = conn.recv(4096).decode()
                    data = json.loads(recv)
                    unBlindedSignedMessage = int(
                        data["unBlindedSignedMessage"])
                    r = int(data["r"])
                    vote_val = verify(unBlindedSignedMessage, r, e, N)

                    print(vote_val)
                    if vote_val >= 1 and vote_val <= 10:
                        if vote_val in votesTally.keys():
                            votesTally[vote_val] += 1
                        else:
                            votesTally[vote_val] = 1
                        conn.sendall(b"Vote registered!")
                        voted[(d, N)] = True
                    else:
                        conn.sendall(b"Vote value not legit or corrupted")
                else:
                    conn.sendall(b"Voter not registered!")

            elif data["choice"] == "results":
                data_string = json.dumps(votesTally)
                conn.sendall(data_string.encode())

        except Exception as e:
            print(e)
            sys.exit()
コード例 #41
0
votesTally = {}
factors = {}
voted = {}

# Keys for the CTF
ctf_p = getPrime(1024)
ctf_q = getPrime(1024)
ctf_phi = (ctf_p - 1) * (ctf_q - 1)
ctf_n = ctf_p * ctf_q
ctf_found = False
while not ctf_found:
    ctf_e = random.randint(2, ctf_phi - 1)
    if gcd(ctf_e, ctf_phi) == 1:
        ctf_found = True

ctf_d = inverse(ctf_e, ctf_phi)


def signature(msg, d, n):
    coded = pow(msg, d, n)
    print("Blinded Signed Message " + str(coded))
    return coded


def verify(msg, r, e, n):
    ver = pow(msg, e, n)
    print("Message After Verification " + str(ver))
    return ver


def logic(conn, addr):
コード例 #42
0
ファイル: tp5.py プロジェクト: k-chanez/fac-L2-3
def rsa_CRT_key_prive(p, q, d):
    dp = d % (p - 1)
    dq = d % (q - 1)
    iq = inverse(q, p)
    return dp, dq, iq
コード例 #43
0
 def decrypt(self, c):
     g, p, q = self.privkey
     return self.logarithm(pow(c, p - 1, p**2)) * inverse(
         self.logarithm(pow(g, p - 1, p**2)), p) % p
コード例 #44
0
def CRT(b1, b2, p1, p2):
    N = p1 * p2
    invOne = inverse(p2, p1)
    invTwo = inverse(p1, p2)
    return -(b1 * invOne * p2 + b2 * invTwo * p1) % N
コード例 #45
0
ファイル: solve.py プロジェクト: xavierntnu/CTF-1
    if k < 0: return []
    sk, complete = gmpy2.iroot(k, 2)
    if not complete: return []
    return [int((-b + sk) // 2), int((-b - sk) // 2)]


def wiener(e, n):
    kd = convergents(cf_expansion(e, n))
    for i, (k, d) in enumerate(kd):
        if k == 0: continue
        phi = (e * d - 1) // k
        roots = solve(phi - n - 1, n)
        if len(roots) == 2:
            p, q = roots
            if p * q == n:
                return (p, q)


b = 536380958350616057242691418634880594502192106332317228051967064327642091297687630174183636288378234177476435270519631690543765125295554448698898712393467267006465045949611180821007306678935181142803069337672948471202242891010188677287454504933695082327796243976863378333980923047411230913909715527759877351702062345876337256220760223926254773346698839492268265110546383782370744599490250832085044856878026833181982756791595730336514399767134613980006467147592898197961789187070786602534602178082726728869941829230655559180178594489856595304902790182697751195581218334712892008282605180395912026326384913562290014629187579128041030500771670510157597682826798117937852656884106597180126028398398087318119586692935386069677459788971114075941533740462978961436933215446347246886948166247617422293043364968298176007659058279518552847235689217185712791081965260495815179909242072310545078116020998113413517429654328367707069941427368374644442366092232916196726067387582032505389946398237261580350780769275427857010543262176468343294217258086275244086292475394366278211528621216522312552812343261375050388129743012932727654986046774759567950981007877856194574274373776538888953502272879816420369255752871177234736347325263320696917012616273

e = 0x23f52cf5663b7c4725585b3aba7cccb1458937807da8fa5cefe5fec0b2a60ae4043bff95ed3e2b721901ca3db7a1ceff57fe26d37e9249737a65e3533ad8a2f86f5575165647981d44240d14040dca6f2450efcbb7e45ecbc1fab1f863fbdf4720b00291b423edafafae8df0aa8b76a7ee10d468102c25fe46c6064e4d874c3f9314937845663892f4343475179a55356af61b5a0e84f7a7e92e4c87168f6126289b781beb65762761bc94e1061936dc17232b603dee2e3f3d6a07dfa510f23d7b205b297ea2f874c595ee0a613fd74013befb163164fe916c5e83ee0add0039d858dd1dcbbde5c6c556eb88078d375ee6cce30047c5b453af90f9113615a0ab859d3ddf178acee80c6a16b5f5bd6d351ffcfba1ee2bae3b2596bd932fbc40b99206d2ae144b498cacca39c41e6f13d3df64e9993ede48fbad7f145a6afc7c3eca683ac025d11f7b5f1643784b487ff10357ab53549cd46a7c496effd5a8f2f28fbb9233287b5c4e0fb7b90a9ca503216faf6cba9233be8e5fc62dcaeae4b757437f6171dac83561d8dd0639515ced45ab3d56a8fd209b4ed1bdab9d863c1cfefe7daafa49095dd741085f39afa00fdf63eb7385ca1eb7c9c49f569d84c289bbecb23d0dd8e17766fa16ec317bae79e5c1277b6a3f291aa5e19dd6bcb4a66b796aeb664f14413bbbc3b6cdd827bd9b0cd284da1ad62822f5837ae555ad4f3009

n = 0x76fc639cc00be768d4c6ae1624b6ee8a94c07e3afa0da2bc34e483f235d496c08447b4285c93246cc9b4a952d219d9a47577644bc58facda642590ff37ad29a8f269d2ef07d436e8dbb9f610a4a64495eefbba07f7e5984d227476da17e8e522350a16d1aedb4135bca4d5f0343bca8c6f3fa2a3872e06113330153014bb62896e21abaed946d22dc7ac1259242b28f485fb31fc1de6c084a7f819e2881de21b1988a56f7590a47deb7bf872a2a05f6c6e314651ccfd0b1e048b5e9f693dc6b3a9c1cfd71a7ba6934767c98f4f2f241181c67e399e57c448b3a9bdcbb43d5344462c224d9c493e3f18453318a11c7cfd863fc1bae8fe95bf5c31460e213ea49f961cdee8aaa948c09023efbf602f74b7ff5ce50042f032dc6477f8bad33c490b1b9bf588a8fa580ba4ff274c76a339c065e459f5f88e273e80b0fd88f902cae331a91c6923636abe7446136e6a810aecc8c5ac10ce3c9c34f89ac2036193f17191839cade4df451b4a6f171b7ea4042ea7534bbbdffa6974cc64c8d59cdb04f76e6af011d3bb7f0c2cbfce1b13feaf54f8a0f7d32a2d11ab28e01385d6746d849140f71bffcc25fb20992d4a6bcbcf33e3b9e995a806839fa84b865200bd1c0b8f0466382c40323b834c77f822cc4583997fbe1770b1003c424a560889f8657cf2c7021aa59d71f4cc162b4bf7fe29e7a4d9dbf9f67efcc9a59025fc54ea1a9d

t = inverse(e, b)

p, q = wiener(t, n)

print("p =", p)
print("q =", q)
コード例 #46
0
16175693991682950929,
16418126406213832189,
16568399117655835211,
16618761350345493811,
16663643217910267123,
16750888032920189263,
16796967566363355967,
16842398522466619901,
17472599467110501143,
17616950931512191043,
17825248785173311981,
18268960885156297373,
18311624754015021467,
18415126952549973977]

def lcm(a,b):
    return a*b//GCD(a,b)

n = 1
lamda = 1
e = 65537
C = 3832859959626457027225709485375429656323178255126603075378663780948519393653566439532625900633433079271626752658882846798954519528892785678004898021308530304423348642816494504358742617536632005629162742485616912893249757928177819654147103963601401967984760746606313579479677305115496544265504651189209247851288266375913337224758155404252271964193376588771249685826128994580590505359435624950249807274946356672459398383788496965366601700031989073183091240557732312196619073008044278694422846488276936308964833729880247375177623028647353720525241938501891398515151145843765402243620785039625653437188509517271172952425644502621053148500664229099057389473617140142440892790010206026311228529465208203622927292280981837484316872937109663262395217006401614037278579063175500228717845448302693565927904414274956989419660185597039288048513697701561336476305496225188756278588808894723873597304279725821713301598203214138796642705887647813388102769640891356064278925539661743499697835930523006188666242622981619269625586780392541257657243483709067962183896469871277059132186393541650668579736405549322908665664807483683884964791989381083279779609467287234180135259393984011170607244611693425554675508988981095977187966503676074747171

for number in prime_factors:
    n *= number
    lamda = lcm(lamda,(number-1))
    
d = inverse(e, lamda)
m = pow(C, d, n)

print(long_to_bytes(m))
コード例 #47
0
def MODERATE(TARGET, SS):
    print(TARGET)
    cbound = TARGET.degree()
    p = (2**127) - 1
    if TARGET.is_irreducible() and TARGET.degree() <= B:
        for i in range(747):
            if IRR[i] == TARGET:
                return SS[i]
        assert (False)
    cutoff = int(sqrt(cbound * B))
    DDD = 18
    KK = 4
    HH = 32
    for U in tqdm(range(1, 1 << (DDD + 1))):
        AA = P(0)
        BB = P(0)
        for i in range(0, DDD + 1):
            if (U & (1 << i)) != 0:
                AA += (y**i)
        BBP = ((y**HH) * AA) % TARGET
        idx = 0
        for j in range(16):
            idx = rand.randint(1, 1 << (DDD - TARGET.degree()))
            BB = BBP + int_to_poly(idx) * TARGET
            idx += 1
            if BB.degree() > DDD:
                break
            if AA.gcd(BB) != P(1):
                continue
            CC = (y**HH) * AA + BB
            DD = (CC**KK) % POL
            if CC % TARGET != P(0):
                continue
            VV = CC / TARGET

            L1 = VV.factor()
            L2 = DD.factor()

            isok = True
            for polpol, ex in L1:
                if polpol.degree() > cutoff:
                    isok = False
                    break
            for polpol, ex in L2:
                if polpol.degree() > cutoff:
                    isok = False
                    break

            if isok == False:
                continue
            # log(TARGET) = log(CC) - log(VV) = 1/4 * log(DD) - log(VV)

            ret = 0
            for polpol, ex in L1:
                ret -= MODERATE(polpol, SS) * ex
            for polpol, ex in L2:
                ret += inverse(4, p) * MODERATE(polpol, SS) * ex

            ret = (ret % p + p) % p
            return ret
    assert (False)
コード例 #48
0
from Crypto.Util.number import bytes_to_long, inverse, getPrime, long_to_bytes, inverse
import json
import math

p = 320163545884759912335372936276795190799
q = 329022220307104142121947724162904472797

c = 36189757403806675821644824080265645760864433613971142663156046962681317223254
l = math.lcm(p - 1, q - 1)
n = 105340920728399121621249827556031721254229602066119262228636988097856120194803
e = 65537
d = inverse(e, l)
m = hex(pow(c, d, n))[2:]

dump = (bytes.fromhex(m)).decode("utf-8")
print(dump)
コード例 #49
0
ファイル: ElGamal.py プロジェクト: aminba90/PythonCourse
def generate(bits, randfunc, progress_func=None):
    """Randomly generate a fresh, new ElGamal key.

    The key will be safe for use for both encryption and signature
    (although it should be used for **only one** purpose).

    :Parameters:
        bits : int
            Key length, or size (in bits) of the modulus *p*.
            Recommended value is 2048.
        randfunc : callable
            Random number generation function; it should accept
            a single integer N and return a string of random data
            N bytes long.
        progress_func : callable
            Optional function that will be called with a short string
            containing the key parameter currently being generated;
            it's useful for interactive applications where a user is
            waiting for a key to be generated.

    :attention: You should always use a cryptographically secure random number generator,
        such as the one defined in the ``Crypto.Random`` module; **don't** just use the
        current time and the ``random`` module.

    :Return: An ElGamal key object (`ElGamalobj`).
    """
    obj = ElGamalobj()
    # Generate a safe prime p
    # See Algorithm 4.86 in Handbook of Applied Cryptography
    if progress_func:
        progress_func('p\n')
    while 1:
        q = bignum(getPrime(bits - 1, randfunc))
        obj.p = 2 * q + 1
        if number.isPrime(obj.p, randfunc=randfunc):
            break
    # Generate generator g
    if progress_func:
        progress_func('g\n')
    while 1:
        # Choose a square residue; it will generate a cyclic group of order q.
        obj.g = pow(number.getRandomRange(2, obj.p, randfunc), 2, obj.p)

        # We must avoid g=2 because of Bleichenbacher's attack described
        # in "Generating ElGamal signatures without knowning the secret key",
        # 1996
        if obj.g in (1, 2):
            continue

        # Discard g if it divides p-1 because of the attack described
        # in Note 11.67 (iii) in HAC
        if (obj.p - 1) % obj.g == 0:
            continue

        # g^{-1} must not divide p-1 because of Khadir's attack
        # described in "Conditions of the generator for forging ElGamal
        # signature", 2011
        ginv = number.inverse(obj.g, obj.p)
        if (obj.p - 1) % ginv == 0:
            continue

        # Found
        break

    # Generate private key x
    if progress_func:
        progress_func('x\n')
    obj.x = number.getRandomRange(2, obj.p - 1, randfunc)
    # Generate public key y
    if progress_func:
        progress_func('y\n')
    obj.y = pow(obj.g, obj.x, obj.p)
    return obj
コード例 #50
0
def decrypt(q, h, f, g, e):
    a = (f*e) % q
    m = (a*inverse(f, g)) % g
    return m
コード例 #51
0
ファイル: eidtools.py プロジェクト: zelcakok/eddystone
 def ToNumber(self):
     return (self.x *
             number.inverse(self.z, Curve25519.P)) % Curve25519.P
コード例 #52
0
from Crypto.Util.number import inverse

p = 857504083339712752489993810777  # No. Primo (n)
q = 1029224947942998075080348647219  # No. Primo (m)
e = 65537

phi = (p - 1) * (q - 1)  # coeficiente phi de euler
d = inverse(e, phi)  # clave privada utilizando el inverso multiplicativo

print(d)
コード例 #53
0
from Crypto.Util import number
from progressbar import *

p = 13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171
g = 11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568
h = 3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333

widgets = ['Progress: ', Percentage(), ' ', Bar('#'), ' ', Timer()]
tbl = {}
bar1 = ProgressBar(maxval=pow(2, 20), widgets=widgets)
bar1.start()
for x1 in range(0, pow(2, 20) + 1):
    bar1.update(x1)
    try:
        tmp = (h * number.inverse(pow(g, x1, p), p)) % p
        tbl[tmp] = x1
    except Exception:
        continue
# Using Dictionary, indexing complexity O(1). List indexing is O(n)
# I learned that dict is already using hash table, see:
# https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6
bar1.finish()
mid = pow(g, pow(2, 20), p)
bar2 = ProgressBar(maxval=pow(2, 20), widgets=widgets)
bar2.start()
for x0 in range(0, pow(2, 20) + 1):
    bar2.update(x0)
    tmp = pow(mid, x0, p)
    try:
        idx = tbl[tmp]
        res = x0
コード例 #54
0
ファイル: tp5.py プロジェクト: k-chanez/fac-L2-3
def trouve_d(e, p, q):
    phi_N = (p - 1) * (q - 1)
    d = inverse(e, phi_N)
    return d
コード例 #55
0
ファイル: apex.py プロジェクト: r3yc0n1c/CTF-Writeups
def get_mult(states, n):
    s1 = states[0]
    s2 = states[1]
    s3 = states[2]
    m = ((s3 - s2) * inverse(s2 - s1, n)) % n
    return m
コード例 #56
0
ファイル: decrypt.py プロジェクト: Hong5489/TJCTF-2019
from Crypto.Util.number import inverse
text = 29031324384546867512310480993891916222287719490566042302485
p = 564819669946735512444543556507
q = 671998030559713968361666935769

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

d = inverse(65537,phi)

print hex(pow(text,d,p*q))[2:-1].decode('hex')
コード例 #57
0
class Unit(NotEnglishUnit):

    GROUPS = ["crypto", "rsa"]
    """
    These are "tags" for a unit. Considering it is a Crypto unit, "crypto"
    is included, and the name of the unit, "rsa".
    """

    BLOCKED_GROUPS = ["crypto"]
    """
    These are tags for groups to not recurse into. Recursing into other crypto units
    would be silly.
    """

    PRIORITY = 60
    """
    Priority works with 0 being the highest priority, and 100 being the 
    lowest priority. 50 is the default priorty. This unit has a slightly
    lower priority.
    """

    RECURSE_SELF = False
    """
    Do not recurse into self
    """
    def __init__(self, *args, **kwargs):
        super(Unit, self).__init__(*args, **kwargs)

        self.c = -1
        self.e = parse_int(self.get("e"))
        self.n = parse_int(self.get("n"))
        self.q = parse_int(self.get("q"))
        self.p = parse_int(self.get("p"))
        self.d = parse_int(self.get("d"))
        self.dq = parse_int(self.get("dq"))
        self.dp = parse_int(self.get("dp"))
        self.phi = parse_int(self.get("phi"))

        if self.get("c"):
            try:
                handle = open(self.get("c"), "rb")
                is_file = True
            except OSError:
                is_file = False

            if is_file:
                ciphertext_data = handle.read()
                self.c = parse_int(ciphertext_data)
                if self.c == -1:
                    raise NotApplicable(
                        "could not determine ciphertext from file")
            else:
                self.c = parse_int(self.get("c"))

        if self.target.is_file:
            try:
                self.raw_target = self.target.stream.read().decode("utf-8")
            except UnicodeDecodeError:
                raise NotApplicable(
                    "unicode error, must not be potential ciphertext")

            for finding in find_variables(self.raw_target):
                if finding:
                    vars(self)[finding[0]] = parse_int(finding[1])

        if self.c == -1:
            raise NotApplicable("no ciphertext determined")

    def evaluate(self, case: Any) -> None:
        """
        Evaluate the target.

        :param case: A case returned by ``enumerate``. For this unit, \
        the ``enumerate`` function is not used.

        :return: None. This function should return any data.
        """
        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

        # If we have d, c, and n, just decrypt!
        if self.d != -1 and self.c != -1 and self.n != -1:
            self.m = pow(self.c, self.d, self.n)
            result = long_to_bytes(self.m).decode()

            self.manager.register_data(self, result)
            return

        # If e is not given, assume it is the standard 65537
        if self.e == -1:
            self.e = 0x10001

        # if n is NOT given but p and q are, multiply them to get n
        if self.n == -1 and self.p != -1 and self.q != -1:
            self.n = self.p * self.q

        # if we have a differential RSA problem, try that first.
        if self.dp != -1 and self.dq != -1:
            # if we have n, but not p and q, try and factor n
            if self.n == -1 and self.p != -1 and self.q != -1:
                factor_n()

            # if we have p and q and dp and dq, we can try this attack.
            if self.q != -1 and self.p != -1:

                qinv = inverse(self.q, self.p)

                m1 = pow(self.c, self.dp, self.p)
                m2 = pow(self.c, self.dq, self.q)
                h = qinv * (m1 - m2)
                self.m = m2 + h * self.q

                result = long_to_bytes(self.m).decode()

                self.manager.register_data(self, result)
                return

        # If e is large, we might have a Weiner's Little D attack!
        if self.e > 0x10001 and self.n != -1:
            self.d = weiners_little_d(self.e, self.n)

            # Attempt to decrypt!!!
            self.m = pow(self.c, self.d, self.n)
            result = long_to_bytes(self.m).decode()

            self.manager.register_data(self, result)
            return

        # If e is 3, we can use a use a cubed root attack!
        if self.e == 3 and self.n != -1:
            self.m = find_cube_root(self.c)

            result = long_to_bytes(self.m).decode()

            self.manager.register_data(self, result)
            return

        factor_n()  # set self.p, and self.q

        # Now that all the given values are found, try to calcuate phi
        if self.phi == -1:
            self.phi = (self.q - 1) * (self.p - 1)

        # If d is not supplied (which is normal) calculate it
        if self.d == -1:
            self.d = inverse(self.e, self.phi)

        # Calculate message
        self.m = pow(self.c, self.d, self.n)

        result = long_to_bytes(self.m).decode()

        self.manager.register_data(self, result)
        return
コード例 #58
0
 def _unblind(self, m, r):
     return inverse(r, self.n) * m % self.n
コード例 #59
-1
ファイル: applet.py プロジェクト: LudovicRousseau/asterix
    def __init__( self, **kw ):
        """ Constructor, kw is dict of CRT paramters and RSA key.
Required RSA priv. key params (as long)
 n, d, e - modulus and private exponent
or
 p, q, e - primes p, q, and public exponent e
If also dp, dq, qinv present, they are checked to be consistent.
Default value for e is 0x10001
"""
#        super( RSAtoken, self ).__init__( **kw )
        Token.__init__( self, **kw )
        # check RSA parameters
        for par in ( 'n', 'd', 'e', 'p', 'q', 'dp', 'dq', 'dqinv' ):
            if par in kw:
                assert isinstance( long( kw[par] ), long ), \
                    "RSA parameter %s must be long" % par
        e = long( kw.get( 'e', 0x10001L ))
        if 'n' in kw and 'd' in kw:
            self.key = RSA.construct(( n, e, d ))
        elif 'p' in kw and 'q' in kw:
            p = kw['p']
            q = kw['q']
            n = p*q
            d = number.inverse( e, (p-1)*(q-1))
            if 'd' in kw:
                assert d == kw['d'], "Inconsinstent private exponent"
            if 'dp' in kw:
                assert d % (p-1) == kw['dp'], "Inconsistent d mod (p-1)"
            if 'dq' in kw:
                assert d % (q-1) == kw['dq'], "Inconsistent d mod (q-1)"
            u = number.inverse( q, p )
            if 'qinv' in kw:
                assert u == kw['qinv'], "Inconsistent q inv"
            self.key = RSA.construct(( n, e, d, q, p, u ))
コード例 #60
-1
ファイル: solve.py プロジェクト: WildfootTW/CTF
def common_modulus_attack(c1, c2, e1, e2, n):
    _, s1, s2 = xgcd(e1, e2)
    if s1 < 0:
        s1 = -s1
        c1 = inverse(c1, n)
    if s2 < 0:
        s2 = -s2
        c2 = inverse(c2, n)
    c1s1 = pow(c1, s1, n)
    c2s2 = pow(c2, s2, n)
    m = (c1s1 * c2s2) % n
    return m