Ejemplo n.º 1
0
def calculate_dh_secret(their_public, my_private):
    #validate public key to protect against a small subgroup attack
    if their_public < 2 or their_public > p-1:
        print("invalid public key")
        return None
    if pow(their_public, q, prime) != 1:
        print("invalid public key")
        return None
    # Calculate the shared secret
    shared_secret = pow(their_public, my_private, prime)

    # Hash the value so that:
    # (a) There's no bias in the bits of the output
    #     (there may be bias if the shared secret is used raw)
    # (b) We can convert to raw bytes easily
    # (c) We could add additional information if we wanted
    # Feel free to change SHA256 to a different value if more appropriate
    #TOM: changed to SHA-1 to comply with RFC standard

    #oid for AES-256
    keyspecificinfo = "aes 42"
    #number of bits in AES-256 key
    supppubinfo = "00 00 01 00 "
    #first block of 160 bits, we need an additional 96 bits
    KM1 = SHA.new(bytes(shared_secret + "00 00 00 01" + keyspecificinfo + supppubinfo, "ascii")).hexdigest()
    KM2 = SHA.new(bytes(shared_sected + "00 00 00 02" + keyspecificinfo + supppubinfo, "ascii")).hexdigest()
    KM3 = SHA.new(bytes(shared_sected + "00 00 00 03" + keyspecificinfo + supppubinfo, "ascii")).hexdigest()
    #the shared hash has 60 bytes
    #we need 32 for the key and 16 more for the iv
    shared_hash = KM1 + KM2 + KM3
    return shared_hash
Ejemplo n.º 2
0
def main():
    print("=== Test of my implementation of DSA signer/verifyier ===")
    test_MyDSASigner()
    print("=== Verifying signature ===")
    msg = b"""For those that envy a MC it can be hazardous to your health\nSo be friendly, a matter of life and death, just like a etch-a-sketch\n"""
    hb = SHA.new(msg).digest()
    hi = int.from_bytes(hb, byteorder="big")
    assert hi == 0xD2D0714F014A9784047EAECCF956520045C45265  # check from website
    y = number.bytes_to_long(
        b"\x08\x4a\xd4\x71\x9d\x04\x44\x95\x49\x6a\x32\x01\xc8\xff\x48\x4f\xeb\x45\xb9\x62\xe7\x30\x2e\x56\xa3\x92\xae\xe4\xab\xab\x3e\x4b\xde\xbf\x29\x55\xb4\x73\x60\x12\xf2\x1a\x08\x08\x40\x56\xb1\x9b\xcd\x7f\xee\x56\x04\x8e\x00\x4e\x44\x98\x4e\x2f\x41\x17\x88\xef\xdc\x83\x7a\x0d\x2e\x5a\xbb\x7b\x55\x50\x39\xfd\x24\x3a\xc0\x1f\x0f\xb2\xed\x1d\xec\x56\x82\x80\xce\x67\x8e\x93\x18\x68\xd2\x3e\xb0\x95\xfd\xe9\xd3\x77\x91\x91\xb8\xc0\x29\x9d\x6e\x07\xbb\xb2\x83\xe6\x63\x34\x51\xe5\x35\xc4\x55\x13\xb2\xd3\x3c\x99\xea\x17"
    )
    r = 548099063082341131477253921760299949438196259240
    s = 857042759984254168557880549501802188789837994940
    myDSA = MyDSASigner()
    print("Verification:", myDSA.verify((r, s), hb, y))
    print("=== Breaking x from k ===")
    k = find_k(r)
    x = (s * k - hi) * number.inverse(r, q)
    x = x % q
    print("x:", x)
    print("=== Verifying x by signer ===")
    sig = myDSA.sign(hb, x, k)
    assert (r, s) == sig
    print("OK")
    print("=== Verifying x by hash ===")
    xh = hex(x)[2:]
    print("encoded x:", xh)
    ch = SHA.new(xh.encode("ascii")).digest()
    print("SHA-1 hash of x:", hex(int.from_bytes(ch, byteorder="big"))[2:])
    assert hex(int.from_bytes(ch, byteorder="big"))[2:] == "954edd5e0afe5542a4adf012611a91912a3ec16"
Ejemplo n.º 3
0
def EMSAPSSVER(M, EM, emBits, sLen = 16):
    mHash = SHA.new(M).digest()
    hLen = len(mHash)
    emLen = utils.ceil(emBits, 8)

    if emLen < hLen + sLen + 2 or EM[len(EM) - 1] != '\xbc':
        print "Inconsistent"
        return False

    maskedDB, h = EM[:emLen - hLen - 1], EM[emLen - hLen - 1: -1]

    octets, bits = (8 * emLen - emBits) / 8, (8 * emLen - emBits) % 8
    zero = maskedDB[:octets] + chr(ord(maskedDB[octets]) & ~(255 >>bits))

    for c in zero:
        if c != '\x00':
            return False

    dbMask = MGF(h, emLen - hLen - 1)
    DB = stringXOR(maskedDB, dbMask)
    newByte = chr(ord(DB[octets]) & (255 >> bits))
    DB = ('\x00' * octets) + newByte + DB[octets+1:]

    for c in DB[:emLen - hLen - sLen - 2]:
        if c != '\x00':
            return False

    if DB[emLen - hLen - sLen - 2] != '\x01':
        return False

    salt = DB[-sLen:]
    m_prime = ('\x00' * 8) + mHash + salt
    h_prime = SHA.new(m_prime).digest()

    return h_prime == h
Ejemplo n.º 4
0
    def checkPeer(self, addr, port, peer_pub_key, self_pub_key, connection):
        peer_pub_key_hash = SHA.new()
        peer_pub_key_hash.update(peer_pub_key)
        self_pub_key_hash = SHA.new()
        self_pub_key_hash.update(self_pub_key)

        print "Checking: addr:{}, port:{}, peer_pub_key_hash:{}, self_pub_key_hash:{}".format(
            addr, port, peer_pub_key_hash.hexdigest(), self_pub_key_hash.hexdigest())
        return True
Ejemplo n.º 5
0
def decryptAES(file, ciphertext):
    # print "AES"
    text = b''
    # base64_decoded_text = base64.b64decode(ciphertext)
    base64_decoded_text =ciphertext.decode('base64')
    key = "0xccb97558940b82637c8bec3c770f86fa3a391a56"


    #read salt from file
    fo = open(file, "rb")
    salt = readBytes(fo)

    version = struct.unpack('b', fo.read(1))[0]

    # read encryptionKey from file
    if version != -1:
        encrypt_key = readBytes(fo)
        if version >=2:
            encrypt_key = readBytes(fo)

    # var 'key2key' means RC2 key to AES key
    print "encrypt_key(%d): %s" % (len(encrypt_key), encrypt_key.encode('hex'))
    hasher = SHA.new()
    hasher.update(salt)
    hasher.update(key)
    # hasher.update(key)
    # hasher.update(salt)
    key2key = hasher.digest()
    print key2key.encode('hex')

    for i in range(1, 5):
        hasher = SHA.new()
        hasher.update(key2key)
        key2key = hasher.digest()
        print key2key.encode('hex')

    print "key2key len:", len(key2key)
    print "key2key:", key2key.encode("hex")

    print encrypt_key[:8].encode('hex')
    rc2 = ARC2.new(key2key[8:], ARC2.MODE_CBC, key2key[:8])

    print encrypt_key[8:].encode('hex')
    key = rc2.decrypt(encrypt_key)

    print "key:", key.encode('hex')


    # iv = ciphertext.index(0, 16)
    # ciphertext2 = ciphertext.index(16)
    #
    # AESCipher = AES.new(key, AES.MODE_CBC, iv)
    #
    # text = AESCipher.decrypt(ciphertext2)

    fo.close()
    return text
Ejemplo n.º 6
0
 def aes_calculate(self, msg_key, direction="to server"):
     x = 0 if direction == "to server" else 8
     sha1_a = SHA.new(msg_key + self.auth_key[x:x+32]).digest()
     sha1_b = SHA.new(self.auth_key[x+32:x+48] + msg_key + self.auth_key[48+x:64+x]).digest()
     sha1_c = SHA.new(self.auth_key[x+64:x+96] + msg_key).digest()
     sha1_d = SHA.new(msg_key + self.auth_key[x+96:x+128]).digest()
     aes_key = sha1_a[0:8] + sha1_b[8:20] + sha1_c[4:16]
     aes_iv = sha1_a[8:20] + sha1_b[0:8] + sha1_c[16:20] + sha1_d[0:8]
     return aes_key, aes_iv
Ejemplo n.º 7
0
 def verify_sign(self,busi_data,sign):
     print publickey,privatekey
     signn=base64.b64decode(sign)
     h=SHA.new(busi_data)
     verifier = pk.new(publickey)
     if verifier.verify(SHA.new(busi_data), sign):
         print "verify data ok"
         return True
     else:
         print "verify data failed"
         return False
Ejemplo n.º 8
0
def test_extract_k():
    print('=== Extract k from two signatures ===')
    myDSA = MyDSASigner()
    x = 42
    k = 57
    h1 = SHA.new(b'test message 1').digest()
    h2 = SHA.new(b'test message 2').digest()
    s1 = myDSA.sign(h1, x, k)
    s2 = myDSA.sign(h2, x, k)
    k1 = extract_k(s1, s2, h1, h2)
    k2 = extract_k(s2, s1, h2, h1)
    assert k1 == k2
