Ejemplo n.º 1
0
def test_full_encrypt():
    priv1 = crypto.generate_rsa_key()
    priv2 = crypto.generate_rsa_key()
    target_pubkey = crypto.serialize_pubkey(priv2.public_key())
    message = "Santa is not real."

    aes_ciphertext, encry_aes_key, hmac, hmac_signature, iv, metadata = \
        crypto.encrypt(message, priv1, target_pubkey)

    aes_key = crypto.rsa_decrypt(encry_aes_key, priv2)

    assert crypto.aes_decrypt(aes_ciphertext, aes_key, iv) == message

    assert message == \
        crypto.decrypt(
                aes_ciphertext, encry_aes_key, hmac, hmac_signature,
                priv2, iv, metadata
            )
Ejemplo n.º 2
0
def decrypt_root_key(encrypted_key, salt, passphrase, hash_function):
    """
    decrypt_root_key(encrypted_key, salt, passphrase, hash_function).
    encrypted_key is a 16/32/64 byte string
    salt is prefix+date+entropy
    passphrase should be a byte string (utf-8)
    hash_function should be a function that takes a key, a salt, and a length L and outputs an L byte string.
    The returned value is the unencrypted key as a string.
    """
    preH = crypto.pbkdf2(salt, passphrase, 10000, 64)
    strongH = hash_function(preH[0:32], preH[0:32], 64)
    H = crypto.pbkdf2(preH, strongH, 1, len(encrypted_key) + 32)

    encryption_key = H[-32:] # Use the last 32 bytes of H as a key
    decrypted_key = crypto.aes_decrypt(encrypted_key, encryption_key) # The key, of length n, is still xored with the first n bits of H

    unwhitened_root_key = crypto.string_xor(decrypted_key, H[0:-32])

    return unwhitened_root_key
