Python Crypto.Util.number.GCD Examples

The following are 12 code examples for showing how to use Crypto.Util.number.GCD(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module Crypto.Util.number , or try the search function .

Example 1
Project: earthengine   Author: mortcanty   File: test_number.py    License: MIT License 6 votes vote down vote up
def test_getStrongPrime(self):
        """Util.number.getStrongPrime"""
        self.assertRaises(ValueError, number.getStrongPrime, 256)
        self.assertRaises(ValueError, number.getStrongPrime, 513)
        bits = 512
        x = number.getStrongPrime(bits)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1L << bits-1)-1, 1)
        self.assertEqual(x < (1L << bits), 1)
        e = 2**16+1
        x = number.getStrongPrime(bits, e)
        self.assertEqual(number.GCD(x-1, e), 1)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1L << bits-1)-1, 1)
        self.assertEqual(x < (1L << bits), 1)
        e = 2**16+2
        x = number.getStrongPrime(bits, e)
        self.assertEqual(number.GCD((x-1)>>1, e), 1)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1L << bits-1)-1, 1)
        self.assertEqual(x < (1L << bits), 1) 
Example 2
Project: Safejumper-for-Desktop   Author: proxysh   File: test_number.py    License: GNU General Public License v2.0 6 votes vote down vote up
def test_getStrongPrime(self):
        """Util.number.getStrongPrime"""
        self.assertRaises(ValueError, number.getStrongPrime, 256)
        self.assertRaises(ValueError, number.getStrongPrime, 513)
        bits = 512
        x = number.getStrongPrime(bits)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1L << bits-1)-1, 1)
        self.assertEqual(x < (1L << bits), 1)
        e = 2**16+1
        x = number.getStrongPrime(bits, e)
        self.assertEqual(number.GCD(x-1, e), 1)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1L << bits-1)-1, 1)
        self.assertEqual(x < (1L << bits), 1)
        e = 2**16+2
        x = number.getStrongPrime(bits, e)
        self.assertEqual(number.GCD((x-1)>>1, e), 1)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1L << bits-1)-1, 1)
        self.assertEqual(x < (1L << bits), 1) 
Example 3
Project: FODI   Author: vcheckzen   File: test_number.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_getStrongPrime(self):
        """Util.number.getStrongPrime"""
        self.assertRaises(ValueError, number.getStrongPrime, 256)
        self.assertRaises(ValueError, number.getStrongPrime, 513)
        bits = 512
        x = number.getStrongPrime(bits)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1 << bits-1)-1, 1)
        self.assertEqual(x < (1 << bits), 1)
        e = 2**16+1
        x = number.getStrongPrime(bits, e)
        self.assertEqual(number.GCD(x-1, e), 1)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1 << bits-1)-1, 1)
        self.assertEqual(x < (1 << bits), 1)
        e = 2**16+2
        x = number.getStrongPrime(bits, e)
        self.assertEqual(number.GCD((x-1)>>1, e), 1)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1 << bits-1)-1, 1)
        self.assertEqual(x < (1 << bits), 1) 
Example 4
Project: android_universal   Author: bkerler   File: test_number.py    License: MIT License 6 votes vote down vote up
def test_getStrongPrime(self):
        """Util.number.getStrongPrime"""
        self.assertRaises(ValueError, number.getStrongPrime, 256)
        self.assertRaises(ValueError, number.getStrongPrime, 513)
        bits = 512
        x = number.getStrongPrime(bits)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1 << bits-1)-1, 1)
        self.assertEqual(x < (1 << bits), 1)
        e = 2**16+1
        x = number.getStrongPrime(bits, e)
        self.assertEqual(number.GCD(x-1, e), 1)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1 << bits-1)-1, 1)
        self.assertEqual(x < (1 << bits), 1)
        e = 2**16+2
        x = number.getStrongPrime(bits, e)
        self.assertEqual(number.GCD((x-1)>>1, e), 1)
        self.assertNotEqual(x % 2, 0)
        self.assertEqual(x > (1 << bits-1)-1, 1)
        self.assertEqual(x < (1 << bits), 1) 
