예제 #1
0
파일: fcaa.py 프로젝트: idle010/FCAA_EGARA
def init():
    for line in open("root.txt"):
        global MAXLEN
        MAXLEN = len(line.strip("\n"))
        global MAXVALUE
        MAXVALUE = gmpy2.mpz("1" * MAXLEN, 2)
        A.add(gmpy2.mpz(line.strip("\n"), 2))
예제 #2
0
def import_cmd_signature(cmd, keys_path):
    f = os.path.join(keys_path, '{0}.sig'.format(cmd))
    with open(f, 'r') as f:
        data = f.read()
        d = data.split('\n')
        (r, s) = (mpz(d[0]), mpz(d[1]))
        return (r, s)
예제 #3
0
    def test_is_methods(self):
        self.assertFalse(is_pysmt_fraction(4))
        self.assertTrue(is_pysmt_fraction(Fraction(4)))

        self.assertFalse(is_pysmt_integer(4.0))
        self.assertTrue(is_pysmt_integer(Integer(4)))

        self.assertTrue(is_python_integer(int(2)))
        if PY2:
            self.assertTrue(is_python_integer(long(2)))
        if HAS_GMPY:
            from gmpy2 import mpz
            self.assertTrue(is_python_integer(mpz(1)))

        if HAS_GMPY:
            from gmpy2 import mpz, mpq
            self.assertTrue(is_python_rational(mpz(1)))
            self.assertTrue(is_python_rational(mpq(1)))
        if PY2:
            self.assertTrue(is_python_rational(long(1)))

        self.assertTrue(is_python_rational(pyFraction(5)))
        self.assertTrue(is_python_rational(3))

        self.assertTrue(is_python_boolean(True))
        self.assertTrue(is_python_boolean(False))
예제 #4
0
 def test_pollard_rho(self):
     q = gmpy2.mpz(getPrime(512))
     p = gmpy2.mpz(getPrime(20))
     if p > q :
         p , q = q , p
     n = p * q
     self.assertEqual((p, q), number.pollard_rho(n))
예제 #5
0
def main(argv):
    lines      = files.read_lines(argv[0])
    N_1        = mpz(lines[0])
    N_2        = mpz(lines[1])
    N_3        = mpz(lines[2])

    lines      = files.read_lines(argv[1])
    C          = mpz(lines[0])
    E          = int(lines[1])

    p1, q1, i1 = number.factorize(N_1, 1)
    p2, q2, i2 = number.factorize(N_2, 1048576)
    p3, q3, i3 = number.factorize(mul(N_3, 24), 1)

    print
    print 'Factorization Demo'
    print
    print '       1st:'
    print 'Iterations: ', i1
    print '         p: ', p1
    print '         q: ', q1
    print
    print '       2nd:'
    print 'Iterations: ', i2
    print '         p: ', p2
    print '         q: ', q2
    print
    print '       3rd:'
    print 'Iterations: ', i3
    print '         p: ', div(p3, 6)
    print '         q: ', div(q3, 4)
    print
    print
    print ' Plaintext: ', encdec.rsa_decrypt(C, E, p1, q1, N_1)
    print
예제 #6
0
def main():

    global base
    global number

    try:
        base = int(retrieve_last_base())
    except ValueError:
        base = 2
        store_last_base(base)

    try:
        number = mpz(retrieve_last_attempt())
    except ValueError:
        number = mpz(2)
        store_last_attempt(number)

    print "starting with base: %d" % base
    print "starting with number: %d" % number

    i = 0
    # while i < 90000:
    while 1:
        base = attempt_number(mpz(number.digits(2), 6), 6)
        # i += 1
        number += 1

    print base
예제 #7
0
	def __init__(self,n):
		self.n = n
		self.unseen = mpz("0b"+("1"*(n-1))+"00")
		self.seen = mpz(0)
		self.prime = 0
		self.global_shift = 0
		self.totients = [i for i in range(0,n+1)]
예제 #8
0
def MultInverse(a,b):
    a = mpz(a)
    b = mpz(b)
    #only used for counting number of iterations for metrics
    count = mpz(0)
    a_O = a
    b_O = b
    t_O = mpz(0)
    t = mpz(1)
    q = f_div(a_O, b_O)
    r = sub(a_O, mul(q, b_O))
    while r > 0:
        temp = f_mod(sub(t_O,mul(q, t)), a)
        t_O = t
        t = temp
        a_O = b_O
        b_O = r
        q = f_div(a_O,b_O)
        r = sub(a_O,mul(q, b_O))
        count = add(1,count)
    #print("Number of iterations: " + str(count))
    if(b_O != 1):
        return 0
    else:
        return t
예제 #9
0
def elemop(N=1000):
    r'''
    (Takes about 40ms on a first-generation Macbook Pro)
    '''
    for i in range(N):
        assert a+b == 579
        assert a-b == -333
        assert b*a == a*b == 56088
        assert b%a == 87
        assert divmod(a, b) == (0, 123)
        assert divmod(b, a) == (3, 87)
        assert -a == -123
        assert pow(a, 10) == 792594609605189126649
        assert pow(a, 7, b) == 99
        assert cmp(a, b) == -1
        assert '7' in str(c)
        assert '0' not in str(c)
        assert a.sqrt() == 11
        assert _g.lcm(a, b) == 18696
        assert _g.fac(7) == 5040
        assert _g.fib(17) == 1597
        assert _g.divm(b, a, 20) == 12
        assert _g.divm(4, 8, 20) == 3
        assert _g.divm(4, 8, 20) == 3
        assert _g.mpz(20) == 20
        assert _g.mpz(8) == 8
        assert _g.mpz(4) == 4
        assert a.invert(100) == 87
예제 #10
0
def main23(N):
    c=gmpy2.context()
    c.precision=len(str(N))+20
    c.real_prec=len(str(N))+20
    gmpy2.set_context(c)
    assert N==gmpy2.mpz(N)
    N=gmpy2.mpz(N)
    A=find_sqrt(6*N)
    A = gmpy2.mpz(A)
    assert ( (A-1)**2<6*N<A**2 ),'not found'
    Atag = A
    for iA in xrange(-2**20,2**20):
        A = Atag + iA
        s =A**2-N
        x = gmpy2.sqrt(s)
        try:
            x = gmpy2.mpz(x)
        except:continue
        '''print x**2 > s ,  x**2 < s
        while x**2>s:
            x-=1
            print 1,
        print x**2 > s ,  x**2 < s'''
        for p in [(A-x)/2,(A-x)/3,(A+x)/2,(A+x)/3   ]:
            q = N/p
            
            if p*q==N:
                print gmpy2.is_prime(q)
                print gmpy2.is_prime(p)
                print min(p,q)
                assert False,'bla'