Ejemplo n.º 9
0
 def _checkSignaturePath(self, path, signature, maxDepth=128):
   if len(path) > maxDepth:
     return self._checkSignature(path, signature)       
   
   candidate = ''
   for index, segment in enumerate(path):
     candidate = SHA.new(candidate + segment).hexdigest()
     if hexToBase(SHA.new(candidate + str(Root.componentSecret)).hexdigest()[:20]) == signature:                
       #verify the implementations are in sync
       return self._checkSignature(path[:index+1], signature)  
   else:      
     return False
Ejemplo n.º 10
0
def addUser( configSettings, userName, passWord ):
    dbInst = DBStorage.DBStorage( "Cron", configSettings[ 'dbhost' ], configSettings[ 'dbtype' ], 
                                            userName=configSettings[ 'dbuser' ], passWord=configSettings[ 'dbpass' ] )
    dbInst.dbOpen()
    instanceCursor = dbInst.getCursor()
    sqlToRun = "SELECT userName FROM Users WHERE userName = '******';" % userName
    dbInst.execSQL( instanceCursor, sqlToRun )
    retRow = dbInst.returnSingle( instanceCursor )
    if retRow is None:
        print "Adding User: %s" % userName
        sqlToRun = "INSERT INTO Users VALUES( NULL, '%s', '%s' );" % ( userName, sha.new( passWord ).digest() )
        dbInst.execSQL( instanceCursor, sqlToRun )
    else:
        print "Updating Password For User: %s" % userName
        dbInst.execSQL( instanceCursor, "UPDATE Users SET userPassWord = '******';" % sha.new( passWord ).digest() )
Ejemplo n.º 11
0
    def run():
        #get command line arguments and initialize socket
        connection_type, hostname, k1, k2 = get_args()
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        #calculate first 128 bits of hash of key k1
        k1_sha = SHA.new(k1.encode())
        k1_sha_digest_128 = k1_sha.digest()[:16]

        #calculate first 128 bits of hash of key k1
        k2_sha = SHA.new(k2.encode())
        k2_sha_digest_128 = k2_sha.digest()[:16]

        if connection_type == 'client':
            try:
                s.connect((hostname, PORT_NUM))
                inputs_list = [s, sys.stdin]
                outputs_list = [s]

                #starts listening for a message from the server or user inpu
                while True:
                    inputs_ready, outputs_ready, exceptions_ready = select.select(inputs_list, outputs_list, [])
                    for curr_socket in inputs_ready:
                        if curr_socket == sys.stdin:
                            send_message(k1_sha_digest_128, k2_sha_digest_128, outputs_ready)
                        elif curr_socket == s:
                            receive_message(curr_socket, k1_sha_digest_128, k2_sha_digest_128, inputs_list, outputs_list)
            except socket.error:
                print 'No active server at specified hostname'

        elif connection_type == 'server':
            s.bind(('', PORT_NUM))
            s.listen(1)
            inputs_list = [s, sys.stdin]
            outputs_list = []

            #start listening for hosts trying to connect, user input or messages from the client
            while True:
                inputs_ready, outputs_ready, exceptionsReady = select.select(inputs_list, outputs_list, [])
                for curr_socket in inputs_ready:
                    if curr_socket == s:
                        c, addr = s.accept()
                        inputs_list.append(c)
                        outputs_list.append(c)
                    elif curr_socket == sys.stdin:
                        send_message(k1_sha_digest_128, k2_sha_digest_128, outputs_ready)
                    else:
                       receive_message(curr_socket, k1_sha_digest_128, k2_sha_digest_128, inputs_list, outputs_list)
Ejemplo n.º 12
0
 def _parse_kexdh_init(self, m):
     # server mode
     self.e = m.get_mpint()
     if (self.e < 1) or (self.e > P - 1):
         raise SSHException('Client kex "e" is out of range')
     K = pow(self.e, self.x, P)
     key = str(self.transport.get_server_key())
     # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || e || f || K)
     hm = Message()
     hm.add(self.transport.remote_version, self.transport.local_version,
            self.transport.remote_kex_init, self.transport.local_kex_init)
     hm.add_string(key)
     hm.add_mpint(self.e)
     hm.add_mpint(self.f)
     hm.add_mpint(K)
     H = SHA.new(str(hm)).digest()
     self.transport._set_K_H(K, H)
     # sign it
     sig = self.transport.get_server_key().sign_ssh_data(self.transport.rng, H)
     # send reply
     m = Message()
     m.add_byte(chr(_MSG_KEXDH_REPLY))
     m.add_string(key)
     m.add_mpint(self.f)
     m.add_string(str(sig))
     self.transport._send_message(m)
     self.transport._activate_outbound()
Ejemplo n.º 13
0
 def Generate(self):
     if not os.path.exists(self.source_dir_):
         print("The source directory %s is invalid." % self.source_dir_)
         return
     try:
         zip_file = '%s.tmp' % self.output_file_
         self.__Compress(self.source_dir_, zip_file)
         signer = PKCS1_v1_5.new(self.RSAkey)
         zfile = open(zip_file, 'rb')
         sha = SHA.new(zfile.read())
         signature = signer.sign(sha)
         xpk = open(self.output_file_, 'wb')
         zfile.seek(0)
         print('Generating XPK package: %s' % self.output_file_)
         xpk.write('\x43\x72\x57\x6B')
         xpk.write(struct.pack('<I', len(self.pubkey)))
         xpk.write(struct.pack('<I', len(signature)))
         xpk.write(self.pubkey)
         xpk.write(signature)
         xpk.write(zfile.read())
         zfile.close()
         xpk.close()
         print('Generated new XPK package %s successfully.'
               % self.output_file_)
     except IOError:
         if os.path.exists(self.output_file_):
             os.remove(self.output_file_)
         traceback.print_exc()
     finally:
         if os.path.exists(zip_file):
             os.remove(zip_file)
Ejemplo n.º 14
0
 def _parse_kexdh_gex_init(self, m):
     self.e = m.get_mpint()
     if (self.e < 1) or (self.e > self.p - 1):
         raise SSHException('Client kex "e" is out of range')
     self._generate_x()
     self.f = pow(self.g, self.x, self.p)
     K = pow(self.e, self.x, self.p)
     key = str(self.transport.get_server_key())
     # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || min || n || max || p || g || e || f || K)
     hm = Message()
     hm.add(self.transport.remote_version, self.transport.local_version,
            self.transport.remote_kex_init, self.transport.local_kex_init,
            key)
     if not self.old_style:
         hm.add_int(self.min_bits)
     hm.add_int(self.preferred_bits)
     if not self.old_style:
         hm.add_int(self.max_bits)
     hm.add_mpint(self.p)
     hm.add_mpint(self.g)
     hm.add_mpint(self.e)
     hm.add_mpint(self.f)
     hm.add_mpint(K)
     H = SHA.new(str(hm)).digest()
     self.transport._set_K_H(K, H)
     # sign it
     sig = self.transport.get_server_key().sign_ssh_data(self.transport.randpool, H)
     # send reply
     m = Message()
     m.add_byte(chr(_MSG_KEXDH_GEX_REPLY))
     m.add_string(key)
     m.add_mpint(self.f)
     m.add_string(str(sig))
     self.transport._send_message(m)
     self.transport._activate_outbound()
Ejemplo n.º 15
0
 def _verify_sign(self, public_key, sign_str, sign):
     rsa_key = RSA.importKey(public_key)
     signer = PKCS1_v1_5.new(rsa_key)
     digest = SHA.new(sign_str)
     if signer.verify(digest, base64.decodestring(sign)):
         return True
     return False
Ejemplo n.º 16
0
 def _parse_kexdh_gex_reply(self, m):
     host_key = m.get_string()
     self.f = m.get_mpint()
     sig = m.get_string()
     if (self.f < 1) or (self.f > self.p - 1):
         raise SSHException('Server kex "f" is out of range')
     K = pow(self.f, self.x, self.p)
     # okay, build up the hash H of (V_C || V_S || I_C || I_S || K_S || min || n || max || p || g || e || f || K)
     hm = Message()
     hm.add(self.transport.local_version, self.transport.remote_version,
            self.transport.local_kex_init, self.transport.remote_kex_init,
            host_key)
     if not self.old_style:
         hm.add_int(self.min_bits)
     hm.add_int(self.preferred_bits)
     if not self.old_style:
         hm.add_int(self.max_bits)
     hm.add_mpint(self.p)
     hm.add_mpint(self.g)
     hm.add_mpint(self.e)
     hm.add_mpint(self.f)
     hm.add_mpint(K)
     self.transport._set_K_H(K, SHA.new(str(hm)).digest())
     self.transport._verify_key(host_key, sig)
     self.transport._activate_outbound()
Ejemplo n.º 17
0
def sign(message, sender_private_key):

    h = SHA.new(message)
    signer = PKCS1_v1_5.new(sender_private_key)
    signature = signer.sign(h)
    
    return signature
Ejemplo n.º 18
0
def H2(message):
	# hash the message
	digest = SHA.new(message).hexdigest()
	# convert to integer
	x = int(digest, 16)
	# take it mod p
	return x % p