Example 5
Project: CVE-2017-7494   Author: joxeankoret   File: crypto.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _nfold(str, nbytes):
    # Convert str to a string of length nbytes using the RFC 3961 nfold
    # operation.

    # Rotate the bytes in str to the right by nbits bits.
    def rotate_right(str, nbits):
        nbytes, remain = (nbits//8) % len(str), nbits % 8
        return ''.join(chr((ord(str[i-nbytes]) >> remain) |
                           ((ord(str[i-nbytes-1]) << (8-remain)) & 0xff))
                       for i in xrange(len(str)))

    # Add equal-length strings together with end-around carry.
    def add_ones_complement(str1, str2):
        n = len(str1)
        v = [ord(a) + ord(b) for a, b in zip(str1, str2)]
        # Propagate carry bits to the left until there aren't any left.
        while any(x & ~0xff for x in v):
            v = [(v[i-n+1]>>8) + (v[i]&0xff) for i in xrange(n)]
        return ''.join(chr(x) for x in v)

    # Concatenate copies of str to produce the least common multiple
    # of len(str) and nbytes, rotating each copy of str to the right
    # by 13 bits times its list position.  Decompose the concatenation
    # into slices of length nbytes, and add them together as
    # big-endian ones' complement integers.
    slen = len(str)
    lcm = nbytes * slen / gcd(nbytes, slen)
    bigstr = ''.join((rotate_right(str, 13 * i) for i in xrange(lcm / slen)))
    slices = (bigstr[p:p+nbytes] for p in xrange(0, lcm, nbytes))
    return reduce(add_ones_complement, slices) 
Example 6
Project: featherduster   Author: nccgroup   File: modern.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def recover_rsa_modulus_from_signatures(m1, s1, m2, s2, e=0x10001):
   """
   Calculates the modulus used to produce RSA signatures from
   two known message/signature pairs and the public exponent.

   Since the most common public exponent is 65537, we default
   to that.
   
   Parameters:
   m1 - (string) The first message
   s1 - (string) The signature of the first message
      as an unencoded string
   m2 - (string) The second message
   s2 - (string) The signature of the second message
   e - (int) The exponent to use

   Returns the modulus as an integer, or False upon failure.
   """
   m1 = string_to_long(m1)
   s1 = string_to_long(s1)
   m2 = string_to_long(m2)
   s2 = string_to_long(s2)
   gcd_result = number.GCD( s1 ** e - m1, s2 ** e - m2 )

   if gcd_result < s1 or gcd_result < s2:
      # The modulus can never be smaller than our signature.
      # If this happens, we have been fed bad data.
      return False

   else:
      return int(gcd_result) 
Example 7
Project: cracke-dit   Author: eth0izzle   File: crypto.py    License: MIT License 5 votes vote down vote up
def _nfold(str, nbytes):
    # Convert str to a string of length nbytes using the RFC 3961 nfold
    # operation.

    # Rotate the bytes in str to the right by nbits bits.
    def rotate_right(str, nbits):
        nbytes, remain = (nbits//8) % len(str), nbits % 8
        return ''.join(chr((ord(str[i-nbytes]) >> remain) |
                           ((ord(str[i-nbytes-1]) << (8-remain)) & 0xff))
                       for i in xrange(len(str)))

    # Add equal-length strings together with end-around carry.
    def add_ones_complement(str1, str2):
        n = len(str1)
        v = [ord(a) + ord(b) for a, b in zip(str1, str2)]
        # Propagate carry bits to the left until there aren't any left.
        while any(x & ~0xff for x in v):
            v = [(v[i-n+1]>>8) + (v[i]&0xff) for i in xrange(n)]
        return ''.join(chr(x) for x in v)

    # Concatenate copies of str to produce the least common multiple
    # of len(str) and nbytes, rotating each copy of str to the right
    # by 13 bits times its list position.  Decompose the concatenation
    # into slices of length nbytes, and add them together as
    # big-endian ones' complement integers.
    slen = len(str)
    lcm = nbytes * slen / gcd(nbytes, slen)
    bigstr = ''.join((rotate_right(str, 13 * i) for i in xrange(lcm / slen)))
    slices = (bigstr[p:p+nbytes] for p in xrange(0, lcm, nbytes))
    return reduce(add_ones_complement, slices) 
Example 8
Project: Crypton   Author: ashutosh1206   File: hastad_unpadded.py    License: MIT License 5 votes vote down vote up
def crt(list_a, list_m):
    """
    Reference: https://crypto.stanford.edu/pbc/notes/numbertheory/crt.html
    Returns the output after computing Chinese Remainder Theorem on

    x = a_1 mod m_1
    x = a_2 mod m_2
    ...
    x = a_n mod m_n

    input parameter list_a = [a_1, a_2, ..., a_n]
    input parameter list_m = [m_1, m_2, ..., m_n]

    Returns -1 if the operation is unsuccessful due to some exceptions
    """
    try:
        assert len(list_a) == len(list_m)
    except:
        print "[+] Length of list_a should be equal to length of list_m"
        return -1
    for i in range(len(list_m)):
        for j in range(len(list_m)):
            if GCD(list_m[i], list_m[j])!= 1 and i!=j:
                print "[+] Moduli should be pairwise co-prime"
                return -1
    M = 1
    for i in list_m:
        M *= i
    list_b = [M/i for i in list_m]
    assert len(list_b) == len(list_m)
    try:
        list_b_inv = [int(gmpy2.invert(list_b[i], list_m[i])) for i in range(len(list_m))]
    except:
        print "[+] Encountered an unusual error while calculating inverse using gmpy2.invert()"
        return -1
    x = 0
    for i in range(len(list_m)):
        x += list_a[i]*list_b[i]*list_b_inv[i]
    return x % M 
Example 9
Project: X-RSA   Author: X-Vector   File: RSA_common_modulus.py    License: GNU General Public License v3.0 5 votes vote down vote up
def neg_pow(a, b, n):
        assert b < 0
        assert GCD(a, n) == 1
        res = int(gmpy2.invert(a, n))
        res = pow(res, b*(-1), n)
        return res 
Example 10
Project: PiBunny   Author: tholum   File: crypto.py    License: MIT License 5 votes vote down vote up
def _nfold(str, nbytes):
    # Convert str to a string of length nbytes using the RFC 3961 nfold
    # operation.

    # Rotate the bytes in str to the right by nbits bits.
    def rotate_right(str, nbits):
        nbytes, remain = (nbits//8) % len(str), nbits % 8
        return ''.join(chr((ord(str[i-nbytes]) >> remain) |
                           ((ord(str[i-nbytes-1]) << (8-remain)) & 0xff))
                       for i in xrange(len(str)))

    # Add equal-length strings together with end-around carry.
    def add_ones_complement(str1, str2):
        n = len(str1)
        v = [ord(a) + ord(b) for a, b in zip(str1, str2)]
        # Propagate carry bits to the left until there aren't any left.
        while any(x & ~0xff for x in v):
            v = [(v[i-n+1]>>8) + (v[i]&0xff) for i in xrange(n)]
        return ''.join(chr(x) for x in v)

    # Concatenate copies of str to produce the least common multiple
    # of len(str) and nbytes, rotating each copy of str to the right
    # by 13 bits times its list position.  Decompose the concatenation
    # into slices of length nbytes, and add them together as
    # big-endian ones' complement integers.
    slen = len(str)
    lcm = nbytes * slen / gcd(nbytes, slen)
    bigstr = ''.join((rotate_right(str, 13 * i) for i in xrange(lcm / slen)))
    slices = (bigstr[p:p+nbytes] for p in xrange(0, lcm, nbytes))
    return reduce(add_ones_complement, slices) 
Example 11
Project: earthengine   Author: mortcanty   File: _slowmath.py    License: MIT License 4 votes vote down vote up
def rsa_construct(n, e, d=None, p=None, q=None, u=None):
    """Construct an RSAKey object"""
    assert isinstance(n, long)
    assert isinstance(e, long)
    assert isinstance(d, (long, type(None)))
    assert isinstance(p, (long, type(None)))
    assert isinstance(q, (long, type(None)))
    assert isinstance(u, (long, 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 
Example 12
Project: Safejumper-for-Desktop   Author: proxysh   File: _slowmath.py    License: GNU General Public License v2.0 4 votes vote down vote up
def rsa_construct(n, e, d=None, p=None, q=None, u=None):
    """Construct an RSAKey object"""
    assert isinstance(n, long)
    assert isinstance(e, long)
    assert isinstance(d, (long, type(None)))
    assert isinstance(p, (long, type(None)))
    assert isinstance(q, (long, type(None)))
    assert isinstance(u, (long, 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