Ejemplo n.º 3
0
def login_as_user(demo, d_uname, d_password, d_features):
    """
	:return: 1 if login was successful, 0 otherwise

	the login function calls all the functions necessary to complete a login. this includes:
	* performing sanity checks if a user even exists
	* reading the password from the user input
	* recreate the polynomial points from the instruction table
	* interpolate the polynomial using the points
	* decrypt the history file and check against a known plain text
	* update the history file accordingly and basically perform all the initial steps
	"""

    everything_fine = True

    if not os.path.exists('users'):
        print("Sorry, no accounts available. Please sign up first.")
        return False

    user_names = os.listdir('users')

    if not user_names:
        print("Sorry, no accounts available. Please sign up first.")
        return False

    if demo:
        user_name = d_uname
    else:
        user_name = input("Enter name: ")

    if user_name not in user_names:
        print("Sorry, no such account.")
        return False

    else:
        r = int(file_ops.read("users/" + user_name + "/r", "r"))
        if not r:
            print("\nNo r file available.")
            return False

        q = int(file_ops.read("users/" + user_name + "/q", "r"))
        if not q:
            print("\nNo q file available.")
            return False

        instruction_table = file_ops.read(
            "users/" + user_name + "/instructions", "r")
        if not instruction_table:
            print("\nNo instruction table file available.")
            return False

        instructions = []
        instruction_table = instruction_table.split("\n")

        for i in instruction_table:
            instructions.append(i.split(" "))

        if demo:
            password = d_password
            features = d_features
            print("Features of current login: "******"Enter password: "******"No password entered.")
                return False

            features = list(map(int, (user_input[0].split(" "))))
            print("Features of current login: "******"Password length does not match instruction table!")
            return False

        feature_below_t = list(
            map(lambda feature: feature < parameters.t, features))
        points = []

        for i in range(1, len(features) + 1):
            if list(feature_below_t)[i - 1]:
                alpha = int(instructions[0][i - 1])
                x_i = 2 * i
                y_i = alpha - (crypto.get_prf(password, str(r), 2 * i) % q)
                points.append((x_i, y_i))
            #elif i <= m:
            else:
                beta = int(instructions[1][i - 1])
                x_i = 2 * i + 1
                y_i = beta - (crypto.get_prf(password, str(r), 2 * i + 1) % q)
                points.append((x_i, y_i))

        print("Points: " + str(points))

        hardened_password = misc.lagrange_interpolation(points)(0)
        print("\nThe reconstructed hpwd is: ", hardened_password)
        print("\nTrying to decrypt history file with hpwd...")

        nonce, tag, cipher_text = file_ops.read(
            "users/" + user_name + "/history", "rb")
        if not nonce or not tag or not cipher_text:
            print("\nNo history file available.")
            return False

        decrypted = crypto.aes_decrypt(
            cipher_text, nonce, tag,
            crypto.get_aes_key(hardened_password).digest())

        if decrypted is None:
            print("\nLogin failed due to wrong password or typing pattern.")
            print("\nHpwd was not recovered correctly!")
            print('           ."`".')
            print("       .-./ _=_ \.-.")
            print("      {  (,(oYo),) }}")
            print('      {{ |   "   |} }')
            print("      { { \(---)/  }}")
            print("      {{  }'-=-'{ } }")
            print("      { { }._:_.{  }}")
            print("      {{  } -:- { } }")
            print("      {_{ }`===`{  _}")
            print("     ((((\)     (/))))")
            print("\nYou won't get in here >:D")

            return False
        """ create new polynomial such that c[0] = hpwd """
        polynomial = misc.generate_polynomial(q, m)

        print(
            "\nHpwd was recovered correctly, since the history was decrypted successfully!"
        )
        """ update history file """
        updated_history = history.update_history(decrypted, features)

        print("Updated history file: ")
        print(updated_history)
        os.remove("users/" + user_name + "/history")

        if not file_ops.write(
                "users/" + user_name + "/history",
                crypto.aes_encrypt(
                    str(history.assemble_history(updated_history)),
                    crypto.get_aes_key(polynomial[0]).digest()), "wb"):
            print(parameters.error_msg)
            return False
        """ update r """
        os.remove("users/" + user_name + "/r")
        new_r = misc.generate_r(user_name)
        """ update instruction table """
        instruction_table = inttable.update_instruction_table(
            polynomial, m, password, new_r, updated_history, q)
        print("\nInstruction table:\n" + str(instruction_table))

        os.remove("users/" + user_name + "/instructions")
        if not file_ops.write("users/" + user_name + "/instructions",
                              instruction_table, "w"):
            print(parameters.error_msg)
            return False

        return True
    def requestHandler(self, server_socket, address):
        # Receive query & search parameters from the client
        client_query_object = receive_object(server_socket)

        # Info
        print "Received request for: " + client_query_object.query_string

        # Start timer
        start_time = time()

        query = client_query_object.query_string
        top_k = client_query_object.top_k

        # Prepare the hashed query
        time_1 = time()
        stemmed_query = stem_text(query)
        query_terms = list(set(stemmed_query.split()))
        hashed_query_terms = [sha256(self.salt.encode() + query.encode()).hexdigest() for query in query_terms]
        time_2 = time()
        print "Query hashing: " + "{0:.4f}".format(time_2 - time_1)

        # Ranked result will be stored here
        sort_index = dict()

        time_1 = time()
        # Main logic for fetching ranked result from encrypted index goes here
        for keyword in hashed_query_terms:
            if keyword in self.index:
                keyword_search_index = self.index[keyword]
                for filename, value in keyword_search_index.iteritems():
                    # AES decrypt now
                    filename = aes_decrypt(filename, self.aes_key)

                    if filename in sort_index:
                        sort_index[filename] = e_add(self.paillier_keys[1], sort_index[filename], value)
                    else:
                        sort_index[filename] = value
        time_2 = time()
        print "Search & Paillier add: " + "{0:.4f}".format(time_2 - time_1)

        time_1 = time()
        # Decrypt the sort index
        for filename, value in sort_index.iteritems():
            sort_index[filename] = decrypt(self.paillier_keys[0], self.paillier_keys[1], value)

        # Sort the final sort_index
        ranked_result = sorted(sort_index.items(), key=operator.itemgetter(1), reverse=True)
        ranked_result = [result[0] for result in ranked_result]
        time_2 = time()
        print "Decrypt & Sort: " + "{0:.4f}".format(time_2 - time_1)

        # Get top-k results
        if top_k == 0:
            if len(ranked_result) > 170:
                ranked_result = ranked_result[:170]
        else:
            ranked_result = ranked_result[:top_k]

        # Note end time
        end_time = time()

        # Create response to client
        response = Server_Response(float("{0:.4f}".format(end_time - start_time)), ranked_result)

        # Send response back to the client
        send_object(server_socket, response)

        # Close socket
        server_socket.close()
Ejemplo n.º 5
0
def test_aes_encrypt_decrypt():
    priv = crypto.create_aes_key()
    message = "Sell Watermelons"
    ciphertext, iv = crypto.aes_encrypt(message, priv)
    assert crypto.aes_decrypt(ciphertext, priv, iv) == message
        while True:
            query = raw_input("Search: ")
            stemmed_query = stem_text(query)
            query_terms = list(set(stemmed_query.split()))
            hashed_query_terms = [
                hashpw(query.encode('utf-8'), bcryt_salt)
                for query in query_terms
            ]
            sort_index = dict()

            for keyword in hashed_query_terms:
                if keyword in index:
                    keyword_search_index = index[keyword]
                    for filename, value in keyword_search_index.iteritems():
                        # AES decrypt now
                        filename = aes_decrypt(filename, aes_key)

                        if filename in sort_index:
                            sort_index[filename] = e_add(
                                public_key, sort_index[filename], value)
                        else:
                            sort_index[filename] = value

            # Decrypt the sort index
            for filename, value in sort_index.iteritems():
                sort_index[filename] = decrypt(private_key, public_key, value)
            # Sort the final sort_index
            ranked_result = sorted(sort_index.items(),
                                   key=operator.itemgetter(1),
                                   reverse=True)
            # Print for now