Ejemplo n.º 19
0
 def randomize(self, N = 0):
     "Adds N bits of entropy to random pool.  If N is 0, fill up pool."
     import os, string, time
     if N <= 0:
         bits = self.bits - self.entropy
     else:
         bits = N*8
     if bits == 0:
         return
     #rintbits,'bits of entropy are now required.  Please type on the keyboard'
     #rint'until enough randomness has been accumulated.'
     kb = KeyboardEntry()
     s=''    # We'll save the characters typed and add them to the pool.
     hash = self._hash
     e = 0
     try:
         while e < bits:
             temp=str(bits-e).rjust(6)
             os.write(1, temp)
             s=s+kb.getch()
             e += self.add_event(s)
             os.write(1, 6*chr(8))
         self.add_event(s+hash.new(s).digest() )
     finally:
         kb.close()
     #rint'\n\007 Enough.  Please wait a moment.\n'
     self.stir_n()   # wash the random pool.
     kb.close(4)
Ejemplo n.º 20
0
def asymmetricSign(message, key):
	"""Returns a signature of inpString signed with 'key'."""
	key = RSA.importKey(key)
	h = SHA.new()
	h.update(message)
	signer = PKCS1_PSS.new(key)
	return binascii.b2a_base64(signer.sign(h))
Ejemplo n.º 21
0
def pam_conv(auth,query_list,userdata):
	resp = []

	for i in range(len(query_list)):
		query, type = query_list[i]
		if type == PAM.PAM_PROMPT_ECHO_ON:
			val = raw_input(query)
			resp.append((val,0))
		elif type == PAM.PAM_PROMPT_ECHO_OFF:
			challenge = os.urandom(20)
			sha1 = SHA.new(challenge)
			sha1.update(challenge)
			digest = sha1.digest()
			print "PYTHON digest: %s" % digest
			print "PYTHON Encoded digest: %s" % base64.b64encode(digest)
			cc = ccHandler()
			cc.openSession()
			signed = cc.sign(challenge)
			val = base64.b64encode(digest)+'-'+signed

			resp.append((val,0))
		elif type == PAM.PAM_PROMPT_ERROR_MSG or type == PAM.PAM_PROMPT_TEXT_INFO:
			print query
			resp.append(('', 0))
		else:
			return None

	return resp
Ejemplo n.º 22
0
def rsa_sign(para_str):
    """对请求参数做rsa签名"""
    para_str = para_str.encode('utf-8')
    key = RSA.importKey(settings.ALIPAY_PRIVATE_KEY)
    h = SHA.new(para_str)
    signer = PKCS1_v1_5.new(key)
    return base64.b64encode(signer.sign(h))
Ejemplo n.º 23
0
    def decrypt(self, ciphertext, key, padding="pkcs1_padding"):
        if padding == "pkcs1_padding":
            cipher = PKCS1_v1_5.new(key)
            if self.with_digest:
                dsize = SHA.digest_size
            else:
                dsize = 0
            sentinel = Random.new().read(32+dsize)
            text = cipher.decrypt(ciphertext, sentinel)
            if dsize:
                _digest = text[-dsize:]
                _msg = text[:-dsize]
                digest = SHA.new(_msg).digest()
                if digest == _digest:
                    text = _msg
                else:
                    raise DecryptionFailed()
            else:
                if text == sentinel:
                    raise DecryptionFailed()
        elif padding == "pkcs1_oaep_padding":
            cipher = PKCS1_OAEP.new(key)
            text = cipher.decrypt(ciphertext)
        else:
            raise Exception("Unsupported padding")

        return text
Ejemplo n.º 24
0
def sign_rsa_sha1(base_string, rsa_private_key):
    """**RSA-SHA1**

    Per `section 3.4.3`_ of the spec.

    The "RSA-SHA1" signature method uses the RSASSA-PKCS1-v1_5 signature
    algorithm as defined in `RFC3447, Section 8.2`_ (also known as
    PKCS#1), using SHA-1 as the hash function for EMSA-PKCS1-v1_5.  To
    use this method, the client MUST have established client credentials
    with the server that included its RSA public key (in a manner that is
    beyond the scope of this specification).

    NOTE: this method requires the python-rsa library.

    .. _`section 3.4.3`: http://tools.ietf.org/html/rfc5849#section-3.4.3
    .. _`RFC3447, Section 8.2`: http://tools.ietf.org/html/rfc3447#section-8.2

    """
    # TODO: finish RSA documentation
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA

    key = RSA.importKey(rsa_private_key)
    if isinstance(base_string, unicode_type):
        base_string = base_string.encode("utf-8")
    h = SHA.new(base_string)
    p = PKCS1_v1_5.new(key)
    return binascii.b2a_base64(p.sign(h))[:-1].decode("utf-8")
Ejemplo n.º 25
0
def sign(xml, private, public, cert, sign_element='</s:Security>'):
    '''
    Return xmldsig XML string from xml_string of XML.
    @param xml: str of bytestring xml to sign
    @param private: publicKey Private key
    @param public: publicKey Public key
    @return str: signed XML byte string
    '''
    if isinstance(xml, unicode):
        xml = xml.encode('utf-8', 'xmlcharrefreplace')
    signed_info_xml = _generate_signed_info(xml)

    signer = PKCS1_v1_5.PKCS115_SigScheme(private)
    signature_value = signer.sign(SHA.new(c14n(signed_info_xml)))

    signature_xml = PTN_SIGNATURE_XML % {
        'signed_info_xml': signed_info_xml,
        'signature_value': binascii.b2a_base64(signature_value)[:-1],
        'key_info_xml': _generate_key_info_xml_rsa(public.key.n,
                                                   public.key.e,
                                                   cert)
    }

    position = xml.rfind(sign_element)
    return xml[0:position] + signature_xml + xml[position:]
Ejemplo n.º 26
0
    def _get_build_list_sha1(self):
        sha = SHA.new()
        # add public key and then LF to hash
        pem_ck = self._public_key.exportKey('PEM')
        sha.update(pem_ck)
        sha.update(BuildList.NEWLINE)

        # add title and LF to hash
        sha.update(self._title.encode('utf-8'))
        sha.update(BuildList.NEWLINE)

        # add timestamp and LF to hash
        sha.update(self.timestamp.encode('utf-8'))
        sha.update(BuildList.NEWLINE)

        # add CONTENT_START and LF line to hash
        sha.update((BuildList.CONTENT_START + '\n').encode('utf-8'))

        # add serialized NLHTree to hash, each line terminated by LF
        sha.update(self._tree.__str__().encode('utf-8'))

        # add CONTENT_END and LF line to hash
        sha.update((BuildList.CONTENT_END + '\n').encode('utf-8'))

        # add LF to hash
        sha.update(BuildList.NEWLINE)
        return sha
Ejemplo n.º 27
0
def encrypt(N, e, message, L = ""):
    lHash = SHA.new(L).digest()
    hLen = len(lHash)
    mLen = len(message)
    k = numOctets(N)

    if mLen > k - (2*hLen) - 2:
        print "Message too long"
        return -1

    lPS = (k - mLen - 2*hLen - 2)
    PS = '\x00' * lPS
    DB = ''.join((lHash, PS, '\x01', message))

    seed = I2OSP(utils.gen_random(hLen * 8), hLen)

    dbMask = MGF(seed, k - hLen - 1)
    maskedDB = stringXOR(DB, dbMask)

    seedMask = MGF(maskedDB, hLen)
    maskedSeed = stringXOR(seed, seedMask)

    EM = ''.join(('\x00', maskedSeed, maskedDB))

    m = OS2IP(EM)

    c = RSAEP(N, e, m)

    cipherText = I2OSP(c, k)

    return cipherText
Ejemplo n.º 28
0
	def do_GET(self):
		"""Sends commands b64 encoded in HTTP responses
		"""
		global last_command, output_ready,command_ready,password, salt
		if ((self.client_address[0] == socket.gethostbyname(host)) and command_ready):
			self.send_response(200) # begin sending response
			if encrypt:
				salt = self.headers["Content-Salt"].strip() # extract the salt the client is using
				if verbose: print "received salt from client: "+salt
				hasher = SHA.new() # new hasher
				hasher.update(password + salt) # create the hash of the string passwordsalt
				rc4 = ARC4.new(hasher.hexdigest()) # use the hash for password to avoid weak key scheduling 
				self.end_headers() # end of response headers
				self.wfile.write(base64.b64encode(rc4.encrypt(last_command))) # send payload
			else: 
				# send payload without encryption
				self.end_headers()
				self.wfile.write(base64.b64encode(last_command))
			command_ready=False # wait for next command
			
		else:
			# GET does not come from the client we are currently listening to or there is no command available yet
			self.send_response(200) # send empty response and end
			self.send_header("Content-Type","0") # no command issued
			self.end_headers()
			
		# Check special header to know client current polling period
		if "Next-Polling-In" in self.headers:
			global next_polling,timestamp,client_sync
			next_polling = self.headers["Next-Polling-In"] # so the server can calculate roughly next polling
			# set the time of last request
			timestamp = int(time.time())
			client_sync = True
