コード例 #1
0
ファイル: memdump2.py プロジェクト: zenosxx/2FAssassin
def main():
    n = int(sys.argv[2], 16)
    keysize = n.bit_length() / 16
    with open(sys.argv[1], "rb") as f:
        chunk = f.read(16384)
        while chunk:
            for offset in xrange(0, len(chunk) - keysize):
                p = long(
                    ''.join([
                        "%02x" % ord(chunk[x])
                        for x in xrange(offset + keysize - 1, offset - 1, -1)
                    ]).strip(), 16)
                if gmpy.is_prime(p) and p != n and n % p == 0:
                    e = 65537
                    q = n / p
                    phi = (p - 1) * (q - 1)
                    d = gmpy.invert(e, phi)
                    dp = d % (p - 1)
                    dq = d % (q - 1)
                    qinv = gmpy.invert(q, p)
                    seq = Sequence()
                    for x in [0, n, e, d, p, q, dp, dq, qinv]:
                        seq.setComponentByPosition(len(seq), Integer(x))
                        print "\n\n-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n\n" % base64.encodestring(
                            encoder.encode(seq))
                        sys.exit(0)
            chunk = f.read(16384)
        print "private key not found :("

        if __name__ == '__main__':
            main()
コード例 #2
0
ファイル: heartbleed.py プロジェクト: tellnol437/Cheatsheet
def extractkey(host, chunk, modulus):
	
    #print "\nChecking for private key...\n"
    n = int (modulus, 16)
    keysize = n.bit_length() / 16

    for offset in xrange (0, len (chunk) - keysize):
        p = long (''.join (["%02x" % ord (chunk[x]) for x in xrange (offset + keysize - 1, offset - 1, -1)]).strip(), 16)
        if gmpy.is_prime (p) and p != n and n % p == 0:
            if opts.verbose:
                print '\n\nFound prime: ' + str(p)
            e = 65537
            q = n / p
            phi = (p - 1) * (q - 1)
            d = gmpy.invert (e, phi)
            dp = d % (p - 1)
            dq = d % (q - 1)
            qinv = gmpy.invert (q, p)
            seq = Sequence()
            for x in [0, n, e, d, p, q, dp, dq, qinv]:
                seq.setComponentByPosition (len (seq), Integer (x))
            print "\n\n-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n\n" % base64.encodestring(encoder.encode (seq))
            privkeydump = open("hb-certs/privkey_" + host + ".dmp", "a")
            privkeydump.write(chunk)
            return True
        else:
            return False
コード例 #3
0
ファイル: keydump.py プロジェクト: semimitoz/heartbleed-tools
def main(cert_path, data_path, offset):
    mod = get_modulus(cert_path)
    mod = int(mod, 16)
    key_size = int(mod.bit_length() / 16)
    offset = int(offset, 16)
    print('Prime should be at offset: %x' % offset)
    print('Key size: %d\n' % key_size)
    with open(data_path, 'rb') as f:
        data = f.read()
    print('Hexdump of surrounding data:')
    hexdump(data, max(0, offset - 1024), 2048)
    p = long(data, offset, key_size)
    if gmpy.is_prime(p) and p != mod and mod % p == 0:
        print('Prime factor found: %s\n' % p)
        hexbytes = binascii.hexlify(data[offset:offset +
                                         key_size]).decode('ascii').upper()
        hexbytes = re.sub(r'(..)', r'\x\1', hexbytes)
        print('Prime in greppable ascii: %s\n' % hexbytes)
        p = gmpy.mpz(p)
        e = gmpy.mpz(65537)
        q = gmpy.divexact(mod, p)
        phi = (p - 1) * (q - 1)
        d = gmpy.invert(e, phi)
        dp = d % (p - 1)
        dq = d % (q - 1)
        qinv = gmpy.invert(q, p)
        seq = Sequence()
        for x in [0, mod, e, d, p, q, dp, dq, qinv]:
            seq.setComponentByPosition(len(seq), Integer(x))
        print(
            "\n\n-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n\n"
            % base64.encodestring(encoder.encode(seq)).decode('ascii'))
    else:
        print('Prime factor not found')
コード例 #4
0
ファイル: Rsa_Auto.py プロジェクト: f4ck-team/RsaCtfTool
 def _e_is_2(self):
     publickey = raw_input("请输入公钥的绝对路经:")
     key_data = open(publickey, 'rb').read()
     key = RSA.importKey(key_data)
     print("[*] n: " + str(key.n))
     print("[*] e: " + str(key.e))
     x = raw_input("密文格式:1.数字 2. 文件\n")
     c = 0
     if x == '1':
         c = raw_input("请输入密文数字:")
     elif x == '2':
         pathen = raw_input("请输入密文绝对路经:")
         f = open(pathen, 'r').read()
         c = s2n(f)
     print("[*]请分解 n提供pq: " + str(key.n))
     p = raw_input("请输入p:")
     q = raw_input("请输入q:")
     p = int(p)
     q = int(q)
     n = p * q
     r = pow(c, (p + 1) / 4, p)
     s = pow(c, (q + 1) / 4, q)
     a = gmpy.invert(p, q)
     b = gmpy.invert(q, p)
     x = (a * p * s + b * q * r) % n
     y = (a * p * s - b * q * r) % n
     print(n2s(x % n))
     print(n2s((-x) % n))
     print(n2s(y % n))
     print(n2s((-y) % n))
     raw_input("执行完毕,按任意键继续...")