예제 #11
0
 def __mul__(lhs,rhs):
     if isinstance(rhs,(Number,type(mpz(0)),type(mpq(0,1)))):
         ret = DPolynomial(lhs.Nvar , lhs.Nweight , lhs.weightMat)
         if rhs==0:return ret
         for (m,c) in lhs.coeffs.items():
              ret.coeffs[m] = c*rhs
              ret.weights[m] = lhs.weights[m]
         ret._normalized = False
         return ret
     elif isinstance(lhs,(Number,type(mpz(0)),type(mpq(0,1)))):
         ret = DPolynomial(rhs.Nvar , rhs.Nweight , rhs.weightMat)
         if lhs==0:return ret
         for (m,c) in rhs.coeffs.items():
              ret.coeffs[m] = c*lhs
              ret.weights[m] = rhs.weights[m]
         ret._normalized = False
         return ret
     else:
         ret = DPolynomial(lhs.Nvar , lhs.Nweight , lhs.weightMat)
         for (m1,c1) in lhs.coeffs.items():
            if c1==0:continue
            for (m2,c2) in rhs.coeffs.items():
              if c2==0:continue
              m3 = iadd(m1,m2)
              ret.coeffs[m3] = ret.coeffs.get(m3,0) + (c1*c2)
              ret.weights[m3] = iadd(lhs.weights[m1] , rhs.weights[m2])
     return ret.normalize()
예제 #12
0
def main(N):
    c=gmpy2.context()
    c.precision=len(str(N))+20
    c.real_prec=len(str(N))+20
    gmpy2.set_context(c)
    assert N==gmpy2.mpz(N)
    N=gmpy2.mpz(N)
    A=find_sqrt(N)
    A = gmpy2.mpz(A)
    assert ( (A-1)**2<N<A**2 ),'not found'
    Atag = A
    for iA in xrange(-2**20,2**20):
        A = Atag + iA
        s =A**2-N
        x = gmpy2.sqrt(s)
        try:
            x = gmpy2.mpz(x)
        except:continue
        print x**2 > s ,  x**2 < s
        '''while x**2>s:
            x-=1
            print 1,'''
        print x**2 > s ,  x**2 < s

        p = A-x
        q = A+x
        q = N/p

        if p*q==N:
            print gmpy2.is_prime(q)
            print gmpy2.is_prime(p)
            print min(p,q)
            break
예제 #13
0
def main():
    # predefine these, we will stop overwriting them when ready to run the big numbers
    p=mpz('13407807929942597099574024998205846127'
         '47936582059239337772356144372176403007'
         '35469768018742981669034276900318581848'
         '6050853753882811946569946433649006084171'
         )
    g=mpz('117178298803662070095161175963353670885'
         '580849999989522055999794590639294997365'
         '837466705721764714603129285948296754282'
         '79466566527115212748467589894601965568'
        )
    y=mpz('323947510405045044356526437872806578864'
         '909752095244952783479245297198197614329'
         '255807385693795855318053287892800149470'
         '6097394108577585732452307673444020333'
         )

    log.info("Starting Discrete Log Calculation")
    log.info("p: %i", p)
    log.info("g: %i", g)
    log.info("y: %i", y)

    # custom range since builtin has a size limit
    log.info("Starting brute force in reverse")
    try:
        i = p
        while p > 2181019112:
            if check_dc_brute(i,g,p) == y:
                log.info("Discrete Log found, x = {}".format(i))
                return
            p -= 1
            log.info(p)    
    except KeyboardInterrupt:
        log.info("Stopped at: {}".format(i))
예제 #14
0
    def __init__(self, sInit, iRadix=10, iBlockSize=128):
        """
        Construct a new FFX character string

        :param    sInit        The value of the character string, can be int, str or FFXString
        :param    iRadix        The radix of the character string alphabet, default 10 for integers
        :param    iBlockSize    The blocksize to use with the character string in bits, default 128 bits
        :return    returns nothing
        """

        # Determine the type of the initial value
        if(isinstance(sInit, int)):
            self._sValue = mpz(sInit).digits(iRadix)
        elif(isinstance(sInit, str)):
            self._sValue = sInit
        elif(isinstance(sInit, FFXString)):
            self._sValue = sInit._sValue
        elif(isinstance(sInit, bytearray)):
            self._sValue = mpz(bytes_to_long(sInit)).digits(iRadix)
        else:
            raise UnsupportedTypeException(type(sInit))

        self._iRadix = iRadix
        self._iBlockSize = iBlockSize
        self._iLen = len(self._sValue)

        # Representations of value as integer and bytearray
        self._iValue = None
        self._bValue = None
예제 #15
0
파일: week6.py 프로젝트: jiulongw/coursera
def Q1Q4():
    N = mpz('17976931348623159077293051907890247336179769789423065727343008115\
    77326758055056206869853794492129829595855013875371640157101398586\
    47833778606925583497541085196591615128057575940752635007475935288\
    71082364994994077189561705436114947486504671101510156394068052754\
    0071584560878577663743040086340742855278549092581')

    A = isqrt(N) + 1
    x = isqrt(sub(mul(A, A), N))

    p = sub(A, x)
    q = add(A, x)

    print("Q1:")
    print(p)

    fiN = mul(sub(p, 1), sub(q, 1))
    e = mpz(65537)
    d = gmpy2.invert(e, fiN)
    ct = mpz('22096451867410381776306561134883418017410069787892831071731839143\
            67613560012053800428232965047350942434394621975151225646583996794\
            28894607645420405815647489880137348641204523252293201764879166664\
            02997509188729971690526083222067771600019329260870009579993724077\
            458967773697817571267229951148662959627934791540')
    pt = gmpy2.powmod(ct, d, N)
    ptstr = pt.digits(16)
    pos = ptstr.find('00')
    payload = ptstr[pos + 2:]
    
    print("Q4:")
    print(binascii.unhexlify(payload))