Ejemplo n.º 29
0
    def parse_response(self, form, success=True):
        """Parse and return payment response."""
        fields = {
            # Successful payment
            '1101': ('SERVICE', 'VERSION', 'SND_ID', 'REC_ID', 'STAMP', #  1..5
                     'T_NO', 'AMOUNT', 'CURR', 'REC_ACC', 'REC_NAME',   #  6..10
                     'SND_ACC', 'SND_NAME', 'REF', 'MSG', 'T_DATE'),    # 11..15
            # Unsuccessful payment
            '1901': ('SERVICE', 'VERSION', 'SND_ID', 'REC_ID', 'STAMP', #  1..5
                     'REF', 'MSG')                                      #  6..7
        }
        # See which response we got
        resp = form.get('VK_SERVICE', None)
        if not resp and resp not in fields:
            raise InvalidResponseError
        success = resp == '1101'

        Random.atfork()

        # Parse and validate MAC
        m = self._build_mac(fields[resp], form)
        f = lambda x: form.get('VK_%s' % x)
        if not PKCS1_v1_5.new(self.keychain.public_key) \
                         .verify(SHA.new(m), b64decode(f('MAC'))):
            raise InvalidResponseError
        # Save payment data
        data = {}
        if success:
            for item in ('T_NO', 'AMOUNT', 'CURR', 'REC_ACC', 'REC_NAME',
                         'SND_ACC', 'SND_NAME', 'REF', 'MSG', 'T_DATE'):
                data[item] = f(item)
        return PaymentResponse(self, data, success)
Ejemplo n.º 30
0
def encrypt_for_master(data):
    # Encrypt the file so it can only be read by the bot master
    h=SHA.new(data)
    key = RSA.importKey(open(os.path.join("pastebot.net", "master_rsa.pub")).read())
    cipher = PKCS1_v1_5.new(key)
    ciphertext = cipher.encrypt(data+h.digest())
    return ciphertext
Ejemplo n.º 31
0
 def fix_size(text):
     crypto = SHA.new()
     crypto.update(text.encode())
     return crypto.hexdigest()
Ejemplo n.º 32
0
 def encrypt(key,massage):
     hasher = SHA.new(massage.encode())
     asym = RSA.importKey(key)
     cipher = PKCS1_v1_5.new(asym)
     return cipher.encrypt(massage.encode()+hasher.digest())
Ejemplo n.º 33
0
def send(amount_input, recipient_input, keep_input, openfield_input):
    try:
        key
    except:
        top5 = Toplevel()
        top5.title("Locked")

        Label(top5, text="Wallet is locked", width=20).grid(row=0, pady=0)

        done = Button(top5, text="Cancel", command=top5.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))

    app_log.warning("Received tx command")

    try:
        float(amount_input)
    except:
        top7 = Toplevel()
        top7.title("Invalid amount")
        Label(top7, text="Amount must be a number", width=20).grid(row=0,
                                                                   pady=0)
        done = Button(top7, text="Cancel", command=top7.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))

    # alias check

    # alias check

    if len(recipient_input) != 56:
        top6 = Toplevel()
        top6.title("Invalid address")
        Label(top6, text="Wrong address length", width=20).grid(row=0, pady=0)
        done = Button(top6, text="Cancel", command=top6.destroy)
        done.grid(row=1, column=0, sticky=W + E, padx=15, pady=(5, 5))
    else:

        app_log.warning("Amount: {}".format(amount_input))
        app_log.warning("Recipient: {}".format(recipient_input))
        app_log.warning("Keep Forever: {}".format(keep_input))
        app_log.warning("OpenField Data: {}".format(openfield_input))

        timestamp = '%.2f' % time.time()
        transaction = (str(timestamp), str(myaddress), str(recipient_input),
                       '%.8f' % float(amount_input), str(keep_input),
                       str(openfield_input))  # this is signed

        h = SHA.new(str(transaction).encode("utf-8"))
        signer = PKCS1_v1_5.new(key)
        signature = signer.sign(h)
        signature_enc = base64.b64encode(signature)
        app_log.warning("Client: Encoded Signature: {}".format(
            signature_enc.decode("utf-8")))

        verifier = PKCS1_v1_5.new(key)
        if verifier.verify(h, signature) == True:
            fee = fee_calculate(openfield_input, keep_var.get())

            if float(amount_input) < 0:
                app_log.warning(
                    "Client: Signature OK, but cannot use negative amounts")

            elif (float(amount_input) + float(fee) > float(balance)):
                app_log.warning("Mempool: Sending more than owned")

            else:
                app_log.warning(
                    "Client: The signature is valid, proceeding to save transaction, signature, new txhash and the public key to mempool"
                )

                # print(str(timestamp), str(address), str(recipient_input), '%.8f' % float(amount_input),str(signature_enc), str(public_key_hashed), str(keep_input), str(openfield_input))
                tx_submit = (str(timestamp), str(myaddress),
                             str(recipient_input),
                             '%.8f' % float(amount_input),
                             str(signature_enc.decode("utf-8")),
                             str(public_key_hashed.decode("utf-8")),
                             str(keep_input), str(openfield_input))

                while True:
                    connections.send(s, "mpinsert", 10)
                    connections.send(
                        s, [tx_submit], 10
                    )  # change address here to view other people's transactions
                    reply = connections.receive(s, 10)
                    app_log.warning("Client: {}".format(reply))
                    break
        else:
            app_log.warning("Client: Invalid signature")
Ejemplo n.º 34
0
def main(argv):
    print "ooooooo"
    print argv
    filePath = argv[0]
    content = read_file_object(filePath)

    if (content.find("//hash =") and content.find("//signature =")):
        strBegin = "//hash ="
        strEnd = "//signature ="
        hashFromFile = splitString(strBegin, strEnd, content)

        strBegin = "//signature ="
        strEnd = "//begin<"
        signatureFromFile = splitString(strBegin, strEnd, content)
        signatureFromFile = signatureFromFile.decode('hex')

    if (content.find("//begin<") and content.find("//>end")):
        strBegin = "//begin<"
        strEnd = "//>end"
        indexBegin = content.find(strBegin, 0)
        indexEnd = content.find(strEnd, 0)
        content = content[indexBegin + len(strBegin):indexEnd]
        hashStr = generate_hash(content)

    if hashStr == hashFromFile:
        print "hash matches"
    else:
        print False

#generate privateKey publicKey
    random_generator = Random.new().read
    rsa = RSA.generate(1024, random_generator)
    privkey = rsa.exportKey()
    print privkey
    print len(privkey)
    with open('master-private.pem', 'w') as f:
        f.write(privkey)

    pubkey = rsa.publickey().exportKey()
    print pubkey
    print len(pubkey)
    with open('master-public.pem', 'w') as f:
        f.write(pubkey)

#Master use the privateKey for signing
    with open('master-private.pem') as f:
        key = f.read()
        rsakey = RSA.importKey(key)
        signer = Signature_pkcs1_v1_5.new(rsakey)
        digest = SHA.new()
        digest.update(content)
        sign = signer.sign(digest)
        signature = base64.b64encode(sign)
        signature = binascii.b2a_hex(signature.encode("utf8"))
        print "----signature hex--"
        print signature
        #a5hK9mUNcAS/Mv/D7hYHAGjuR6oJiv+KQgRHmMDEBE5Dmp4eUEYL6Jyo+JMVkxoHSusdDcFdlSEI2GywW0ym7AtZzP4w0w1z/J52GIMgnCJrnsOaUAhbwDXdfu89qzJGSIc5n0oZmq9qGCVnxoMEenV7ZZYIztMs8llZRNyf8IY=


#Ghost use Master's publicKey for verifying signature
    with open('master-public.pem') as f:
        key = f.read()
        rsakey = RSA.importKey(key)
        verifier = Signature_pkcs1_v1_5.new(rsakey)
        digest = SHA.new()
        digest.update(content)
        is_verify = verifier.verify(digest,
                                    base64.b64decode(signature.decode('hex')))
        print is_verify
    if is_verify:
        print "signature matches"
    else:
        print "signature does not match"
Ejemplo n.º 35
0
key = RSA.importKey(open('privkey.der').read())
public_key = key.publickey()
private_key_readable = str(key.exportKey())
public_key_readable = str(key.publickey().exportKey())
address = hashlib.sha224(public_key_readable.encode("utf-8")).hexdigest()

print("Your address: {}".format(address))
print("Your private key:\n {}".format(private_key_readable))
print("Your public key:\n {}".format(public_key_readable))
public_key_hashed = base64.b64encode(public_key_readable)
# import keys

timestamp = str(time.time())
print("Timestamp: {}".format(timestamp))
transaction = (timestamp, "genesis", address, str(float(100000000)), "genesis")
h = SHA.new(str(transaction))
signer = PKCS1_v1_5.new(key)
signature = signer.sign(h)
signature_enc = base64.b64encode(signature)
print("Encoded Signature: {}".format(signature_enc))
block_hash = hashlib.sha224(str(
    (timestamp,
     transaction)).encode("utf-8")).hexdigest()  # first hash is simplified
print("Transaction Hash: {}".format(block_hash))

if os.path.isfile("static/ledger.db"):
    print("You are beyond genesis")
else:
    # transaction processing
    cursor = None
    mem_cur = None
 def sign_transaction(self):
     private_key = RSA.importKey(binascii.unhexlify(
         self.sender_private_key))
     signer = PKCS1_v1_5.new(private_key)
     hash = SHA.new(str(self.to_dict()).encode('utf8'))
     return binascii.hexlify(signer.sign(hash)).decode('ascii')
