def update(form) :
	if User.session.exists() :
		user = User.session.get()
		un, un_repeat = form.get("username"), form.get("username-repeat")
		pw, pw_repeat = form.get("password"), form.get("password-repeat")
		if un != un_repeat :
			flash(u"Bitte wiederhole den neuen Benutzernamen korrekt!", Config.Flash.error)
		elif pw != pw_repeat :
			flash(u"Bitte wiederhole das neue Passwort korrekt!", Config.Flash.error)
		elif not (un or pw) :
			flash(u"Keine Änderungen eingegeben.", Config.Flash.warn)
		else :
			user.update(username = un, password = Hash.hash(pw))
			User.session.set(user)
			flash(u"Die neuen Eingaben wurden erfolgreich übernommen.", Config.Flash.success)
	return redirect(Config.Urls.App.user)
class Bob:
    def __init__(self, messages, file_path):
        """ PSI receiver side implementation. \
            Gets as input public_key and ciphertexts files located at file_path/to_bob"""
        if type(messages) != np.ndarray:
            raise ('Error: the messages should be passed as a numpy array')
        self.messages = messages
        self.file_path = file_path
        base_path = os.path.join(self.file_path, 'to_bob')
        key_path = os.path.join(base_path, 'public_key.npy')
        ciphers_path = os.path.join(base_path, 'ciphertexts.npy')
        hash_path = os.path.join(base_path, 'hash_params.npy')
        if not os.path.isdir(base_path) \
        or not os.path.isfile(key_path) \
        or not os.path.isfile(ciphers_path) \
        or not os.path.isfile(hash_path):
            raise ("Error: Alice's files were not found")

        self.encryption_scheme = EncryptionScheme()
        self.encryption_scheme.from_file(key_path)
        self.modulo = self.encryption_scheme.public_key
        raw_encrypted_polynomial = np.load(ciphers_path, allow_pickle=True)
        self.hash = Hash()
        self.hash.from_file(hash_path)
        t1 = datetime.datetime.now()
        self.encrypted_polynomials = np.array([
            Ciphertext(raw_encrypted_polynomial[i, j], self.modulo)
            for i in range(raw_encrypted_polynomial.shape[0])
            for j in range(raw_encrypted_polynomial.shape[1])
        ])
        self.encrypted_polynomials = self.encrypted_polynomials.reshape(
            (raw_encrypted_polynomial.shape[0],
             raw_encrypted_polynomial.shape[1]))
        homomorphic_encs = self._compute_homomorphic_encryptions()
        t2 = datetime.datetime.now()
        print("Bob's computations took: " + str(t2 - t1))
        raw_encs = np.array([cipher.ciphertext for cipher in homomorphic_encs])
        raw_encs = np.random.permutation(
            raw_encs)  # Permute set elements to hide order
        output_path = os.path.join(self.file_path, 'from_bob')
        if not os.path.isdir(output_path):
            os.mkdir(output_path)
        ciphers_path = os.path.join(output_path, 'ciphertexts.npy')
        np.save(ciphers_path, raw_encs, allow_pickle=True)

    def _homomorphic_poly_evaluation(self, message):
        """ Evaluate Enc(P(y)) for the specified message and the relevant polynomial \
            using Horner's rule for short exponentations """
        hash_1, hash_2 = self.hash.hash(message)
        poly_1 = self.encrypted_polynomials[hash_1]
        poly_2 = self.encrypted_polynomials[hash_2]
        result_1, result_2 = self.encryption_scheme.encrypt_single_message(
            0), self.encryption_scheme.encrypt_single_message(0)
        result_1 += poly_1[-1]  # Coefficient of the largest power, a_n
        result_2 += poly_2[-1]
        for coefficient in np.flip(poly_1)[1:]:
            result_1 = result_1 * message + coefficient
        for coefficient in np.flip(poly_2)[1:]:
            result_2 = result_2 * message + coefficient
        return result_1, result_2

    def _compute_homomorphic_encryptions(self):
        """ Evaluates Enc(P(y)*r + y) for all messages y """
        homomorphic_encs = np.array([
            item for message in self.messages
            for item in self._homomorphic_poly_evaluation(int(message))
        ])
        for i in tqdm.tqdm(range(homomorphic_encs.size)):
            homomorphic_encs[i] *= random.randint(1, self.modulo - 1)
            homomorphic_encs[
                i] += self.encryption_scheme.encrypt_single_message(
                    int(self.messages[i // 2]))
        return homomorphic_encs
Example #3
0
class Alice:
    def __init__(self, messages, file_path):
        """ PSI sender side implementation. \
            The relevant files for bob will be located at "file_path/to_bob" """
        if type(messages) != np.ndarray:
            raise ('Error: the messages should be passed as a numpy array')
        self.messages = messages
        self.file_path = file_path
        self.hash_table_size = round(
            len(messages) / np.log(np.log(messages.size)))
        print('Number of bins: ' + str(self.hash_table_size))
        self.max_bin_size = round(5 * np.log(np.log(messages.size)))
        print('Single Bin size: ' + str(self.max_bin_size))
        self.hash = Hash()
        self.hash.generate(self.hash_table_size)
        self.polynomials = self._compute_polynomials()
        self.encryption_scheme = EncryptionScheme()
        self.encryption_scheme.generate()
        t1 = datetime.datetime.now()
        encrypted_poly = self.encryption_scheme.encrypt_encoded_message(
            self.polynomials)
        t2 = datetime.datetime.now()
        print("Alice's coefficients encryption took " + str(t2 - t1))
        base_path = os.path.join(self.file_path, 'to_bob')
        if not os.path.isdir(base_path):
            os.mkdir(base_path)
        key_path = os.path.join(base_path, 'public_key.npy')
        self.encryption_scheme.to_file(key_path)
        ciphers_path = os.path.join(base_path, 'ciphertexts.npy')
        hash_path = os.path.join(base_path, 'hash_params.npy')
        self.hash.to_file(hash_path)
        ciphers_array = np.array([
            encrypted_poly[i, j].ciphertext
            for i in range(encrypted_poly.shape[0])
            for j in range(encrypted_poly.shape[1])
        ],
                                 dtype=object)
        ciphers_array = ciphers_array.reshape(encrypted_poly.shape)
        np.save(ciphers_path, ciphers_array, allow_pickle=True)

    def _compute_polynomials(self):
        polynomials = np.zeros((self.hash_table_size, self.max_bin_size),
                               dtype=int)
        roots_by_hash = [[] for _ in range(self.hash_table_size)]
        for message in self.messages:
            hash_1, hash_2 = self.hash.hash(message)
            if len(roots_by_hash[hash_1]) < len(roots_by_hash[hash_2]):
                roots_by_hash[hash_1].append(message)
            else:
                roots_by_hash[hash_2].append(message)
        print('Maximum actual items in a single bin: ' +
              str(max([len(row) for row in roots_by_hash])))
        for i in range(len(roots_by_hash)):
            roots = np.array(roots_by_hash[i])
            poly = MathUtils().polynomial_coefficients_from_roots(roots)
            for j in range(-int(poly.size), 0, 1):
                polynomials[i, j] = poly[j + poly.size]
        return polynomials

    def evaluate_intersection(self):
        """ Evaluate the intersection after recieving bob's file \
         Bob's file should be located at "file_path/from_bob" """
        ciphers_path = os.path.join(self.file_path, 'from_bob/ciphertexts.npy')
        if not os.path.isfile(ciphers_path):
            raise ("Error: bob's file was not found")
        raw_ciphertexts = np.load(ciphers_path, allow_pickle=True)
        ciphertexts = np.array([
            Ciphertext(int(raw_cipher), self.encryption_scheme.public_key)
            for raw_cipher in raw_ciphertexts
        ])
        decryptions = self.encryption_scheme.decrypt_to_encoded_message(
            ciphertexts)
        print('Alice sees from Bob: ' + str(decryptions))
        return np.intersect1d(self.messages, decryptions)
def getByRegister(credentials) :
	username, password = credentials.get("username"), credentials.get("password")
	if not Database.existsUser(username) :
		user = User(username, Hash.hash(password))
		Database.storeUser(user)
		return user
def getByLogin(credentials) :
	data = Database.loadUserByLogin(credentials.get("username"), Hash.hash(credentials.get("password")))
	if data :
		user = User(*data)
		return user