예제 #16
0
파일: test_formula.py 프로젝트: pysmt/pysmt
    def test_real(self):
        """Create Real using different constant types."""
        from fractions import Fraction as pyFraction
        from pysmt.constants import HAS_GMPY

        v1 = (1,2)
        v2 = 0.5
        v3 = pyFraction(1,2)
        v4 = Fraction(1,2)

        c1 = self.mgr.Real(v1)
        c2 = self.mgr.Real(v2)
        c3 = self.mgr.Real(v3)
        c4 = self.mgr.Real(v4)

        self.assertIs(c1, c2)
        self.assertIs(c2, c3)
        self.assertIs(c3, c4)

        if HAS_GMPY:
            from gmpy2 import mpq, mpz
            v5 = (mpz(1), mpz(2))
            v6 = mpq(1,2)

            c5 = self.mgr.Real(v5)
            c6 = self.mgr.Real(v6)
            self.assertIs(c4, c5)
            self.assertIs(c5, c6)
예제 #17
0
파일: PyPi.py 프로젝트: wxv/PiCalc
def chudnovsky(digits):
    # 20 safety digits because lots of calculations (only about 3 are needed)
    scale = 10**(mpz(digits+20))  

    gmpy2.get_context().precision = int(math.log2(10) * (digits + 20)) 
    
    k = mpz(1)
    a_k = scale
    a_sum = scale
    b_sum = mpz(0)
    C = mpz(640320)
    C_cubed_over_24 = C**3 // 24
    
    while True:
        a_k *= -(6*k-5) * (2*k-1) * (6*k-1)
        a_k //= k**3 * C_cubed_over_24
        a_sum += a_k
        b_sum += k * a_k
        k += 1
        if a_k == 0:
            break
    
    total_sum = mpfr(13591409 * a_sum + 545140134 * b_sum)
    pi = (426880 * gmpy2.sqrt(mpfr(10005))) / total_sum
 
    return pi*scale
예제 #18
0
파일: repos.py 프로젝트: xqzy/Crypto
 def calc_near6(self):
     """ Solves the Extra Credit question Q3
     See:
     Uses only integer arithmetic to avoid issues with rounding errors
     Solution credit to Francois Degros:
     https://class.coursera.org/crypto-011/forum/thread?thread_id=517#post-2279
     :return: the prime factors of ```self.n```, p and q
     :rtype: tuple
     """
     # A = ceil(sqrt(24 N))  - the use of isqrt() won't matter, as we seek the ceil
     A = add(isqrt(mul(self.n, mpz(24))), mpz(1))
     # D = A^2 - 24 N
     D = sub(mul(A, A), mul(24, self.n))
     # E = sqrt(D)  - note D is a perfect square and we can use integer arithmetic
     E = isqrt(D)
     assert sub(mul(E, E), D) == mpz(0)
     p = div(sub(A, E), 6)
     q = div(add(A, E), 4)
     if self._check_sol(p, q):
         return p, q
     # The above is the right solution, however, there is another possible solution:
     p = div(add(A, E), 6)
     q = div(sub(A, E), 4)
     if self._check_sol(p, q):
         return p, q
     print 'Could not find a solution'
     return 0, 0
예제 #19
0
    def factorization(n, delta):
        gmpy2.get_context().precision=1000000
        t = gmpy2.mpz(gmpy2.sqrt(n))
        res = gmpy2.mpfr('0.0', 1000000)
        steps = delta-t
        print "Steps: %d" % steps

        while True:

            res = gmpy2.sqrt(t**2 - n)

            if gmpy2.is_integer(res):
                break
            if res >= n/2:
                sys.stderr.write('I can\'t solve')
                exit()

            t += 1
            steps -= 1
            if steps % 1000 == 0:
                print steps

        p = t - gmpy2.mpz(res)
        q = n/p

        return {
            'p': int(q),
            'q': int(p)
        }