Ejemplo n.º 37
0
def update():
    print_debug(("DEBUG: USER_SERVICE: UPDATE: got form", request.form), 9)

    validate_uuid = UUID(request.form['uuid'])
    uuid = str(validate_uuid)
    session = ws.hashlib.sha256(config.SESSION_SECRET + uuid).hexdigest()

    email = request.form['email'] if 'email' in request.form else None
    wallet = request.form['wallet'] if 'wallet' in request.form else None

    secret = request.form['mfasecret'] if 'mfasecret' in request.form else None
    token = request.form['mfatoken'] if 'mfatoken' in request.form else None
    action = request.form['mfaaction'] if 'mfaaction' in request.form else None

    question = unicode(
        str(request.form['question'])[:64],
        errors='replace') if 'question' in request.form else None
    answer = unicode(str(request.form['answer'])[:32],
                     errors='replace') if 'answer' in request.form else None

    location = str(
        request.form['location']) if 'location' in request.form else None
    consent = str(
        request.form['consent']) if 'consent' in request.form else None

    if config.LOCALDEVBYPASSDB:
        session_challenge = session + "_challenge"
        session_pubkey = session + "_public_key"

        if session_challenge not in session_store:
            print_debug(
                ('DEBUG: USER_SERVICE: UPDATE: Challenge not in session'), 8)
            abort(403)

        if session_pubkey not in session_store:
            print_debug(
                ('DEBUG: USER_SERVICE: UPDATE: Public key not in session'), 8)
            abort(403)

        challenge = session_store.get(session_challenge)
        signature = request.form['signature']
        pubkey = session_store.get(session_pubkey)

        key = RSA.importKey(pubkey)
        h = SHA.new(challenge)
        verifier = PKCS1_v1_5.new(key)

        if not verifier.verify(h, signature.decode('hex')):
            print_debug((
                'DEBUG: USER_SERVICE: UPDATE: Challenge signature not verified'
            ), 8)
            abort(403)

        session_store.delete(session_challenge)
    else:
        ROWS = dbSelect(
            "select challenge,pubkey from sessions where sessionid=%s",
            [session])
        if len(ROWS) == 0 or ROWS[0][0] == None:
            print_debug(
                ('DEBUG: USER_SERVICE: UPDATE: Challenge not in session'), 8)
            abort(403)

        if len(ROWS) == 0 or ROWS[0][1] == None:
            print_debug(
                ('DEBUG: USER_SERVICE: UPDATE: Public key not in session'), 8)
            abort(403)

        challenge = ROWS[0][0]
        signature = request.form['signature']
        pubkey = ROWS[0][1]

        key = RSA.importKey(pubkey)
        h = SHA.new(challenge)
        verifier = PKCS1_v1_5.new(key)

        if not verifier.verify(h, signature.decode('hex')):
            print_debug((
                'DEBUG: USER_SERVICE: UPDATE: Challenge signature not verified'
            ), 8)
            print_debug(("DEBUG: USER_SERVICE: UPDATE: uuid is :", uuid), 9)
            print_debug(("DEBUG: USER_SERVICE: UPDATE: pubkey is :",
                         json.dumps(str(pubkey))), 9)
            print_debug(
                ("DEBUG: USER_SERVICE: UPDATE: challenge is: ", challenge), 9)
            print_debug(
                ("DEBUG: USER_SERVICE: UPDATE: signature is: ", signature), 9)

            abort(403)

        dbExecute(
            "update sessions set challenge=NULL, timestamp=DEFAULT where sessionid=%s",
            [session])
        dbCommit()
        print_debug(("DEBUG: USER_SERVICE: UPDATE: completed for uuid", uuid),
                    9)

    ret = False
    if wallet != None:
        if email != None:
            ret = write_wallet(uuid, wallet, email)
        else:
            ret = write_wallet(uuid, wallet)
    elif None not in [location, consent]:
        set_setting(uuid, 'geo', {'consent': consent, 'location': location})
    elif None not in [token, action]:
        ret = update_mfa(uuid, token, action, secret)
        if ret and action == 'add':
            data = {'question': question, 'answer': answer}
            encdata = encrypt_value(json.dumps(data))
            if encdata[0]:
                if not (set_setting(uuid, 'asq', encdata[1])):
                    print_debug(
                        ("DEBUG: USER_SERVICE: UPDATE: Error setting ASQ:",
                         uuid, encdata), 8)
            else:
                print_debug(("DEBUG: USER_SERVICE: UPDATE: Error setting ASQ:",
                             uuid, data, encdata), 8)

    response = {'updated': ret}
    print_debug(("DEBUG: USER_SERVICE: UPDATE: final response:", ret), 9)

    return jsonify(response)
Ejemplo n.º 38
0
def SHA1_ENCRYPT(plaintext):
    h = SHA.new()
    h.update(plaintext)
Ejemplo n.º 39
0
def rsaSign(data, private_key):
    key = RSA.importKey(private_key)
    hash_obj = SHA.new(data)
    signer = PKCS1_v1_5.new(key)
    d = b64encode(signer.sign(hash_obj))
    return d
Ejemplo n.º 40
0
def miner(q, privatekey_readable, public_key_hashed, address):
    from Crypto.PublicKey import RSA
    Random.atfork()
    key = RSA.importKey(privatekey_readable)
    rndfile = Random.new()
    tries = 0
    firstrun = True
    begin = time.time()

    if pool_conf == 1:
        #do not use pools public key to sign, signature will be invalid

        self_address = address
        address = pool_address

        #ask for diff percentage
        s_pool = socks.socksocket()
        s_pool.settimeout(0.3)
        if tor_conf == 1:
            s_pool.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
        s_pool.connect((pool_ip_conf, 8525))  # connect to pool
        print("Connected")

        print("Miner: Asking pool for share qualification difficulty requirement")
        connections.send(s_pool, "diffp", 10)
        pool_diff_percentage = int(connections.receive(s_pool, 10))
        print("Miner: Received pool for share qualification difficulty requirement: {}%".format(pool_diff_percentage))
        s_pool.close()
        #ask for diff percentage

    while True:
        try:

            # calculate new hash
            nonces = 0
            # calculate difficulty
            s_node = socks.socksocket()
            if tor_conf == 1:
                s_node.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
            s_node.connect((node_ip_conf, int(port)))  # connect to local node

            connections.send(s_node, "blocklast", 10)
            blocklast = connections.receive(s_node, 10)
            db_block_hash = blocklast[7]

            connections.send(s_node, "diffget", 10)
            diff = connections.receive(s_node, 10)
            s_node.close()

            diff = int(diff[1])

            diff_real = int(diff)

            if pool_conf == 0:
                diff = int(diff)


            else:  # if pooled
                diff_pool = diff_real
                diff = percentage(pool_diff_percentage, diff_real)

                if diff > diff_pool:
                    diff = diff_pool

            mining_condition = bin_convert(db_block_hash)[0:diff]


            # block_hash = hashlib.sha224(str(block_send) + db_block_hash).hexdigest()


            while tries < diff_recalc_conf:
                start = time.time()

                nonce = hashlib.sha224(rndfile.read(16)).hexdigest()[:32]
                mining_hash = bin_convert(hashlib.sha224((address + nonce + db_block_hash).encode("utf-8")).hexdigest())

                end = time.time()
                if tries % 2500 == 0: #limit output
                    try:
                        cycles_per_second = 1/(end - start)
                        print("Thread{} {} @ {:.2f} cycles/second, difficulty: {}({}), iteration: {}".format(q, db_block_hash[:10], cycles_per_second, diff, diff_real, tries))
                    except:
                        pass
                tries = tries + 1

                if mining_condition in mining_hash:
                    tries = 0

                    print("Thread {} found a good block hash in {} cycles".format(q, tries))

                    # serialize txs

                    block_send = []
                    del block_send[:]  # empty
                    removal_signature = []
                    del removal_signature[:]  # empty

                    s_node = socks.socksocket()
                    if tor_conf == 1:
                        s_node.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
                    s_node.connect((node_ip_conf, int(port)))  # connect to config.txt node
                    connections.send(s_node, "mpget", 10)
                    data = connections.receive(s_node, 10)
                    s_node.close()

                    if data != "[]":
                        mempool = data

                        for mpdata in mempool:
                            transaction = (
                                str(mpdata[0]), str(mpdata[1][:56]), str(mpdata[2][:56]), '%.8f' % float(mpdata[3]), str(mpdata[4]), str(mpdata[5]), str(mpdata[6]),
                                str(mpdata[7]))  # create tuple
                            # print transaction
                            block_send.append(transaction)  # append tuple to list for each run
                            removal_signature.append(str(mpdata[4]))  # for removal after successful mining

                    # claim reward
                    block_timestamp = '%.2f' % time.time()
                    transaction_reward = (str(block_timestamp), str(address[:56]), str(address[:56]), '%.8f' % float(0), "0", str(nonce))  # only this part is signed!
                    # print transaction_reward

                    h = SHA.new(str(transaction_reward).encode("utf-8"))
                    signer = PKCS1_v1_5.new(key)
                    signature = signer.sign(h)
                    signature_enc = base64.b64encode(signature)

                    if signer.verify(h, signature) == True:
                        print("Signature valid")

                        block_send.append((str(block_timestamp), str(address[:56]), str(address[:56]), '%.8f' % float(0), str(signature_enc.decode("utf-8")), str(public_key_hashed), "0", str(nonce)))  # mining reward tx
                        print("Block to send: {}".format(block_send))
                        #  claim reward
                        # include data

                        tries = 0

                        # submit mined block to node

                        if sync_conf == 1:
                            check_uptodate(300)

                        if pool_conf == 1:
                            mining_condition = bin_convert(db_block_hash)[0:diff_real]
                            if mining_condition in mining_hash:
                                print("Miner: Submitting block to all nodes, because it satisfies real difficulty too")
                                nodes_block_submit(block_send)

                            try:
                                s_pool = socks.socksocket()
                                s_pool.settimeout(0.3)
                                if tor_conf == 1:
                                    s_pool.setproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
                                s_pool.connect((pool_ip_conf, 8525))  # connect to pool
                                print("Connected")

                                print("Miner: Proceeding to submit mined block to pool")

                                connections.send(s_pool, "block", 10)
                                connections.send(s_pool, self_address, 10)
                                connections.send(s_pool, block_send, 10)
                                s_pool.close()

                                print("Miner: Block submitted to pool")

                            except Exception as e:
                                print("Miner: Could not submit block to pool")
                                pass

                        if pool_conf == 0:
                            nodes_block_submit(block_send)
                    else:
                        print("Invalid signature")
            tries = 0

        except Exception as e:
            print(e)
            time.sleep(0.1)
            if debug_conf == 1:
                raise
            else:
                pass