コード例 #5
0
def build_fancy_ssh_key():
    n = 26240039799439281277428991018816126472584192712357885635313159618017867599553946910086493824697325697459899057037252321992434312383526020179103669324033172240080083504036221922015855600754563085717218550168161255435496850472698530773001974651033983647351279774260999491275857855184240838513799742065892227247500196946486743887238163332335265778058266229624732673600138507643201455967290783154676397787677091064108104899760962349320575164417986884080576662581242348768103625357724955359787090235358588550254354354517795469206122862585274648362207432821350507008845767866686240836257288458101839822991339180170660270339
    p = 163493857190096272089714326824687833016230055253025944605019043980668505352847867467836176472809138237630251341555249787949745988391345622816563382634316979998428913478943333115469580963083309536717317636885711244757578668516876376648175000497963982248437505385251001367254125956049451693892145283722300414193
    q = n // p
    e = 65537

    print("n", n)

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

    import gmpy
    d = int(gmpy.invert(e, phi_n))

    print("d", d)

    print("mod", (e * d) % phi_n)
    e1 = d % (p - 1)
    e2 = d % (q - 1)
    print("e1", e1)
    print("e2", e2)

    c = int(gmpy.invert(q, p))
    print("c", c)

    # write new key files
    write_rsa_pub("id.pub", n, e, "qctf")
    write_rsa_pri("id", n, e, d, p, q, e1, e2, c)

    print 'new keys:\n%s\n%s\n' % ("id.pub", "id")
コード例 #6
0
ファイル: modern.py プロジェクト: gitcollect/featherduster
def dsa_repeated_nonce_attack(r,msg1,s1,msg2,s2,n,verbose=False):
   '''
   Recover k (nonce) and Da (private signing key) from two DSA or ECDSA signed messages
   with identical k values
   
   Takes the following arguments:
   string: r (r value of signatures)
   string: msg1 (first message)
   string: s1 (s value of first signature)
   string: msg2 (second message)
   string: s2 (s value of second signature)
   long: n (curve order for ECDSA or modulus (q parameter) for DSA)
   
   adapted from code by Antonio Bianchi ([email protected])
   <http://antonio-bc.blogspot.com/2013/12/mathconsole-ictf-2013-writeup.html>
   '''
   r = string_to_long(r)
   s1 = string_to_long(s1)
   s2 = string_to_long(s2)
   # convert messages to sha1 hash as number
   z1 = string_to_long(SHA.new(msg1).digest())
   z2 = string_to_long(SHA.new(msg2).digest())
   
   sdiff_inv = gmpy.invert(((s1-s2)%n),n)
   k = ( ((z1-z2)%n) * sdiff_inv) % n
   
   r_inv = gmpy.invert(r,n)
   da = (((((s1*k) %n) -z1) %n) * r_inv) % n
   
   if verbose:
      print "Recovered k:" + hex(k)
      print "Recovered Da: " + hex(da)
   
   return (k, da)
コード例 #7
0
ファイル: modern.py プロジェクト: LucaBongiorni/featherduster
def dsa_repeated_nonce_attack(r,msg1,s1,msg2,s2,n,verbose=False):
   '''
   Recover k (nonce) and Da (private signing key) from two DSA or ECDSA signed messages
   with identical k values
   
   Takes the following arguments:
   string: r (r value of signatures)
   string: msg1 (first message)
   string: s1 (s value of first signature)
   string: msg2 (second message)
   string: s2 (s value of second signature)
   long: n (curve order for ECDSA or modulus (q parameter) for DSA)
   
   adapted from code by Antonio Bianchi ([email protected])
   <http://antonio-bc.blogspot.com/2013/12/mathconsole-ictf-2013-writeup.html>
   '''
   r = string_to_long(r)
   s1 = string_to_long(s1)
   s2 = string_to_long(s2)
   # convert messages to sha1 hash as number
   z1 = string_to_long(SHA.new(msg1).digest())
   z2 = string_to_long(SHA.new(msg2).digest())
   
   sdiff_inv = gmpy.invert(((s1-s2)%n),n)
   k = ( ((z1-z2)%n) * sdiff_inv) % n
   
   r_inv = gmpy.invert(r,n)
   da = (((((s1*k) %n) -z1) %n) * r_inv) % n
   
   if verbose:
      print "Recovered k:" + hex(k)
      print "Recovered Da: " + hex(da)
   
   return (k, da)