def create_rsa_keys(bits_length=512, e=65537):
    """
    产生有关 RSA 的一切参数, 包括 p, q, n ,phi_n, d, e
    本来想用 pycrypto 库的 RSA 来生成的, 但是这个库至少要求 1024bits, 还是自己手搓吧
    :param bits_length: p 和 q 的位长度限制
    :param e: 指定的 e
    :return: dict(), RSA 的一切参数作为字典返回
    """
    rsa = dict()
    while True:
        p = gmpy2.mpz(getPrime(bits_length))
        q = gmpy2.mpz(getPrime(bits_length))
        n = p * q
        phi_n = (p - 1) * (q - 1)

        if gmpy2.gcd(e, phi_n) == 1:
            break

    rsa["p"] = p
    rsa["q"] = q
    rsa["n"] = n
    rsa["phi"] = phi_n
    rsa["d"] = gmpy2.invert(e, rsa["phi"])
    rsa["e"] = e

    return rsa
 def do_pubkey(self, data):
     print "Generating RSA key..."
     #self.rsa = RSA.generate(4096)
     # If you find p and q which this is fast for, put them in here.
     #p, q = Crypto.Util.number.getPrime(2048), Crypto.Util.number.getPrime(2048) #379, Crypto.Util.number.getPrime(4095)
     #e = 1
     #N = p*q
     #d = Crypto.Util.number.inverse(e, (q-1)*(p-1))
     num_cop = 20
     bits = (4096 // num_cop) + 2
     #ps = [Crypto.Util.number.getPrime(bits) for i in range(x)]
     ps = [gmpy2.mpz(Crypto.Util.number.getPrime(bits)) for i in range(num_cop)]
     e  = gmpy2.mpz(Crypto.Util.number.getPrime(32))
     N = 1
     for x in ps:
         N *= x
     #next x
     #print('e', e, len(hex(e)[2:]) * 4)
     self.v = four1c2.fuckedRSA(ps, e)
     print('e=', self.v.e, len(hex(self.v.e)[2:])*4)
     
     self.rsa = RSA.construct((long(N), long(self.v.e), long(self.v.d)))
     pub = self.rsa.publickey()
     self.state = 'challange'
     self.sendLine(b64e(pub.exportKey(format='DER')))
예제 #22
0
    def bs(a, b):
        """
        Computes the terms for binary splitting the Chudnovsky infinite series

        a(a) = +/- (13591409 + 545140134*a)
        p(a) = (6*a-5)*(2*a-1)*(6*a-1)
        b(a) = 1
        q(a) = a*a*a*C3_OVER_24

        returns P(a,b), Q(a,b) and T(a,b)
        """
        if b - a == 1:
            # Directly compute P(a,a+1), Q(a,a+1) and T(a,a+1)
            if a == 0:
                Pab = Qab = mpz(1)
            else:
                Pab = mpz((6 * a - 5) * (2 * a - 1) * (6 * a - 1))
                Qab = mpz(a * a * a * C3_OVER_24)
            Tab = Pab * (13591409 + 545140134 * a)  # a(a) * p(a)
            if a & 1:
                Tab = -Tab
        else:
            # Recursively compute P(a,b), Q(a,b) and T(a,b)
            # m is the midpoint of a and b
            m = (a + b) // 2
            # Recursively calculate P(a,m), Q(a,m) and T(a,m)
            Pam, Qam, Tam = bs(a, m)
            # Recursively calculate P(m,b), Q(m,b) and T(m,b)
            Pmb, Qmb, Tmb = bs(m, b)
            # Now combine
            Pab = Pam * Pmb
            Qab = Qam * Qmb
            Tab = Qmb * Tam + Pam * Tmb
        return Pab, Qab, Tab
def q4():
    c = mpz('22096451867410381776306561134883418017410069787892831071731839143676135600120538004282329650473509424343946219751512256' +
            '46583996794288946076454204058156474898801373486412045232522932017648791666640299750918872997169052608322206777160001932' + 
            '9260870009579993724077458967773697817571267229951148662959627934791540')

    n = mpz('17976931348623159077293051907890247336179769789423065727343008115' + 
            '77326758055056206869853794492129829595855013875371640157101398586' +
            '47833778606925583497541085196591615128057575940752635007475935288' +
            '71082364994994077189561705436114947486504671101510156394068052754' +
            '0071584560878577663743040086340742855278549092581')

    e = mpz(65537)

    a = isqrt(n) + 1
    x = isqrt(a**2 - n)

    p = a - x
    q = a + x

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

    d = invert(e, fi)

    r = powmod(c, d, n)
    
    m = digits(r, 16).split('00')[1]
    
    return m.decode('hex')
예제 #24
0
def decrypt_database_0(path_, file_, file_d_):
    buf=open(path_+"pub.txt",'rb')
    pub=pickle.load(buf)
    buf.close()
    buf=open(path_+"priv.txt",'rb') 
    priv=pickle.load(buf)
    buf.close()
    in_ = open(path_+file_, 'r')
    n, m =in_.readline().split()
    n=int(n)
    m=int(m)/2
    out_ =open(path_+file_d_, 'w')
    for x in range(n): 
        for y in range(0, 2*m, 2): 
            a=decrypt(priv,pub, mpz(in_.readline()))
            b=decrypt(priv,pub, mpz(in_.readline())) 
            letter=''
            if a==0 and b==0:
                letter='A'
            elif a==0 and b==1: 
                letter='C'
            elif a==1 and b==0:
                letter='G'
            elif a==1 and b==1: 
                letter='T'
#            print letter, 
            out_.write(letter)
#        print 
        out_.write("\n")
    out_.close()
    in_.close()
    return file_d_
예제 #25
0
def verify_A3(A, N):
    '''
    serves factor_3
    '''
    c = -A**2 + A + 6*N
    b = mpz(1)
    a = mpz(1)

    if (b**2 - 4*a*c) < 0:
        return False

    x_candidates = (
        gmpy2.div((-b + gmpy2.isqrt(b**2 - 4*a*c)), 2*a),
        gmpy2.div((-b - gmpy2.isqrt(b**2 - 4*a*c)), 2*a))

    for x in x_candidates:
        if x < 0:
            continue

        # 2q < 3p
        p = gmpy2.div((A + x), 3)
        q = gmpy2.div((A - x - 1), 2)
        if p*q == N:
            return p, q

        # 3p < 2q
        p = gmpy2.div((A - x - 1), 3)
        q = gmpy2.div((A + x), 2)
        if p*q == N:
            return p, q
    return False
예제 #26
0
def decrypt_database_0(path_, file_, file_d_):
    buf = open(path_ + "pub.txt", "rb")
    pub = pickle.load(buf)
    buf.close()
    buf = open(path_ + "priv.txt", "rb")
    priv = pickle.load(buf)
    buf.close()
    in_ = open(path_ + file_, "r")
    n, m = in_.readline().split()
    n = int(n)
    m = int(m) / 2
    out_ = open(path_ + file_d_, "w")
    for x in range(n):
        for y in range(0, 2 * m, 2):
            a = decrypt(priv, pub, mpz(in_.readline()))
            b = decrypt(priv, pub, mpz(in_.readline()))
            letter = ""
            if a == 0 and b == 0:
                letter = "A"
            elif a == 0 and b == 1:
                letter = "C"
            elif a == 1 and b == 0:
                letter = "G"
            elif a == 1 and b == 1:
                letter = "T"
            #            print letter,
            out_.write(letter)
        #        print
        out_.write("\n")
    out_.close()
    in_.close()
    return file_d_
예제 #27
0
def calculateLatBitsEven():
    
    global evenMsg
    #lat = mpfr(raw_input(" Please enter required Latitude > "))
    #longitude =  mpfr(raw_input(" Please enter required longitude > "))
    lat = t_lat
    longitude = t_lon 
    
    calculateLatBitsOdd(lat,longitude)
    
    #Calculate YZ which will be what is put into our message
    modHold = mpfr(modulus(lat,Dlat0))
    modHold = (modHold/Dlat0)
    modHold = modHold * math.pow(2,17)
    modHold = modHold + 0.5
    YZ = mpfr(math.floor(modHold))
    
    #Calculate Rlatiude for airborne
    Rlat0 = mpfr(1.0)
    floorHold = 1
    Rlat0 = mpfr(YZ) / math.pow(2,17)
    floorHold = (lat/mpfr(Dlat0))
    floorHold = math.floor(floorHold)
    Rlat0 = Rlat0 + mpfr(floorHold)
    Rlat0 = Rlat0 * mpfr(Dlat0)
    NlLat = 1
    NlLat = genNlatValue(Rlat0)
    
    #Calcule DLongitude
    Dlon0 = mpfr(1.0)
    if((NlLat-1) > 0):
        Dlon0 = (360/(mpfr(NlLat)));
    else:
        Dlon0 = 360
        
    #calculate XZ the decimal representation of longitude
    XZ = mpfr(1.0)
    modHold = 0
    modHold = modulus(longitude, Dlon0)
    modHold = (modHold/Dlon0)
    modHold = modHold * math.pow(2,17)
    modHold = modHold + 0.5
    XZ = math.floor(modHold)
    #print mpfr(XZ)
    
    #Ensure this fits into our 17 bit space
    YZ1 = mpz(modulus(YZ,math.pow(2,17)))
    XZ1 = mpz(modulus(XZ,math.pow(2,17)))
    #print YZ1
    LatLon = mpz(1)
    YZ1 = YZ1 << 17
    LatLon = (YZ1 | XZ1)
    #LatLon = (LatLon | 17179869184)
    
    #to be decided
    print "even message: " + hex(LatLon)
    evenMsg = LatLon
    
    return 0
예제 #28
0
def main():
    p = mpz(13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171)
    # # not prime:
    g = mpz(11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568)
    # # not prime:
    h = mpz(3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333)
    
    discrete_log(h=h, base=g, B=2**20, m=p)
예제 #29
0
파일: field.py 프로젝트: abhisheietk/ecc
def root(a, poly):
    d = mpz(a)
    p = mpz(poly)
    out = mpz(d)
    psize = p.bit_length()
    for i in range(psize-2):
        d = mod(squar(d), p)
    return d
예제 #30
0
파일: field.py 프로젝트: abhisheietk/ecc
def squar(a):
    d = mpz(a)
    out = mpz(0)
    while d:
        dsize = d.bit_length()
        d = d.bit_clear(dsize-1)
        out = out.bit_set((dsize-1)*2)
    return out
예제 #31
0
from ecpy import ExtendedFiniteField, MapToPoint
from ecpy import EllipticCurveRepository, EllipticCurve
from ecpy import symmetric_weil_pairing
import hashlib
import _pickle as cPickle
import random
import gmpy2
import time

# Parameter taken from Cryptography and Elliptic Curves by TSUJII et al.
p = gmpy2.mpz("501794446334189957604282155189438160845433783392772743395579628"
              "617109929160215221425142482928909270259580854362463493326988807"
              "45359574857376419559953437557")

l = gmpy2.mpz((p + 1) // 6)

F = ExtendedFiniteField(p, "x^2+x+1")
E = EllipticCurve(F, 0, 1)  # y^2 = x^3 + 1

P = E(
    3,
    gmpy2.mpz("1418077311270457886139292292020587683642898636677353664354"
              "1011717684401801069777797699258667061922178009879315047772"
              "033936311133535564812495329881887557081"))

sP = E(
    gmpy2.mpz("129862491850266001914601437161941818413833907050695770313188"
              "660767152646233571458109764766382285470424230719843324368007"
              "92537535129539576510740045312772012"),
    gmpy2.mpz("452543250979361708074026409576755302296698208397782707067096"
              "515523033579018123253402743775747767548650767928190884624134"
예제 #32
0
파일: solve.py 프로젝트: unjambonakap/ctf
#!/usr/bin/env python
from gmpy2 import mpz, gcd, next_prime, invert, isqrt
import random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto.Cipher import PKCS1_OAEP
import base64
from Crypto import Random
import sys

n0 = mpz(
    17088099071005160077519535201251561512827343312119898927636879052601867044714726370386690019037410713114320026517402376841417405031151513348071692422844111539444422581984359115079190646208324178506319406900715874915900634363805971709855749306898889145210604580281672508427585998760093545394796048750722655959
)
n1 = mpz(
    17088099071005160077519535201251561512827343312119898927636879052601867044714726370386690019037410713114320026517402376841417405031151513348071692422843595984982748293316974068618115911067742584379552735602316711058821390310015568237776017595377114965964917241868369393081542210506249720365990388566061488767
)
n2 = mpz(
    17088099071005160077519535201251561512827343312119898927636879052601867044714726370386690019037410713114320026517402376841417405031151513348071692422843432549712853189869867645149366559627418953279461425319827343120906512593400627639486709587239380005123784026423814996927322189025803939737718582864288985553
)

nbits = 40
p = random.randint(1 << nbits, 1 << nbits + 1)
q = random.randint(1 << nbits, 1 << nbits + 1)

P = []
Q = []
for i in range(0, 3):
    p = next_prime(p)
    q = next_prime(q)
    P.append(p)
    Q.append(q)
예제 #33
0
 def __init__(self, value, field):
     self.p = field
     if type(value) == FieldElement:
         self.v = value.v % field
     else:
         self.v = mpz(value) % field
예제 #34
0
def bytes2mpz(b):
    return mpz(int(binascii.hexlify(b), 16))
예제 #35
0
    def seed(self, seed=None, regenerate_modulus=True, random=random):
        """Keep the same security parameters, but reinitialize the state of this instance.

        seed: (optional) a number that deterministically initializes the state
            must be an integer of length 2*security bits or security bits if
            regenerate_modulus is True, the default is to reinitialize from
            /dev/random
        regenerate_modulus: (optional) if true, pick new primes for the modulus,
            if false reuse the existing modulus (default True)
        random: (optional) a random implementation used to stretch the seed when
            regenerating the modulus. Should be a CSPRNG. Will be seeded
            and iterated by this function. If multithreaded, should not
            be used in any other thread.
            (default python's builtin random, which is unsuitable for
            cryptographic purposes, so you *MUST* override this argument)
        """
        seed_bits = 2*self.security if regenerate_modulus else self.security
        # python random.SystemRandom() is unsuitable because it uses /dev/urandom
        if seed is None:
            if self.verbose:
                print 'Seed not supplied, getting %d bytes from /dev/random' % (seed_bits / 8),
                sys.stdout.flush()
            seed = 0L
            with open('/dev/random','rb') as randfile:
                for i in xrange(int(math.ceil(seed_bits / 8.0))):
                    seed |= struct.unpack('B', randfile.read(1))[0] << i*8
                    if self.verbose:
                        print '.',
                        sys.stdout.flush()
            if self.verbose:
                print

        assert isinstance(seed, (Integral, mpz_type))
        self.state = x_0 = seed & (2**self.security - 1)

        if regenerate_modulus:
            import random as builtin_random
            if random is builtin_random or isinstance(random, builtin_random.Random):
                import warnings
                warnings.warn('Python\'s builtin random is completely unsuitable for cryptographic purposes. For any sort of reasonable security, you *MUST* use a CSPRNG as the argument to BlumBlumShubRandom.seed')
            random.seed(seed >> self.security)
            if self.verbose:
                print 'Choosing first prime...',
                sys.stdout.flush()
            p = self.gen_special_prime(int(math.floor(self._modulus_length / 2.0 + 1)),
                                       certainty=self.security, random=random)
            if self.verbose:
                print 'p=%d' % p
                print 'Choosing second prime...',
                sys.stdout.flush()
            q = self.gen_special_prime(int(math.ceil(self._modulus_length / 2.0)),
                                       certainty=self.security, random=random)
            if self.verbose:
                print 'q=%d' % q
                sys.stdout.flush()
            random.seed()

            assert p != q
            self.modulus = p*q
            self.skip_modulus = lcm(p-1, q-1) # TODO: it probably isn't safe to keep this around

        self._bit_count = 0L
        self._cache = 0L
        self._cache_len = 0L

        if has_gmpy:
            self.modulus = mpz(self.modulus)
            self.state = mpz(self.state)
            if self.skip_modulus is not None:
                self.skip_modulus = mpz(self.skip_modulus)


        # degeneracy test as described by
        # http://www.ciphersbyritter.com/NEWS6/BBS.HTM
        if self.verbose:
            print 'Running degeneracy test'
        self.jumpahead(1)
        assert self.state > 0
        x_1 = self.state
        self.jumpahead(1)
        x_2 = self.state
        assert x_0 != x_1 and x_1 != x_2 and x_2 != x_0, \
               "Given parameters resulted in a degenerate cycle. Choose another initial state."
예제 #36
0
파일: 400.py 프로젝트: kadircet/HackMETU-16
    random.shuffle(composites)
    print composites
    sys.stderr.write(str(composites[0]) + "\n")


#foundP=[]
#for i in range(999):
#	for j in range(999):
#		if i==j:
#			continue
#		p=gmpy2.gcd(composites[i], composites[j])
#		if p>1:
#			foundP.append(p)
#			foundP.append(composites[i]/p)
p = mpz(
    136879539319049556687906660518818230892898930161803757032023216914816138786640835527709801513812544955371909036683345095393654530286535681014282249961430979423188074876650524941553413026936533838281136054381984335046004532979371795539304950409648988622214685858522835884068060522877482116306511589614367098143
)
q = mpz(
    93488094760521745490867573600981167326506824062259590701758412961704736978160741035266235873896241059184566340237764070264386769534675426962527810096326138228279252769460632085480075846992461795796507574197925729088472207192317242717765702276177009823779478564206704150744597327822329038606827943300414102837
)
N = p * q
e = 65537
d = gmpy2.invert(e, N - (p + q - 1))


def encrypt(data):
    data = data.encode("hex")
    data = mpz(data, 16)
    return gmpy2.powmod(data, e, N)

예제 #37
0
파일: s.py 프로젝트: jCOTINEAU/richelieu
from math import sqrt
from itertools import count, islice
import random
import gmpy2
from gmpy2 import mpz, c_div, mul, c_divmod, c_mod

n = mpz(
    837849563862443268467145186974119695264713699736869090645354954749227901572347301978135797019317859500555501198030540582269024532041297110543579716921121054608494680063992435808708593796476251796064060074170458193997424535149535571009862661106986816844991748325991752241516736019840401840150280563780565210071876568736454876944081872530701199426927496904961840225828224638335830986649773182889291953429581550269688392460126500500241969200245489815778699333733762961281550873031692933566002822719129034336264975002130651771127313980758562909726233111335221426610990708111420561543408517386750898610535272480495075060087676747037430993946235792405851007090987857400336566798760095401096997696558611588264303087788673650321049503980655866936279251406742641888332665054505305697841899685165810087938256696223326430000379461379116517951965921710056451210314300437093481577578273495492184643002539393573651797054497188546381723478952017972346925020598375000908655964982541016719356586602781209943943317644547996232516630476025321795055805235006790200867328602560320883328523659710885314500874028671969578391146701739515500370268679301080577468316159102141953941314919039404470348112690214065442074200255579004452618002777227561755664967507
)

f = open("../myI1", "r")
c = f.read()
p = mpz(c)

e = 65537
#temp exec
#p =17
#n = 187
#e = 7

##trasnvrt

q = c_div(n, p)

#p2=p
#q2=q

#p=q2
#q=p2

print(q)
예제 #38
0
파일: field.py 프로젝트: abhisheietk/ecc
 def __init__(self, Prime=0):
     self.Prime = mpz(Prime)
예제 #39
0
파일: field.py 프로젝트: abhisheietk/ecc
 def __init__(self, Polynomial=0):
     self.Polynomial = mpz(Polynomial)
예제 #40
0
 def set_server_public_value_from_string(self, spv_str):
     self.set_server_public_value(mpz(spv_str, base=16))
예제 #41
0
 def random_number(length):
     return mpz(''.join(
         (random.choice('0123456789ABCDEF') for _ in range(length))),
                base=16)
예제 #42
0
 def validate_server_evidence_message(self, msg):
     mpz_msg = mpz(msg, base=16)
     return mpz_msg == self.get_server_evidence_message()
예제 #43
0
 def set_salt_from_string(self, salt_str):
     self.salt = mpz(salt_str, base=16)
예제 #44
0
data_file = 'train-images.idx3-ubyte'
label_file = 'train-labels.idx1-ubyte'

TOTAL_SIZE = 60000  # TOTAL_SIZE = TRAIN_SIZE + TEST_SIZE
TRAIN_SIZE = 50000
TEST_SIZE = 10000

BATCH_SIZE = 64
EPOCHS = 1
LR = 0.1

BASE = 10
PRECISION_INTEGRAL = 8
PRECISION_FRACTIONAL = 8
PRECISION = PRECISION_INTEGRAL + PRECISION_FRACTIONAL
Q = mpz(293973345475167247070445277780365744413)

np.random.seed(1)

####################################Functions#############################################

def encode(rational):
    upscaled = int(rational * BASE**PRECISION_FRACTIONAL)
    field_element = mpz(upscaled) % Q
    return field_element
encode = np.vectorize(encode)

def encode_b(rational):
    upscaled = int(rational * BASE**PRECISION_FRACTIONAL)
    field_element = mpz(upscaled) % Q
    return field_element
예제 #45
0
A_curve	= 0
B_curve	= 7
#modulo	= 2**256-2**32-2**9-2**8-2**7-2**6-2**4-1
modulo	= 115792089237316195423570985008687907853269984665640564039457584007908834671663
order	= 115792089237316195423570985008687907852837564279074904382605163141518161494337
#modulo	= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
#order	= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
Gx	= 55066263022277343669578718895168534326250603453777594175500187360389116729240
Gy	= 32670510020758816978083085130507043184471273380659243275938904335757337482424
#Gx	= 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
#Gy	= 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8


# python2+gmpy2 speed-up +8%
if flag_gmpy2:
	A_curve	= gmpy2.mpz(A_curve)
	B_curve	= gmpy2.mpz(B_curve)
	modulo	= gmpy2.mpz(modulo)
	order	= gmpy2.mpz(order)
	Gx	= gmpy2.mpz(Gx)
	Gy	= gmpy2.mpz(Gy)


class Point:
	def __init__(self, x=0, y=0):		# Affine
	#def __init__(self, x=0, y=0, z=1):	# Jacobian
		self.x = x
		self.y = y
		#self.z = 1			# Jacobian

if (not flag_gmpy2) and flag_coincurve:
예제 #46
0
def count_bits(bitboard):
    return gmpy2.popcount(gmpy2.mpz(int(bitboard)))
예제 #47
0
파일: 400.py 프로젝트: kadircet/HackMETU-16
def encrypt(data):
    data = data.encode("hex")
    data = mpz(data, 16)
    return gmpy2.powmod(data, e, N)
예제 #48
0
    def Mul(self, c1, c2):
        a = c1['a'] * c2['a']
        b = c1['b'] * c2['b']

        return {'a': a, 'b': b}


if __name__ == '__main__':
    hm = HomoEnc(1)
    S_key = hm.KeyGen()
    B_key = hm.KeyGen()
    # m = mpz(67661)
    # c = hm.Enc(S_key['pk'],m)
    # mes = hm.Dec(S_key['sk'],c)
    # print("s_key",mes,type(mes))

    m2 = mpz(-5211609863.01 * 10**6)
    c2 = hm.Enc(B_key['pk'], m2)
    mss = hm.Dec(B_key['sk'], c2)
    print("b_key: ", mss)

    # rk = hm.ReKeyGen(S_key['sk'],B_key['pk'])
    # c_sb = hm.ReEnc(rk,c)
    # msb = hm.Dec(B_key['sk'],c_sb)
    # print("b_key: ",msb,type(msb))

    # print(msb*mss,type(msb*mss))
    # c_mul = hm.Mul(c_sb,c2)
    # m_mul = hm.Dec(B_key['sk'],c_mul)
    # print("c_mul:",m_mul,type(m_mul))
예제 #49
0
def max_bits_in_digits(d):
    """
    Returns maximum number of bits fitting in given number of digits eg. 2 digits (99) fits in 7 bits
    :param d: number of digits
    """
    return gmpy2.mpz(gmpy2.ceil(d * (gmpy2.log(10) / gmpy2.log(2))))
예제 #50
0
파일: fc3.py 프로젝트: ggerod/Code
#!/usr/bin/python3
import subprocess
import gmpy2
from gmpy2 import mpz

N =mpz(720062263747350425279564435525583738338084451473999841826653057981916355690188337790423408664187663938485175264994017897083524079135686877441155132015188279331812309091996246361896836573643119174094961348524639707885238799396839230364676670221627018353299443241192173812729276147530748597302192751375739387929)

#N6=gmpy2.mul(6,N)
#rt6N = gmpy2.isqrt(N6)
#A1=rt6N
#A2=rt6N+1
#B1=gmpy2.mul(A1,A1) - N6
#B2=gmpy2.mul(A2,A2) - N6

# x = sqrt((A**2) - 6N)
#A2 = A ** 2
#x = (gmpy2.isqrt(A2 - (6*N))) -2

#>>> B1
#mpz(-196964583030473273123266658613260688730573520313292830146731279751026365681221995415789013203406448897084635027350851945686843616144515898046438742914544125)
#>>> B2
#mpz(-65505485475620074569622727423756953336680463753223255966134738246263093212465065209974072500623587258450057452227357748138839160485320977313355767837140338)
#>>> B3
#mpz(65953612079233123984021203765746782057212592806846318214461803258500179256291864995840868202159274380184520122896136449409165295173873943419727207240263451)

#x1=gmpy2.isqrt(-B2)
#x2=gmpy2.isqrt(B3)

#>>> x1
#mpz(255940394380449594886692315505126271073816530656442568307521829511283316591342)
#>>> x2
예제 #51
0
import math
import struct
import cPickle
import sys
from copy import deepcopy
from fractions import gcd
from numbers import Integral
from itertools import *

from primes import mr_test
from memoize import memoize
from correct_random import CorrectRandom

try:
    from gmpy2 import mpz
    mpz_type = type(mpz())
    has_gmpy = True
except ImportError:
    try:
        from gmpy import mpz
        mpz_type = type(mpz())
        has_gmpy = True
    except ImportError:
        mpz_type = Integral
        has_gmpy = False

random = CorrectRandom()
primes = cPickle.Unpickler(open("10000_primes.pkl")).load()
log_max_primorial = int(math.log(reduce(operator.mul, primes), 2))

def lcm(a,b):
예제 #52
0
#!/usr/local/bin/pypy3
import gmpy2
from gmpy2 import mpz

# 245634634573565468780056745643563568569345634576824563463457356546878005674564356356856934563457682456346345735654687800567456435635685693456345768
# Factors: 3,88,37,37,23,43,289,1933,2539,130099,63799,4715467,10838689,246091348709,267652966241599,2603941883787374089,
numtofactor = mpz(int(input("Enter number to factor: ")))
print("Factors: ", end="")

while (True):
    x = mpz(2)
    y = mpz(2)
    factor = mpz(1)

    while (factor == 1):
        x = gmpy2.mul(x, x)
        x = gmpy2.add(x, 1)
        x = gmpy2.t_mod(x, numtofactor)
        y = gmpy2.mul(y, y)
        y = gmpy2.add(y, 1)
        y = gmpy2.t_mod(y, numtofactor)
        y = gmpy2.mul(y, y)
        y = gmpy2.add(y, 1)
        y = gmpy2.t_mod(y, numtofactor)
        factor = gmpy2.gcd(abs(gmpy2.sub(x, y)), numtofactor)

    if (factor == numtofactor):
        print("Fail.  Remaining number to factor = ", numtofactor)
        exit(1)
    else:
        print(str(factor) + ",", flush=True, end="")
예제 #53
0
sha256_0 = SHA256.new(jks0_input.encode('ascii'))
padded0 = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE(sha256_0, len(jwt0_sig_bytes))

jks1_input = ".".join(jwt1.split('.')[0:2])
sha256_1 = SHA256.new(jks1_input.encode('ascii'))
padded1 = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE(sha256_1, len(jwt0_sig_bytes))

m0 = bytes2mpz(padded0)
m1 = bytes2mpz(padded1)

pkcs1 = asn1tools.compile_files('pkcs1.asn', codec='der')
x509 = asn1tools.compile_files('x509.asn', codec='der')

jwts = []

for e in [mpz(3), mpz(65537)]:
    gcd_res = gcd(pow(jwt0_sig, e) - m0, pow(jwt1_sig, e) - m1)
    #To speed things up switch comments on prev/next lines!
    #gcd_res = mpz(0x143f02c15c5c79368cb9d1a5acac4c66c5724fb7c53c3e048eff82c4b9921426dc717b2692f8b6dd4c7baee23ccf8e853f2ad61f7151e1135b896d3127982667ea7dba03370ef084a5fd9229fc90aeed2b297d48501a6581eab7ec5289e26072d78dd37bedd7ba57b46cf1dd9418cd1ee03671b7ff671906859c5fcda4ff5bc94b490e92f3ba9739f35bd898eb60b0a58581ebdf14b82ea0725f289d1dac982218d6c8ec13548f075d738d935aeaa6260a0c71706ccb8dedef505472ce0543ec83705a7d7e4724432923f6d0d0e58ae2dea15f06b1b35173a2f8680e51eff0fb13431b1f956cf5b08b2185d9eeb26726c780e069adec0df3c43c0a8ad95cbd342)
    print("[*] GCD: ", hex(gcd_res))
    for my_gcd in range(1, 100):
        my_n = c_div(gcd_res, mpz(my_gcd))
        if pow(jwt0_sig, e, my_n) == m0:
            print("[+] Found n with multiplier", my_gcd, " :\n", hex(my_n))
            pkcs1_pubkey = pkcs1.encode("RSAPublicKey", {
                "modulus": int(my_n),
                "publicExponent": int(e)
            })
            x509_der = x509.encode(
                "PublicKeyInfo", {
                    "publicKeyAlgorithm": {
예제 #54
0
 def __init__(self, p, a, b, g, order):
     self.p = mpz(p)
     self.a = mpz(a)
     self.b = mpz(b)
     self.g = (mpz(g[0]), mpz(g[1]))
     self.order = mpz(order)
예제 #55
0
파일: api.py 프로젝트: ResTianTian/tools
def big_num():
    operator = request.values.get('operator')
    result='1'

    try:
        if operator == 'FACT'or operator =='isPrime':
            p = gmpy2.mpz(int(request.values.get('p')))
            if not p:
                resu = {'code': 10001, 'message': '参数不能为空!'}
                return json.dumps(resu, ensure_ascii=False)
            if operator=='FACT':  #p的阶层
                result=gmpy2.fac(p)
            elif operator=='isPrime': #判断p是否是素数
                result=gmpy2.is_prime(p)
        elif operator =='MULMN' or operator =='POWMN':
            p = gmpy2.mpz(int(request.values.get('p')))
            q = gmpy2.mpz(int(request.values.get('q')))
            n = gmpy2.mpz(int(request.values.get('n')))
            if not p and not q and not n:
                resu = {'code': 10001, 'message': '参数不能为空!'}
                return json.dumps(resu, ensure_ascii=False)
            if operator == 'POWMN': #计算p**q mod n
                result=gmpy2.powmod(p,q,n)
            elif operator == 'MULMN':#计算p*q mod n
                result=gmpy2.modf(gmpy2.mul(p,q),n)
        else:
            p = gmpy2.mpz(int(request.values.get('p')))
            q = gmpy2.mpz(int(request.values.get('q')))
            if not p and not q :
                resu = {'code': 10001, 'message': '参数不能为空!'}
                return json.dumps(resu, ensure_ascii=False)
            if operator == 'ADD':#相加
                print('good')
                result=gmpy2.add(p,q)
            elif operator=='SUB':#相减
                result=gmpy2.sub(p,q)
            elif operator=='MUL':#相乘
                result=gmpy2.mul(p,q)
            elif operator=='DIV':#相除
                result=gmpy2.div(p,q)
            elif operator=='MOD':#取余
                result=gmpy2.f_mod(p,q)
            elif operator=='POW':
                result=gmpy2.powmod(p,q)
            elif operator=='GCD':#最大公因数
                result=gmpy2.gcd(p,q)
            elif operator=='LCM':
                result=gmpy2.lcm(p,q)
            elif operator=='OR':#或
                result=p | q
            elif operator=='AND':#与
                result=p & q
            elif operator=='XOR':#抑或
                result=p ^ q
            elif operator=='SHL':#左移
                result=p<<q
            elif operator=='SHR':#右移
                result=p>>q
        resu = {'code': 200, 'result': str(result)}
        return json.dumps(resu, ensure_ascii=False)
    except:
        resu = {'code': 10002, 'message': '异常。'}
        return json.dumps(resu, ensure_ascii=False)
예제 #56
0
def H(ID):
    hash_ID = gmpy2.mpz(hashlib.sha512(ID.encode("utf-8")).hexdigest(), 16)
    res = MapToPoint(E, E.field(hash_ID))
    return res
"""
Use Python 2.X only
"""

import gmpy2
import primefac  # https://pypi.org/project/primefac/
import pdb
import itertools
import time
import python23_encoding

c = gmpy2.mpz(
    5499541793182458916572235549176816842668241174266452504513113060755436878677967801073969318886578771261808846567771826513941339489235903308596884669082743082338194484742630141310604711117885643229642732544775605225440292634865971099525895746978617397424574658645139588374017720075991171820873126258830306451326541384750806605195470098194462985494
)

d = gmpy2.mpz(
    15664449102383123741256492823637853135125214807384742239549570131336662433268993001893338579081447660916548171028888182200587902832321164315176336792229529488626556438838274357507327295590873540152237706572328731885382033467068457038670389341764040515475556103158917133155868200492242619473451848383350924192696773958592530565397202086200003936447
)

phi = gmpy2.mpz(
    25744472610420721576721354142700666534585707423276540379553111662924462766649397845238736588395849560582824664399879219093936415146333463826035714360316647265405615591383999147878527778914526369981160444050742606139799706884875928674153255909145624833489266194817757115584913491575124670523917871310421296173148930930573096639196103714702234087492
)

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

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

## parse factors into list
예제 #58
0
def encode_b(rational):
    upscaled = int(rational * BASE**PRECISION_FRACTIONAL)
    field_element = mpz(upscaled) % Q
    return field_element
예제 #59
0
def setup_hess(P, l):
    t = gmpy2.mpz(random.randint(l // 2, l))
    Q_TA = t * P
    return (t, Q_TA)
예제 #60
0
 def testStringToInteger(self):
     A = ['0', '1']  # Alphabet
     k = 8
     x = mpz(5)
     self.assertEqual(ToString(x, k, A),
                      ['0', '0', '0', '0', '0', '1', '0', '1'])