Ejemplo n.º 41
0
def challenge_hash(peer_challenge, authenticator_challenge, username):
    challenge = SHA.new(peer_challenge + authenticator_challenge +
                        username).digest()
    return challenge[0:8]
Ejemplo n.º 42
0
# decryption session key
privatekey = RSA.importKey(open('./HybridBob/bobprivatekey.txt', 'rb').read())
cipherrsa = PKCS1_OAEP.new(privatekey)

sessionkey = cipherrsa.decrypt(outputAlice[:ENC_SESSION_KEY_SIZE])
ciphertext = outputAlice[ENC_SESSION_KEY_SIZE:]

iv = ciphertext[:16]
obj = AES.new(sessionkey, AES.MODE_CFB, iv)
plaintext = obj.decrypt(ciphertext[16:])
f = open('./HybridBob/sig_MSG_Bob.txt', 'wb')
f.write(bytes(plaintext))
f.close()

# Step 5 :
# decryption signature
f = open('./HybridBob/sig_MSG_Bob.txt', 'rb')
sig_MSG = f.read()
f.close()

publickey = RSA.importKey(
    open('./HybridBob/received_alicepublickey.txt', 'rb').read())
cipherrsa = PKCS1_v1_5.new(publickey)

print("Signature: ", sig_MSG[:256])
print("PlainText: ", sig_MSG[256:])

myhash = SHA.new(sig_MSG[256:])
result = cipherrsa.verify(myhash, sig_MSG[:256])
print("Signature Verification Result : ", result)
Ejemplo n.º 43
0
 def build_key_table(self):
     self.keyTable = {}
     for addr, port, key in self.peer_list:
         self.keyTable[SHA.new(key).hexdigest()] = key
Ejemplo n.º 44
0
	def sign_transaction(self):
		private_key = self.sender._private_key
		signer = PKCS1_v1_5.new(private_key)
		h = SHA.new(str(self.to_dict)).encode('utf8')
		return binascii.hexlify(signer.sign(h)).decode('ascii')
Ejemplo n.º 45
0
def sign_with_privkey(privkey_pem, message):
    privkey = RSA.importKey(privkey_pem)
    h = SHA.new()
    h.update(message)
    signer = PKCS1_PSS.new(privkey)
    return b64encode(signer.sign(h))
Ejemplo n.º 46
0
query = """
        select nonce
        from waiting
        where waitingId = %s;"""

#Get the supposedly signed nonce, based on "request" identifier
cursor.execute(query, (waitingId))
result = cursor.fetchone()

#Retain a Base-64 and binary signature
sigB64 = sig
sigAscii = base64.b64decode(sig, "-_")

#Hash the nonce for this login attempt
h = SHA.new()
h.update(str(result[0]))

#Import the RSA key from the provided SPKI
key = RSA.importKey(base64.b64decode(spki, "-_"))

#Verifier object to verify the signature and hash
verifier = PKCS1_v1_5.new(key)

if (verifier.verify(h, sigAscii)):
    print "Content-type:text/html\r\n\r\n"
    print "<html>authenticated.py</html>"
else:
    print "Content-type:text/html\r\n\r\n"
    print "<html>forbidden.py</html>"
Ejemplo n.º 47
0
    def create_auth_key(self):
        rand_nonce = os.urandom(16)
        req_pq = rpc.req_pq(rand_nonce).get_bytes()
        self.send_message(req_pq)
        resPQ = rpc.resPQ(self.recv_message())
        assert rand_nonce == resPQ.nonce

        public_key_fingerprint = resPQ.server_public_key_fingerprints[0]
        pq = bytes_to_long(resPQ.pq)

        [p, q] = prime.primefactors(pq)
        (p, q) = (q, p) if p > q else (p, q)
        assert p * q == pq and p < q

        print("Factorization %d = %d * %d" % (pq, p, q))

        p_bytes = long_to_bytes(p)
        q_bytes = long_to_bytes(q)
        key = RSA.importKey(self.rsa_key)
        new_nonce = os.urandom(32)

        p_q_inner_data = rpc.p_q_inner_data(pq=resPQ.pq,
                                            p=p_bytes,
                                            q=q_bytes,
                                            server_nonce=resPQ.server_nonce,
                                            nonce=resPQ.nonce,
                                            new_nonce=new_nonce)

        data = p_q_inner_data.get_bytes()
        assert p_q_inner_data.nonce == resPQ.nonce

        sha_digest = SHA.new(data).digest()
        random_bytes = os.urandom(255 - len(data) - len(sha_digest))
        to_encrypt = sha_digest + data + random_bytes
        encrypted_data = key.encrypt(to_encrypt, 0)[0]

        req_DH_params = rpc.req_DH_params(
            p=p_bytes,
            q=q_bytes,
            nonce=resPQ.nonce,
            server_nonce=resPQ.server_nonce,
            public_key_fingerprint=public_key_fingerprint,
            encrypted_data=encrypted_data)
        data = req_DH_params.get_bytes()

        self.send_message(data)
        data = self.recv_message(debug=False)

        server_DH_params = rpc.server_DH_params(data)
        assert resPQ.nonce == server_DH_params.nonce
        assert resPQ.server_nonce == server_DH_params.server_nonce

        encrypted_answer = server_DH_params.encrypted_answer

        tmp_aes_key = SHA.new(new_nonce + resPQ.server_nonce).digest(
        ) + SHA.new(resPQ.server_nonce + new_nonce).digest()[0:12]
        tmp_aes_iv = SHA.new(resPQ.server_nonce + new_nonce).digest(
        )[12:20] + SHA.new(new_nonce + new_nonce).digest() + new_nonce[0:4]

        answer_with_hash = crypt.ige_decrypt(encrypted_answer, tmp_aes_key,
                                             tmp_aes_iv)

        answer_hash = answer_with_hash[:20]
        answer = answer_with_hash[20:]

        server_DH_inner_data = rpc.server_DH_inner_data(answer)
        assert resPQ.nonce == server_DH_inner_data.nonce
        assert resPQ.server_nonce == server_DH_inner_data.server_nonce

        dh_prime_str = server_DH_inner_data.dh_prime
        g = server_DH_inner_data.g
        g_a_str = server_DH_inner_data.g_a
        server_time = server_DH_inner_data.server_time
        self.timedelta = server_time - time()

        dh_prime = bytes_to_long(dh_prime_str)
        g_a = bytes_to_long(g_a_str)

        assert prime.isprime(dh_prime)
        retry_id = 0
        b_str = os.urandom(256)
        b = bytes_to_long(b_str)
        g_b = pow(g, b, dh_prime)

        g_b_str = long_to_bytes(g_b)

        client_DH_inner_data = rpc.client_DH_inner_data(
            nonce=resPQ.nonce,
            server_nonce=resPQ.server_nonce,
            retry_id=retry_id,
            g_b=g_b_str)

        data = client_DH_inner_data.get_bytes()

        data_with_sha = SHA.new(data).digest() + data
        data_with_sha_padded = data_with_sha + os.urandom(
            -len(data_with_sha) % 16)
        encrypted_data = crypt.ige_encrypt(data_with_sha_padded, tmp_aes_key,
                                           tmp_aes_iv)

        for i in range(
                1,
                self.AUTH_MAX_RETRY):  # retry when dh_gen_retry or dh_gen_fail
            set_client_DH_params = rpc.set_client_DH_params(
                nonce=resPQ.nonce,
                server_nonce=resPQ.server_nonce,
                encrypted_data=encrypted_data)
            self.send_message(set_client_DH_params.get_bytes())
            Set_client_DH_params_answer = rpc.set_client_DH_params_answer(
                self.recv_message())

            # print Set_client_DH_params_answer
            auth_key = pow(g_a, b, dh_prime)
            auth_key_str = long_to_bytes(auth_key)
            auth_key_sha = SHA.new(auth_key_str).digest()
            auth_key_aux_hash = auth_key_sha[:8]

            new_nonce_hash1 = SHA.new(new_nonce + b'\x01' +
                                      auth_key_aux_hash).digest()[-16:]
            new_nonce_hash2 = SHA.new(new_nonce + b'\x02' +
                                      auth_key_aux_hash).digest()[-16:]
            new_nonce_hash3 = SHA.new(new_nonce + b'\x03' +
                                      auth_key_aux_hash).digest()[-16:]

            assert Set_client_DH_params_answer.nonce == resPQ.nonce
            assert Set_client_DH_params_answer.server_nonce == resPQ.server_nonce

            if Set_client_DH_params_answer.status == 'ok':
                assert Set_client_DH_params_answer.new_nonce_hash == new_nonce_hash1
                print("Diffie Hellman key exchange processed successfully")

                self.server_salt = strxor(new_nonce[0:8],
                                          resPQ.server_nonce[0:8])
                self.auth_key = auth_key_str
                self.auth_key_id = auth_key_sha[-8:]
                print("Auth key generated")
                return "Auth Ok"
            elif Set_client_DH_params_answer.status == 'retry':
                assert Set_client_DH_params_answer.new_nonce_hash == new_nonce_hash2
                print("Retry Auth")
            elif Set_client_DH_params_answer.status == 'fail':
                assert Set_client_DH_params_answer.new_nonce_hash == new_nonce_hash3
                print("Auth Failed")
                raise Exception("Auth Failed")
            else:
                raise Exception("Response Error")