コード例 #8
0
ファイル: keydump.py プロジェクト: ties/heartbleed-tools
def main(cert_path, data_path, offset):
  mod = get_modulus(cert_path)
  mod = gmpy.mpz(mod, 16)
  key_size = int(mod.bit_length() / 16)
  offset = int(offset, 16)
  print('Prime should be at offset: %x'%offset)
  print('Key size: %d\n'%key_size)
  with open(data_path, 'rb') as f:
    mm_data = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)

    print('Hexdump of surrounding data:')
    hexdump(mm_data, max(0, offset - 1024), 2048)
    p = gmpy.mpz(long(mm_data, offset, key_size))
    if gmpy.is_prime(p) and p != mod and mod % p == 0:
      print('Prime factor found: %s\n'%p)
      hexbytes = binascii.hexlify(mm_data[offset:offset+key_size]).decode('ascii').upper()
      hexbytes = re.sub(r'(..)', r'\x\1', hexbytes)
      print('Prime in greppable ascii: %s\n'%hexbytes)
      p = gmpy.mpz(p)
      e = gmpy.mpz(65537)
      q = gmpy.divexact(mod, p)
      
      assert(gmpy.is_prime(q))

      phi = (p-1) * (q-1)
      d = gmpy.invert(e, phi)
      dp = d % (p - 1)
      dq = d % (q - 1)
      qinv = gmpy.invert(q, p)
      seq = Sequence()
      for x in [0, mod, e, d, p, q, dp, dq, qinv]:
        seq.setComponentByPosition (len (seq), Integer (x))
      print("\n\n-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n\n"%base64.encodestring(encoder.encode(seq)).decode('ascii'))
    else:
      print('Prime factor not found')
コード例 #9
0
def deadbeef(target=_TEST_TARGET, length=128, prime_length=4096,
           public_exponent=65537):
  """Perform the 0xdeadbeef attack.

  Returns a strong prime `p`, a prime `q`, and a private exponent
  `d` such that the last `length` bits of `p * q` is equal to
  `target`. (It is obvious, I hope, that the resulting key does
  not have any particular security guarantee.)

  Or loops forever if the last bit of `target` is `0`.
  """
  d = 0
  while not d:
    N = 2 ** length
    p = pubkey.getStrongPrime(2048-128)
    x = target * 2 ** (2048 - 128 - 2 * length) - 1
    q = x * ((target * invert(p * x, N)) % N)
    while not pubkey.isPrime(q):
      q += N
    phi = (p - 1) * (q - 1)
    d = invert(public_exponent, phi)
  n = p * q
  e = public_exponent
  with open(hex(n)[:18], 'wb') as f:
    f.write("n = {}\ne = {}\nd = {}\np = {}\nq = {}\n"
            .format(n, e, d, p, q))
  return n, e, d, p, q
コード例 #10
0
ファイル: rsatool.py プロジェクト: Xi4or0uji/CTF_Games
 def _calc_values(self):
     self.n = self.p * self.q
     phi = (self.p - 1) * (self.q - 1)
     self.d = gmpy.invert(self.e, phi)
     # CRT-RSA precomputation
     self.dP = self.d % (self.p - 1)
     self.dQ = self.d % (self.q - 1)
     self.qInv = gmpy.invert(self.q, self.p)
コード例 #11
0
 def calculate_differentiation(self, p1, p2):
     if p1 == p2:
         return (
             (3 *
              (p1.x * p1.x) + self.a) * invert(2 * p1.y, self.p)) % self.p
     else:
         return (((p1.y - p2.y) % self.p) *
                 (invert(p1.x - p2.x, self.p))) % self.p
コード例 #12
0
def teal(C, P, Q):
    a, d, p = C
    x1, y1 = P
    x2, y2 = Q
    assert ponc(C, P) and ponc(C, Q)
    x3 = (x1 * y2 + y1 * x2) * gmpy.invert(1 + d * x1 * x2 * y1 * y2, p) % p
    y3 = (y1 * y2 - a * x1 * x2) * gmpy.invert(1 - d * x1 * x2 * y1 * y2,
                                               p) % p
    return (int(x3), int(y3))
コード例 #13
0
ファイル: rsatool.py プロジェクト: ChunHungLiu/ctf-writeup
    def _calc_values(self):
        self.n = self.p * self.q

        phi = (self.p - 1) * (self.q - 1)
        self.d = gmpy.invert(self.e, phi)

        # CRT-RSA precomputation
        self.dP = self.d % (self.p - 1)
        self.dQ = self.d % (self.q - 1)
        self.qInv = gmpy.invert(self.q, self.p)
コード例 #14
0
def common_modules_attack(c1, c2, e1, e2, n):
    gcd, s1, s2 = gmpy.gcdext(e1, e2)
    if s1 < 0:
        s1 = -s1
        c1 = gmpy.invert(c1, n)
    elif s2 < 0:
        s2 = -s2
        c2 = gmpy.invert(c2, n)
    v = pow(c1, s1, n)
    w = pow(c2, s2, n)
    x = (v * w) % n
    return x
コード例 #15
0
ファイル: Paillier.py プロジェクト: wilko77/STRIP
def generateKeyPair(keySize):
    
    primelength = keySize/2
    p = _randomPrime(primelength)
    q = _randomPrime(primelength)
    n = p*q
    nsquared = pow(n,2)
    hp = _L(((p-1)*n+1) % p**2 ,p)
    hp = gmpy.invert(hp,p)
    hq = _L(((q-1)*n+1) % q**2 ,q)
    hq = gmpy.invert(hq, q)
    return PrivateKey(keySize, n, nsquared, p, q, gmpy.invert(p,q), hp, hq),PublicKey(keySize, n, nsquared)
コード例 #16
0
ファイル: rsa.py プロジェクト: sonickun/cryptools
def common_modulus_attack(c1, c2, e1, e2, n):
    gcd, s1, s2 = gcdext(e1, e2)
    if s1 < 0:
        s1 = -s1
        c1 = invert(c1, n)
    if s2 < 0:
        s2 = -s2
        c2 = invert(c2, n)
    v = pow(c1, s1, n)
    w = pow(c2, s2, n)
    m = (v * w) % n
    return m
コード例 #17
0
def common_mode_attack(n, e1, e2, c1, c2):
    print("[*] Try common mode attack")
    _, s1, s2 = gmpy.gcdext(e1, e2)
    if s1 < 0:
        s1 = -s1
        c1 = gmpy.invert(c1, n)
    elif s2 < 0:
        s2 = -s2
        c2 = gmpy.invert(c2, n)

    m = (pow(c1, s1, n) * pow(c2, s2, n)) % n
    print("[*] Maybe success")
    print("[!] flag:", long_to_bytes(m))
    return 1
コード例 #18
0
ファイル: rsatool.py プロジェクト: bmagic/richelieu
    def _calc_values(self):
        if self.n is None:
            self.n = self.p * self.q

        if self.p != self.q:
            phi = (self.p - 1) * (self.q - 1)
        else:
            phi = (self.p ** 2) - self.p

        self.d = gmpy.invert(self.e, phi)

        # CRT-RSA precomputation
        self.dP = self.d % (self.p - 1)
        self.dQ = self.d % (self.q - 1)
        self.qInv = gmpy.invert(self.q, self.p)
コード例 #19
0
ファイル: rsa_common_mod.py プロジェクト: Chr1s-T/cryPtit
def attack(n, e1, e2, c1, c2):
    rst = gcdext(e1, e2)
    s1 = rst[1]
    s2 = rst[2]

    if s1 < 0:
        s1 = -s1
        c1 = invert(c1, n)

    elif s2 < 0:
        s2 = -s2
        c2 = invert(c2, n)

    m = pow(c1, s1) * pow(c2, s2)
    return m
コード例 #20
0
    def add(self,P,Q):

        # P+P=2P
        if P==Q:
            return self.dbl(P)

        # P+0=P
        if P[0]==None:
            return Q
        if Q[0]==None:
            return P

        # P+-P=0
        if Q==self.inv(P):
            return [None,None]

        xP = P[0]
        yP = P[1]
        xQ = Q[0]
        yQ = Q[1]
        s = (yP - yQ) * gmpy.invert(xP - xQ, self.p) % self.p
        xR = (pow(s,2,self.p) - xP -xQ) % self.p
        yR = (-yP + s*(xP-xR)) % self.p
        R = [xR,yR]
        return R
コード例 #21
0
def asn1encodeprivkey(N, e, d, p, q):
    key = pyasn1_modules.rfc3447.RSAPrivateKey()
    dp = d % (p - 1)
    dq = d % (q - 1)
    qInv = gmpy.invert(q, p)
    assert (qInv * q) % p == 1
    key.setComponentByName('version', 0)
    key.setComponentByName('modulus', N)
    key.setComponentByName('publicExponent', e)
    key.setComponentByName('privateExponent', d)
    key.setComponentByName('prime1', p)
    key.setComponentByName('prime2', q)
    key.setComponentByName('exponent1', dp)
    key.setComponentByName('exponent2', dq)
    key.setComponentByName('coefficient', qInv)
    ber_key = pyasn1.codec.ber.encoder.encode(key)
    pem_key = base64.b64encode(ber_key).decode("ascii")
    out = ['-----BEGIN RSA PRIVATE KEY-----']
    out += [pem_key[i:i + 64] for i in range(0, len(pem_key), 64)]
    out.append('-----END RSA PRIVATE KEY-----\n')
    out = "\n".join(out)
    f = open('newkey.pem', 'wb')
    f.write(out.encode("ascii"))
    f.close
    return out.encode("ascii")
def close_factor(n, b):

    # approximate phi
    phi_approx = n - 2 * gmpy.sqrt(n) + 1

    # create a look-up table
    look_up = {}
    z = 1
    for i in range(0, b + 1):
        look_up[z] = i
        z = (z * 2) % n

    # check the table
    mu = gmpy.invert(pow(2, phi_approx, n), n)
    fac = pow(2, b, n)
    j = 0

    # do a bsgs-type attack
    while True:
        mu = (mu * fac) % n
        j += b
        if mu in look_up:
            phi = phi_approx + (look_up[mu] - j)
            break
        if j > b * b:
            return

    # once phi is found, we can compute the factors
    m = n - phi + 1
    roots = (m - gmpy.sqrt(m ** 2 - 4 * n)) / 2, \
            (m + gmpy.sqrt(m ** 2 - 4 * n)) / 2

    return roots
コード例 #23
0
ファイル: affine-cipher.py プロジェクト: madfrogsec/id0-rsa
def main():

    getCoprime(lench)
    for a in list_coprime[0]:
        for index in range(lench):
            print "\n[+] Using key: a={0}, b={1}".format(a, index)
            print decryptAffineCipher(gmpy.invert(a, lench), index)