Ejemplo n.º 48
0
def digest(algorithm=_DEFAULT_HASH_ALGORITHM,
           hash_library=_DEFAULT_HASH_LIBRARY):
    """
  <Purpose>
    Provide the caller with the ability to create
    digest objects without having to worry about hash
    library availability or which library to use.  
    The caller also has the option of specifying which
    hash algorithm and/or library to use.

    # Creation of a digest object using defaults
    # or by specifying hash algorithm and library.
    digest_object = ssl_crypto.hash.digest()
    digest_object = ssl_crypto.hash.digest('sha384')
    digest_object = ssl_crypto.hash.digest('pycrypto')

    # The expected interface for digest objects. 
    digest_object.digest_size
    digest_object.hexdigest()
    digest_object.update('data')
    digest_object.digest()
    
    # Added hash routines by this module.
    digest_object = ssl_crypto.hash.digest_fileobject(file_object)
    digest_object = ssl_crypto.hash.digest_filename(filename)
  
  <Arguments>
    algorithm:
      The hash algorithm (e.g., md5, sha1, sha256).

    hash_library:
      The library providing the hash algorithms 
      (e.g., pycrypto, hashlib).
      
  <Exceptions>
    ssl_crypto.UnsupportedAlgorithmError
    ssl_crypto.UnsupportedLibraryError

  <Side Effects>
    None.

  <Returns>
    Digest object (e.g., hashlib.new(algorithm) or 
    algorithm.new() # pycrypto).
  """

    # Was a hashlib digest object requested and is it supported?
    # If so, return the digest object.
    if hash_library == 'hashlib' and hash_library in _supported_libraries:
        try:
            return hashlib.new(algorithm)

        except ValueError:
            raise ssl_crypto.UnsupportedAlgorithmError(algorithm)

    # Was a pycrypto digest object requested and is it supported?
    elif hash_library == 'pycrypto' and hash_library in _supported_libraries:
        # Pycrypto does not offer a comparable hashlib.new(hashname).
        # Let's first check the 'algorithm' argument before returning
        # the correct pycrypto digest object using pycrypto's object construction.
        if algorithm == 'md5':
            return MD5.new()
        elif algorithm == 'sha1':
            return SHA.new()
        elif algorithm == 'sha224':
            return SHA224.new()
        elif algorithm == 'sha256':
            return SHA256.new()
        elif algorithm == 'sha384':
            return SHA384.new()
        elif algorithm == 'sha512':
            return SHA512.new()
        else:
            raise ssl_crypto.UnsupportedAlgorithmError(algorithm)

    # The requested hash library is not supported.
    else:
        raise ssl_crypto.UnsupportedLibraryError(
            'Unsupported library requested.  '
            'Supported hash libraries: ' + str(_SUPPORTED_LIB_LIST))
Ejemplo n.º 49
0
def auth_receive(request):
    if request.GET.has_key('s') and request.GET['s'] == "logout":
        # This was a logout request
        return HttpResponseRedirect('/')

    if not request.GET.has_key('i'):
        return HttpResponse("Missing IV in url!", status=400)
    if not request.GET.has_key('d'):
        return HttpResponse("Missing data in url!", status=400)

    # Set up an AES object and decrypt the data we received
    decryptor = AES.new(base64.b64decode(settings.PGAUTH_KEY), AES.MODE_CBC,
                        base64.b64decode(str(request.GET['i']), "-_"))
    s = decryptor.decrypt(base64.b64decode(str(request.GET['d']),
                                           "-_")).rstrip(' ')

    # Now un-urlencode it
    try:
        data = urlparse.parse_qs(s, strict_parsing=True)
    except ValueError:
        return HttpResponse("Invalid encrypted data received.", status=400)

    # Check the timestamp in the authentication
    if (int(data['t'][0]) < time.time() - 10):
        return HttpResponse("Authentication token too old.", status=400)

    # Update the user record (if any)
    try:
        user = User.objects.get(username=data['u'][0])
        # User found, let's see if any important fields have changed
        changed = False
        if user.first_name != data['f'][0]:
            user.first_name = data['f'][0]
            changed = True
        if user.last_name != data['l'][0]:
            user.last_name = data['l'][0]
            changed = True
        if user.email != data['e'][0]:
            user.email = data['e'][0]
            changed = True
        if changed:
            user.save()
    except User.DoesNotExist:
        # User not found, create it!

        # NOTE! We have some legacy users where there is a user in
        # the database with a different userid. Instead of trying to
        # somehow fix that live, give a proper error message and
        # have somebody look at it manually.
        if User.objects.filter(email=data['e'][0]).exists():
            return HttpResponse(
                """A user with email %s already exists, but with
a different username than %s.

This is almost certainly caused by some legacy data in our database.
Please send an email to [email protected], indicating the username
and email address from above, and we'll manually merge the two accounts
for you.

We apologize for the inconvenience.
""" % (data['e'][0], data['u'][0]),
                content_type='text/plain')

        user = User(
            username=data['u'][0],
            first_name=data['f'][0],
            last_name=data['l'][0],
            email=data['e'][0],
            password='******',
        )
        user.save()

    # Ok, we have a proper user record. Now tell django that
    # we're authenticated so it persists it in the session. Before
    # we do that, we have to annotate it with the backend information.
    user.backend = "%s.%s" % (AuthBackend.__module__, AuthBackend.__name__)
    django_login(request, user)

    # Finally, check of we have a data package that tells us where to
    # redirect the user.
    if data.has_key('d'):
        (ivs, datas) = data['d'][0].split('$')
        decryptor = AES.new(
            SHA.new(settings.SECRET_KEY).digest()[:16], AES.MODE_CBC,
            base64.b64decode(ivs, "-_"))
        s = decryptor.decrypt(base64.b64decode(datas, "-_")).rstrip(' ')
        try:
            rdata = urlparse.parse_qs(s, strict_parsing=True)
        except ValueError:
            return HttpResponse("Invalid encrypted data received.", status=400)
        if rdata.has_key('r'):
            # Redirect address
            return HttpResponseRedirect(rdata['r'][0])
    # No redirect specified, see if we have it in our settings
    if hasattr(settings, 'PGAUTH_REDIRECT_SUCCESS'):
        return HttpResponseRedirect(settings.PGAUTH_REDIRECT_SUCCESS)
    return HttpResponse(
        "Authentication successful, but don't know where to redirect!",
        status=500)
Ejemplo n.º 50
0
        "460bbb99bc66cae942e33c5a92064995c93cc6a0b4bfc17442516ed3",
        "c4b0121f213469764ac653ac29f670448fefef8e5cddbe164c534922",
        "4be74c848a16316e9c8dabd390996588af6ca027547ffecb4495aeee"
    ]
    to_address = random.choice(to_address_list)
    amount = random.uniform(0.01, 0.1)
    print to_address
    print amount

    timestamp = str(time.time())

    transaction = str(timestamp) + ":" + str(address) + ":" + str(
        to_address) + ":" + str(float(amount))
    print transaction

    h = SHA.new(transaction)
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(h)
    signature_enc = base64.b64encode(signature)
    print("Client: Encoded Signature: " + str(signature_enc))

    print(
        "Client: The signature is valid, proceeding to send transaction, signature, new txhash and the public key"
    )
    s.sendall("transaction")
    time.sleep(0.1)
    transaction_send = (transaction + ";" + str(signature_enc) + ";" +
                        public_key_readable)

    #announce length
    txhash_len = len(str(transaction_send))
Ejemplo n.º 51
0
def sign_file(f , rsaKey):
    h = SHA.new()
    h.update(f)
    signer = PKCS1_PSS.new(rsaKey)
    signature = signer.sign(h)
    return signature + f
Ejemplo n.º 52
0
def sign_transaction(transaction, key):
    h = SHA.new(str(transaction))
    signer = PKCS.new(key)
    signature = signer.sign(h)
    encoded_signature = b64encode(signature)
    return signature, encoded_signature