コード例 #24
0
def multiply_1d(v1, v2):
    assert len(v1) == len(v2)
    assert type(v1[0] == int)
    assert type(v2[0] == int)

    bound = (max(v1) * max(v2)) * (1 + len(v1))

    primes = get_primes(bound)
    modulo_results = []
    for p in primes:
        modulo_results.append(multiply_1d_modulo(v1, v2, p))

    if len(primes) == 1:
        return modulo_results[0]

    total_product = 1
    for p in primes:
        total_product *= p
    coeffs = []
    for p in primes:
        rest = total_product // p
        cur_coeff = rest * gmpy.invert(rest % p, p)
        coeffs.append(cur_coeff)

    result = []
    for i in range(len(modulo_results[0])):
        cur_res = sum(
            [coeffs[j] * modulo_results[j][i] for j in range(len(coeffs))])
        cur_res %= total_product
        result.append(int(cur_res))
    return result
コード例 #25
0
ファイル: cheating.py プロジェクト: RandomsCTF/write-ups
 def __init__(self, e, p, q):
     self.n = p * q
     self.e = e
     self.p = p
     self.q = q
     self.d = long(gmpy.invert(e, (p-1)*(q-1)))
     self.key = RSA.construct((long(self.n), long(self.e), self.d))
コード例 #26
0
 def _ECDSA_sign(self, md):
     # Get the pseudo-random exponent from the messagedigest
     # and the private key.
     order = self.curve.order
     hmk = serialize_number(self.e, SER_BINARY, self.curve.order_len_bin)
     h = hmac.new(hmk, digestmod=hashlib.sha256)
     h.update(md)
     ctr = Crypto.Util.Counter.new(128, initial_value=0)
     cprng = Crypto.Cipher.AES.new(h.digest(),
                                   Crypto.Cipher.AES.MODE_CTR, counter=ctr)
     r = 0
     s = 0
     while s == 0:
         while r == 0:
             buf = cprng.encrypt(b'\0' * self.curve.order_len_bin)
             k = self.curve._buf_to_exponent(buf)
             p1 = self.curve.base * k
             r = p1.x % order
         e = deserialize_number(md, SER_BINARY)
         e = (e % order)
         s = (self.e * r) % order
         s = (s + e) % order
         e = gmpy.invert(k, order)
         s = (s * e) % order
     s = s * order
     s = s + r
     return s
コード例 #27
0
    def add(self, other, curve, mod):
        if self.x == float("inf") and self.y == float("inf") and other.x == float("inf") and other.y == float("inf"):
            return (float("inf"), float("inf"))

        elif self.x == float("inf") and self.y == float("inf"):
            return other

        elif other.x == float("inf") and other.y == float("inf"):
            return self

        point1_curve = self.check_curve(self.x, self.y, curve[0], curve[1], mod)
        point2_curve = self.check_curve(other.x, other.y, curve[0], curve[1], mod)

        if not point1_curve or not point2_curve:
            return "One point is not on the curve"
	
        elif (self.x == other.x) and (self.y == other.y):
            d_up = 3 * self.x ** 2 + curve[0]
            d_low = 2 * self.y

        elif self.x == other.x:
            return (float('inf'), float('inf'))
        else:
            #(y2 - y1),(x2 - x1)
            d_up = other.y - self.y 
            d_low = other.x - self.x

        d_low_mi = gmpy.invert(d_low, mod)
        lmb = (d_up * d_low_mi) % mod

        fin_x = (lmb ** 2 - other.x - self.x) % mod
        fin_y = (lmb * (self.x - fin_x) - self.y) % mod

        return Point(fin_x, fin_y)
コード例 #28
0
ファイル: DSA34.py プロジェクト: HMY626/DSA
def Crack(g, p, q, r, s, H):
    for k in range(2, 65537):
        r0 = pow(g, k, p)
        if r0 % q == r:
            print("Key:%d" % (k))
            x = ((s * k - H) * gmpy.invert(r0, q)) % q
            print("Sercet key is:%s" % (x))
コード例 #29
0
ファイル: daedalus.py プロジェクト: sushant94/daedalus
    def MakePrivateKey(self):
        key = pyasn1_modules.rfc3447.RSAPrivateKey()
        dp = self.d % (self.p - 1)
        dq = self.d % (self.q - 1)
        qInv = gmpy.invert(self.q, self.p)

        key.setComponentByName('version', 0)
        key.setComponentByName('modulus', self.n)
        key.setComponentByName('publicExponent', self.e)
        key.setComponentByName('privateExponent', self.d)
        key.setComponentByName('prime1', self.p)
        key.setComponentByName('prime2', self.q)
        key.setComponentByName('exponent1', dp)
        key.setComponentByName('exponent2', dq)
        key.setComponentByName('coefficient', qInv)

        ber_key = pyasn1.codec.ber.encoder.encode(key)
        pem_key = b64encode(ber_key).decode("ascii")
        out = ['-----BEGIN RSA PRIVATE KEY-----']
        out += [pem_key[i:i + 64] for i in range(0, len(pem_key), 64)]
        out.append('-----END RSA PRIVATE KEY-----\n')
        out = "\n".join(out)
        if not self.outfile == None:
            f = open(self.outfile, 'w')
            f.write(out.encode('ascii'))
            f.close()
        else:
            print out.encode("ascii")
コード例 #30
0
def crt(n, a):
   sum = 0
   prod = functools.reduce(lambda a, b: a*b, n)
   for i,j in zip(n,a):
   	p = prod // i
   	sum += j * gmpy.invert(p,i) * p
   return sum % prod
コード例 #31
0
ファイル: __init__.py プロジェクト: MeeSeongIm/py-seccure
 def _ECDSA_sign(self, md):
     # Get the pseudo-random exponent from the messagedigest
     # and the private key.
     order = self.curve.order
     hmk = serialize_number(self.e, SER_BINARY, self.curve.order_len_bin)
     h = hmac.new(hmk, digestmod=hashlib.sha256)
     h.update(md)
     ctr = Crypto.Util.Counter.new(128, initial_value=0)
     cprng = Crypto.Cipher.AES.new(h.digest(),
                                   Crypto.Cipher.AES.MODE_CTR,
                                   counter=ctr)
     r = 0
     s = 0
     while s == 0:
         while r == 0:
             buf = cprng.encrypt(b'\0' * self.curve.order_len_bin)
             k = self.curve._buf_to_exponent(buf)
             p1 = self.curve.base * k
             r = p1.x % order
         e = deserialize_number(md, SER_BINARY)
         e = (e % order)
         s = (self.e * r) % order
         s = (s + e) % order
         e = gmpy.invert(k, order)
         s = (s * e) % order
     s = s * order
     s = s + r
     return s
コード例 #32
0
def chinese_remainder(c, p, q, dp, dq):
    m1 = pow(c, dp, p)
    m2 = pow(c, dq, q)
    qinv = gmpy.invert(q, p)
    h = (qinv * (m1 - m2)) % p
    m = m2 + h * q
    return m
コード例 #33
0
 def __init__(self, e, p, q):
     self.n = p * q
     self.e = e
     self.p = p
     self.q = q
     self.d = long(gmpy.invert(e, (p - 1) * (q - 1)))
     self.key = RSA.construct((long(self.n), long(self.e), self.d))
コード例 #34
0
ファイル: remunge.py プロジェクト: tomrittervg/cooperpair
def v3privkey(n, e, d, p, q):
    """Builds a PGPv3 private key packet
    """
    ptag = '\x95'
    pver = '\x03'
    timestamp = four_octet(2 ** 25 * 41)
    expiration = two_octet(0)
    pubkey_algo = '\x01'
    s2k_encryption = '\x00' #Not Encrypted

    #Why does OpenPGP make q the larger prime?
    if p > q:
        tmp = q
        q = p
        p = tmp
    u = invert(p, q)

    checksum = 0
    for b in bytearray().join([to_mpi(d), to_mpi(p), to_mpi(q), to_mpi(u)]):
      checksum += b
    checksum %= 65536
    checksum = two_octet(checksum)

    body = bytearray().join([pver, timestamp, expiration, pubkey_algo,
                             to_mpi(n), to_mpi(e), s2k_encryption, 
                             to_mpi(d), to_mpi(p), to_mpi(q), to_mpi(u), 
                             checksum])
    plen = two_octet(len(body))
    return bytearray().join([ptag, plen, body])
コード例 #35
0
ファイル: daedalus.py プロジェクト: sushant94/daedalus
    def MakePrivateKey(self):
        key = pyasn1_modules.rfc3447.RSAPrivateKey()
        dp = self.d % (self.p - 1)
        dq = self.d % (self.q - 1)
        qInv = gmpy.invert(self.q, self.p)

        key.setComponentByName('version', 0)
        key.setComponentByName('modulus', self.n)
        key.setComponentByName('publicExponent', self.e)
        key.setComponentByName('privateExponent', self.d)
        key.setComponentByName('prime1', self.p)
        key.setComponentByName('prime2', self.q)
        key.setComponentByName('exponent1', dp)
        key.setComponentByName('exponent2', dq)
        key.setComponentByName('coefficient', qInv)
        
        ber_key = pyasn1.codec.ber.encoder.encode(key)
        pem_key = b64encode(ber_key).decode("ascii")
        out = ['-----BEGIN RSA PRIVATE KEY-----']
        out += [pem_key[i:i + 64] for i in range(0, len(pem_key), 64)]
        out.append('-----END RSA PRIVATE KEY-----\n')
        out = "\n".join(out)
        if not self.outfile == None:
            f = open(self.outfile, 'w')
            f.write(out.encode('ascii'))
            f.close()
        else:
            print out.encode("ascii")
コード例 #36
0
ファイル: remunge.py プロジェクト: tomrittervg/cooperpair
def v3privkey(n, e, d, p, q):
    """Builds a PGPv3 private key packet
    """
    ptag = '\x95'
    pver = '\x03'
    timestamp = four_octet(2**25 * 41)
    expiration = two_octet(0)
    pubkey_algo = '\x01'
    s2k_encryption = '\x00'  #Not Encrypted

    #Why does OpenPGP make q the larger prime?
    if p > q:
        tmp = q
        q = p
        p = tmp
    u = invert(p, q)

    checksum = 0
    for b in bytearray().join([to_mpi(d), to_mpi(p), to_mpi(q), to_mpi(u)]):
        checksum += b
    checksum %= 65536
    checksum = two_octet(checksum)

    body = bytearray().join([
        pver, timestamp, expiration, pubkey_algo,
        to_mpi(n),
        to_mpi(e), s2k_encryption,
        to_mpi(d),
        to_mpi(p),
        to_mpi(q),
        to_mpi(u), checksum
    ])
    plen = two_octet(len(body))
    return bytearray().join([ptag, plen, body])