Ejemplo n.º 53
0
def main():
    '''
    Main method. Loops forever until killed
    '''
    args = get_args()
    port = args.port
    ip = args.ip

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.setblocking(0)
    server.bind((ip, port))
    server.listen(5)

    inputs = [server]
    outputs = []
    msg_queues = {}
    n_users = 0
    user_connect_time = {}

    #Dictionaries containing buffered messages and message state variable
    #Key for each is a socket object
    msg_buffers = {}
    recv_len = {}
    msg_len = {}
    usernames = {}
    unverified_usernames = {}
    symmetric_keys = {}
    ciphers = {}

    while inputs:

        #if 60 seconds are up no username yet, disconnect the client
        users = list(user_connect_time)
        for s in users:
            if (time.time() - user_connect_time[s]) > TIMEOUT:

                LNP.send(s, '', "EXIT")

                inputs.remove(s)
                outputs.remove(s)
                n_users -= 1
                del user_connect_time[s]

        readable, writable, exceptional = select.select(
            inputs, outputs, inputs)

        for s in readable:

            ###
            ### Processing server connection requests
            ###
            if s is server:

                connection, client_addr = s.accept()
                connection.setblocking(0)

                if n_users < MAX_USR:

                    #ciphers[s] = None

                    public_key = ''
                    with open('rsa_public.pem', 'r') as public_key_file:
                        public_key = public_key_file.read()
                        public_key.replace("\n", "").replace("\r", "")
                    LNP.send(connection, public_key)  # send public key

                    time.sleep(.005)

                    LNP.send(connection, '', "ACCEPT")

                    #set up connnection variables
                    inputs.append(connection)
                    outputs.append(connection)
                    n_users += 1
                    user_connect_time[connection] = time.time()

                    if args.debug:
                        print("        SERVER: new connection from " +
                              str(client_addr))

                else:  #>100 users
                    LNP.send(connection, '', "FULL")
                    connection.close()

                    if args.debug:
                        print("        SERVER: connection from " +
                              str(client_addr) + " refused, server full")

###
### Processing client msgs
###
            else:

                msg_status = None
                if s in ciphers:
                    msg_status = LNP.recv(s, msg_buffers, recv_len, msg_len,
                                          ciphers[s])
                else:
                    msg_status = LNP.recv(s, msg_buffers, recv_len, msg_len,
                                          None)

                if msg_status == "MSG_CMPLT":

                    msg = LNP.get_msg_from_queue(s, msg_buffers, recv_len,
                                                 msg_len)

                    if args.debug:
                        print("        receieved " + str(msg) + " from " +
                              str(s.getpeername()))

                    if s not in symmetric_keys:
                        # decode symmetric key using server private key
                        enc_session_key = base64.b64decode(msg.encode())

                        private_key = RSA.import_key(
                            open("rsa_private.pem").read())
                        cipher_rsa = PKCS1_OAEP.new(private_key)
                        symmetric_key = cipher_rsa.decrypt(enc_session_key)
                        symmetric_keys[s] = symmetric_key

                        # make cipher and store it
                        tempkey = SHA.new(symmetric_key).digest()
                        cipher_server = ARC4.new(tempkey)
                        ciphers[s] = cipher_server

#Username exists for this client, this is a message
                    elif s in usernames:
                        pvt_user = is_private(msg, usernames)
                        msg = "> " + usernames[s] + ": " + msg
                        if pvt_user:
                            private_queue(msg, msg_queues, pvt_user, usernames)
                        else:
                            broadcast_queue(msg, msg_queues, exclude=[s])

                    elif s not in unverified_usernames:
                        unverified_usernames[s] = msg
                        LNP.send(s, '', "NEED-CERTIFICATE")

#no username yet, this message is a username
                    else:
                        username_status = is_username(unverified_usernames[s],
                                                      usernames, msg)

                        LNP.send(s, '', username_status)

                        if username_status == "USERNAME-ACCEPT":
                            usernames[s] = unverified_usernames[s]
                            del user_connect_time[s]
                            msg_queues[s] = queue.Queue()
                            msg = "User " + usernames[s] + " has joined"
                            print("        SERVER: " + msg)
                            broadcast_queue(msg, msg_queues)

                        else:  #invalid username
                            user_connect_time[s] = time.time()
                            msg = None
                            del unverified_usernames[s]

###
### Closing connection with client
###
                elif msg_status == "NO_MSG" or msg_status == "EXIT":

                    # if args.debug:
                    #     print("        SERVER: " + msg_status +
                    #           ": closing connection with " + str(s.getpeername()))

                    outputs.remove(s)
                    inputs.remove(s)
                    if s in writable:
                        writable.remove(s)
                    if s in msg_queues:
                        del msg_queues[s]

#load disconnect message into msg_queues
                    if s in usernames:
                        for sock in msg_queues:
                            msg_queues[sock].put("User " + usernames[s] +
                                                 " has left")
                        del usernames[s]

                    if s in user_connect_time:
                        del user_connect_time[s]

#If user sent disconnect message need to send one back
                    if msg_status == "EXIT":
                        LNP.send(s, '', "EXIT")

                    n_users -= 1
                    s.close()

        #Send messages to clients
        for s in writable:

            if s in msg_queues:

                try:
                    next_msg = msg_queues[s].get_nowait()

                except queue.Empty:
                    next_msg = None

                if next_msg:
                    if args.debug:
                        print("        sending " + next_msg + " to " +
                              str(s.getpeername()))
                    LNP.send(s, next_msg, None, ciphers[s])

        #Remove exceptional sockets from the server
        for s in exceptional:

            if args.debug:
                print("        SERVER: handling exceptional condition for " +
                      str(s.getpeername()))

            inputs.remove(s)
            #if s in outputs:
            outputs.remove(s)
            del msg_queues[s]
            del usernames[s]
            s.close()
Ejemplo n.º 54
0
# Data to encode -- input from the user
m = input("Write a 18-byte message:\n")

# Pad the message
if (len(m) <= 18):
    for i in range(len(m), 32):
        m += " "
elif (len(m) > 18):
    m = m[:18]
    for i in range(len(m), 32):
        m += " "

# Convert input to byte data type
data = bytes(m, 'utf-8')

# Use private key to get the signature
h = SHA.new(data)
signer = PKCS1_v1_5.new(private_key)
signature = signer.sign(h)

print("RSA signature: ", signature)

# Write message and signature to file
sigtext = data + signature
f = open("sigtext", "wb+")
f.write(sigtext)
f.close()

print("\nAlice is done.")
Ejemplo n.º 55
0
def sign(data):
    key = RSA.importKey(priKey)
    h = SHA.new(data)
    signer = PKCS1_v1_5.new(key)
    signature = signer.sign(h)
    return base64.b64encode(signature)
Ejemplo n.º 56
0
waitingId = form.getvalue(
    "waitingId")  #The "request" identifier for this connection

query = """
        select nonce, signature
        from waiting
        where waitingId = %s;"""

db = MySQLdb.connect(myHost, myUser, myPasswd, myDb)
cursor = db.cursor()

#Get the supposedly signed nonce, based on "request" identifier
cursor.execute(query, (waitingId))
result = cursor.fetchone()
myNonce = result[0]
myHash = SHA.new()
myHash.update(str(result[0]))
myHash = myHash.hexdigest()
mySignature = result[1]

print "Content-type:text/html\r\n\r\n"
template_vals = {}
template_vals.update({"myNonce": myNonce})
template_vals.update({"myHash": myHash})
template_vals.update({"mySignature": mySignature})

template = jinja_environment.get_template("forbidden.html")
print template.render(template_vals)

#Cleanup
db.close()
Ejemplo n.º 57
0
def ras_sign_string(private_key, sign_string):
    key = RSA.importKey(private_key)
    singer = PKCS1_v1_5.new(key)
    signature = singer.sign(SHA.new(sign_string.encode('utf8')))
    sign = base64.encodestring(signature).encode("utf8").replace("\n", "")
    return sign
Ejemplo n.º 58
0
def getSHA1(MSG):
    h = SHA.new()
    h.update(MSG)
    return h.hexdigest()
Ejemplo n.º 59
0
def rsaVerify(data, public_key, sign):
    rsakey = RSA.importKey(public_key)
    res = SHA.new(data)
    verifier = PKCS1_v1_5.new(rsakey)
    return verifier.verify(res, b64decode(sign))
Ejemplo n.º 60
0
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )

    pubKey = RSA.importKey(pem)
    sessionCipherKey = PKCS1_OAEP.new(pubKey)

    print('Sending cipher key: {}'.format(str(sessionCipherKey)))
    # Send encrypted session key
    s.send("sessionCipherKey=" + str(sessionCipherKey))
    # Should recieve acknowledgment if server is using session cipher key
    acknowledgment = s.recv(1024).decode()

    #Encrypt message and send to server
    message = b'This is my secret message.'
    h = SHA.new(message)
    encrypted = sessionCipherKey.encrypt(message)

    print('Sending encrypted message: {}'.format(str(encrypted)))

    s.send("encrypted_message=" + encrypted)

    #Server's response
    response = s.recv(1024).decode()
    if(response == "Server: OK"):
        print("Server decrypted message successfully")
    #Tell server to finish connection
    s.send("Quit".encode())

else:
    # Will send 'Goodbye' since certificate is not valid