コード例 #37
0
ファイル: ShoupProtocol.py プロジェクト: vs-uulm/PriCloud
    def resp(publickey, secretkey, r, challenge):
        """is a probabilistic algorithm run by the prover to generate
        the third message. The input is the public key, the secret
        key, as well as a nonce r and the challenge itself, generated
        by genChallenge.
        The result of this function is the response as well as the
        modulus n.

        >>> import os
        >>> (publickey, secretkey) = ShoupProtocol.setup()
        >>> r = os.urandom(2048)
        >>> challenge = ShoupProtocol.genChallenge(os.urandom(32))
        >>> ShoupProtocol.resp(publickey, secretkey, r, challenge) # doctest: +ELLIPSIS
        (mpz(...), ...)
        """
        (y, n) = publickey
        (p, q) = secretkey
        # We output a random 2^(3*5)th root of +- r * y ^challenge, where
        # the sign is chosen such that a root exists.
        r = pow(int.from_bytes(r, "little"), 2, n)
        base = r * pow(y, challenge, n)
        # Choose the sign accordingly
        if gmpy.jacobi(base, n) <= 0:
            base = (n - base) % n
        s = gmpy.invert(p, q)
        t = gmpy.invert(q, p)
        for i in range(3 * 5):  # 5 is the security parameter
            # In this loop we compute modular roots
            # Since p,q = 3 mod 4, a root mod p is just pow(a, (p + 1) / 4, p)
            # but we need to use the chinese remainder theorem to lift
            # if to mod n
            # compute mod p
            ap = base % p
            ap = pow(base, (p + 1) // 4, p)
            # choose the one which is a quadratic residue
            if gmpy.jacobi(ap, p) <= 0:
                ap = (p - ap) % p
            # compute mod q
            aq = base % q
            aq = pow(base, (q + 1) // 4, q)
            # choose the one which is a quadratic residue
            if gmpy.jacobi(aq, q) <= 0:
                aq = (q - aq) % q
            # we have s, t, such that sp+tq = 1
            # so the solution is simply ap*t*q + aq*s*p
            base = ap * t * q + aq * s * p
        return (base, n)
コード例 #38
0
def generate_keys(nbits):
    p = cry.getPrime(nbits//2)
    q = cry.getPrime(nbits//2)
    n = p*q
    g = n+1
    l = (p-1)*(q-1)
    mu = gmpy.invert(((p-1)*(q-1)), n)
    return (n, g, l, mu)
コード例 #39
0
def decrypt2(key, cipher):
    n_sqr = key.modulus * key.modulus
    # Remove random factor from the encryption.
    noise = pow(RANDOM, key.modulus, n_sqr)
    invnoise = gmpy.invert(noise, n_sqr)
    normalized = (cipher * invnoise) % n_sqr
    # The n^2 modulus isn't a hard case of the discrete logarithm problem.
    return ((normalized-1)//key.modulus) // ((key.generator-1)//key.modulus)
コード例 #40
0
ファイル: part1.py プロジェクト: tomasra/studijos
def decrypt(cipher, xs, zs, p, q):
    b = []
    for i, xi in enumerate(xs):
        bi = 1
        for j, xj in enumerate(xs):
            if (i != j):
                bi *= xj
                bi *= gmpy.invert(xj - xi, q)
        bi = bi % q
        b.append(bi)    

    z = 1
    for i, bi in enumerate(b):
        z *= pow(zs[i], bi, p)

    msg = cipher[1] * gmpy.invert(z, p) % p
    return num_to_letters(msg)
コード例 #41
0
ファイル: rsa.py プロジェクト: YuriFA/rsa_backdoored
	def build_keys(self, with_backdoor=False):
		if with_backdoor:
			self.rsa = backdoor.backdoor_rsa(self.bit_count)
		else:
			self.generate_params()
		self.dp = self.rsa.d % (self.rsa.p - 1)
		self.dq = self.rsa.d % (self.rsa.q - 1)
		self.qinv = gmpy.invert(self.rsa.q, self.rsa.p)
コード例 #42
0
ファイル: problem.py プロジェクト: SeahunOh/ctf
def test(n, p, q):
  e = get_random_prime(20)
  pk, sk = (n, e), (long(gmpy.invert(e, (p-1)*(q-1))), )
  print "[+] RSA Self Test: %r" % (pk, )
  c = encrypt(pk, FLAG)
  print "[+] ciphertext = %d" % c
  m = decrypt(pk, sk, c)
  print "[+] Dec(Enc(m)) == m? : %s" % (m == FLAG)
コード例 #43
0
def test(n, p, q):
    e = 17 * get_random_prime(20)
    pk, sk = (n, e), (long(gmpy.invert(e, (p - 1) * (q - 1))), )
    print "[+] RSA Self Test: %r" % (pk, )
    c = encrypt(pk, FLAG)
    print "[+] ciphertext = %d" % c
    m = decrypt(pk, sk, c)
    print "[+] Dec(Enc(m)) == m? : %s" % (m == FLAG)
コード例 #44
0
ファイル: dlog.py プロジェクト: chiggum/crypto
def dlog(p, g, h, B):
    left = { (h*invert(pow(g, x1, p), p)) % p : x1 for x1 in xrange(B) }
    g_b = pow(g, B, p)
    for x0 in xrange(B):
        value = pow(g_b, x0, p)
        if value in left:
            return x0, left[value]
    return None
コード例 #45
0
ファイル: ec_serv.py プロジェクト: pbiernat/BlackBox
def generate_backdoor(curve,d):
    #Create a known relationship between P and Q
    Q = curve.base
    Q = Q * d

    e = gmpy.mpz(0)
    e = gmpy.invert(gmpy.mpz(d),curve.order)
    return Q
コード例 #46
0
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(gmpy.invert(e,(p-1)*(q-1)))
コード例 #47
0
ファイル: cryp_RSA.py プロジェクト: htx1219/Python
def crt(a, m):
    M = 1
    for i in m:
        M *= i
        b = [gmpy.invert(M / m[i], m[i]) for i in range(len(m))]
        x = 0
    for i in range(len(m)):
        x += a[i] * b[i] * M / m[i]
    return x
コード例 #48
0
ファイル: dsa.py プロジェクト: diakovliev/x86-safebooter
def dsa_check(r,s):
  w = gmpy.invert(s,Q)
  print "w: 0x%X" % w
  u1 = (sha2 * w) % Q
  print "u1: 0x%X" % u1
  u2 = (r * w) % Q
  print "u2: 0x%X" % u2
  v = (pow(G,u1,P) * pow(pub,u2,P)) % P % Q
  print "v: 0x%X" % v
  return r - v
コード例 #49
0
ファイル: oracle.py プロジェクト: rot256/Wargames
def rsa_new(size = 2**1024):
    p = get_prime(0, size)
    q = get_prime(0, size)
    n = p * q
    e = 65537
    t = totient(p, q)
    if t % e == 0:
        return rsa_new()
    d = int(invert(e, t))
    return (e, n), (d, n)
コード例 #50
0
ファイル: part2.py プロジェクト: tomasra/studijos
def verify(msg, alpha, beta, gamma, delta, p, q):
    delta_inv = gmpy.invert(delta, q)
    e1 = (msg * delta_inv) % q
    e2 = (gamma * delta_inv) % q
    left = (pow(alpha, e1, p) * pow(beta, e2, p)) % p
    right = gamma % q
    if ((left % q) == right):
        return True
    else:
        return False
コード例 #51
0
 def to_affine(self):
     if self.z == 0:
         return AffinePoint(x=0, y=0, curve=self.curve)
     m = self.curve.m
     h = gmpy.invert(self.z, m)
     y = (h * h) % m
     x = (self.x * y) % m
     y = (y * h) % m
     y = (y * self.y) % m
     return AffinePoint(x=x, y=y, curve=self.curve)
コード例 #52
0
ファイル: btrsync.py プロジェクト: RobinMorisset/Btrsync
def round_neil(hashes, pi_oscar, prev_pp=1, prev_d=1):
    p = generate_next_p()
    pi_neil = product_mod(p, hashes)
    d = pi_oscar * gmpy.invert(pi_neil, p)

    # TODO CRT d/prev_d
    d = d * prev_pp * gmpy.invert(prev_pp, p) + prev_d * p * gmpy.invert(p, prev_pp)
    pp = p * prev_pp

    (oscar, neil) = make_frac(pp, d)
    if oscar == None:
        return (pp, d, None)
    factors_neil = factor(neil, hashes)

    if factors_neil != None:
        files_neil = [hashes[h] for h in factors_neil]
        return (pp, d, (oscar, files_neil))
    else:
        return (pp, d, None)
コード例 #53
0
ファイル: dsa.py プロジェクト: diakovliev/x86-safebooter
def dsa_sign():
  k_inv = gmpy.invert(k,Q)
  print "k_inv: 0x%X" % k_inv
  r = pow(G,k,P)
  r = r % Q
  print "r: 0x%X" % r
  s = (r*priv) % Q
  s = (s + sha2) % Q
  s = (s * k_inv) % Q
  print "s: 0x%X" % s
  return [r,s]
コード例 #54
0
	def cmbm1(n1,k1,p1=1009) :
		'''
		C(n1,k1) % p1 where p1 is prime
		'''
		r1,r2=max(k1,n1-k1),min(k1,n1-k1)
		if not r2 : return 1
		nm1,dn1=1,1
		for j1 in xrange(r1+1,n1+1) : nm1=(nm1*j1)%p1
		for j1 in xrange(2,r2+1) : dn1*=j1#(dn1*invert(j1,p1))%p1
		dn1=invert(dn1,p1)
		return (nm1*dn1)%p1
コード例 #55
0
ファイル: addrgen.py プロジェクト: jpelias/electron.block.io
 def double(p1):
     p = p1.curve.prime
     a = p1.curve.a
     inverse = gmpy.invert((2 * p1.y), p)
     three_x2 = 3 * (p1.x ** 2)
     l = ((three_x2 + a) * inverse) % p
     x3 = (l ** 2 - 2 * p1.x) % p
     y3 = (l * (p1.x - x3) - p1.y) % p
     if 0 > y3:
         y3 = p + y3
     return Point(p1.curve, x3, y3)