def calculsomme(nom1, nom2): connec = db_connexion(db_user, db_password, db_host, db_db) cur = connec.cursor() query = "SELECT salairePHE FROM salaire WHERE nom=(%s) OR nom=(%s)" cur.execute(query, (nom1, nom2)) somme = 0 for salairePHE in cur: #Chargement des attributs dans une variables recuperationPHE = json.loads(salairePHE[0]) #Recuperation de la clé publique contenue n = recuperationPHE['public_key'] public_key = paillier.PaillierPublicKey(n=int(n)) #Regénération de l'objet chiffré valeurSalaire = paillier.EncryptedNumber( public_key, int(recuperationPHE['ciphertext']), int(recuperationPHE['exponent'])) #Somme des salaires somme += valeurSalaire cur.close db_close(connec) #Sérialisation de la somme serieSomme = { 'public_key': public_key.n, 'ciphertext': str(somme.ciphertext()), 'exponent': somme.exponent } return serieSomme
def receiveVotes(self): self.comm.initiateConn() res = self.comm.receiveMessage('bb') f = open('../common/comm.line', 'r') self.votes = json.loads(f.read()) f.close() self.comm.closeConn() print(self.votes) self.comm.joinConn(self.eb_location[0], self.eb_location[1]) res = self.comm.receiveMessage('eb') msg = json.loads(res) self.ebpPub = paillier.PaillierPublicKey(g=int(msg['g']), n=int(msg['n'])) for i in range(len(self.votes)): for j in range(len(self.votes[i])): self.votes[i][j] = paillier.EncryptedNumber( self.ebpPub, int(self.votes[i][j]), 0) totals = [] if (len(self.votes) > 0): totals = self.votes.pop(0) for i in self.votes: if len(self.votes) != len(totals): quit() for j in self.votes[i]: totals[j] += self.votes[i][j] totals_expanded = [str(x.ciphertext()) for x in totals] f = open('../common/comm.line', 'w') f.write(json.dumps(totals_expanded)) f.close() self.comm.sendMessage("SENTOFF" * 10) self.comm.closeConn() quit()
def calculate_geo(): # rebuild public key g = int(request.args.get('g')) n = int(request.args.get('n')) # g is n+1 on both sides pubkey = paillier.PaillierPublicKey(n=n) # load the coordinates as EncryptedNumber type lat = paillier.EncryptedNumber(pubkey, int(request.args.get('lat'))) lng = paillier.EncryptedNumber(pubkey, int(request.args.get('lng'))) # use same key to encrypt the geobox west = pubkey.encrypt(geobox[0]) south = pubkey.encrypt(geobox[1]) east = pubkey.encrypt(geobox[2]) north = pubkey.encrypt(geobox[3]) latoffset = (south - lat) * random() latoffset2 = (north - lat) * random() lngoffset = (west - lng) * random() lngoffset2 = (east - lng) * random() return json.dumps({ "lat": str(latoffset.ciphertext()), "lat2": str(latoffset2.ciphertext()), "lng": str(lngoffset.ciphertext()), "lng2": str(lngoffset2.ciphertext()), })
def testCantAddWithDifferentKeys(self): ciphertext1 = self.public_key.encrypt(0, r_value=1) # Let's not and say we did ciphertext2 = self.public_key.encrypt(20, r_value=1) public_key_2 = paillier.PaillierPublicKey(126869) ciphertext2.public_key = public_key_2 # Suuuper dodgy self.assertRaises(ValueError, ciphertext1.__add__, ciphertext2)
def testRawEncryptDecryptRegression0(self): public_key = paillier.PaillierPublicKey(6497955158, 126869) private_key = paillier.PaillierPrivateKey(public_key, 31536, 53022) ciphertext = public_key.raw_encrypt(10100, 74384) self.assertEqual(848742150, ciphertext) decryption = private_key.raw_decrypt(848742150) self.assertEqual(10100, decryption)
def testRawEncryptDecryptRegression0(self): public_key = paillier.PaillierPublicKey(126869) private_key = paillier.PaillierPrivateKey(public_key, 293, 433) ciphertext = public_key.raw_encrypt(10100, 74384) self.assertEqual(935906717, ciphertext) decryption = private_key.raw_decrypt(935906717) self.assertEqual(10100, decryption)
def encrFromJson(json): pubK = paillier.PaillierPublicKey(n=json['public_key']['n']) value = paillier.EncryptedNumber( public_key=pubK, ciphertext=json['_EncryptedNumber__ciphertext'], exponent=json['exponent']) value._EncryptedNumber__is_obfuscated = json[ '_EncryptedNumber__is_obfuscated'] return value
def KStateTransition(self): print( "#######################K-th State Transistion#############################" ) print("---Matrix transition---") print(self.mat) #Restore the data from the DB self.__retrieveData() #Generation of the K-th random number self.r_a.append(random.randint(0, self.Q_len - 1)) print("---r_a---") print(self.r_a) #Blinding all the matrix element for i in range(0, self.Al_len): for j in range(0, self.Q_len): self.mat[i][j] = (self.mat[i][j] + self.r_a[self.k]) % self.Q_len #Shift left of r_a(k-1) position self.mat[i] = np.roll(self.mat[i], -self.r_a[self.k - 1]) print("---Rolled matrix---") print(self.mat) #Now i have to read data sent from client length = int(self.headers.get('Content-length')) data = self.rfile.read(length) recive_data = json.loads(data) puk = recive_data['PublicKey'] #Rebuild of the encrypted vector sent by the client public_key = paillier.PaillierPublicKey(n=int(puk['n'])) encrypted_e = [ paillier.EncryptedNumber(public_key, int(x[0]), int(x[1])) for x in recive_data['CipherText'] ] #v is the encrypted vector obtained by multiplicating transition matrix to encrypted vector recived enc_mean = np.mean(encrypted_e) v_encrypt = np.dot(self.mat, encrypted_e) #Setting of the data to sent to client data = {} data["BlindVector"] = [(str(x.ciphertext()), x.exponent) for x in v_encrypt] self.__sendResponse(data) if self.k != self.t_len: self.k = self.k + 1 #storage of the data into the DB self.__storeData()
def testEncryptIsRandom(self): # Check for semantic security public_key = paillier.PaillierPublicKey(126869) enc_num = public_key.encrypt(1, r_value=1) self.assertEqual(126870, enc_num.ciphertext(False)) # r_value should be random enc_num2 = public_key.encrypt(1) enc_num3 = public_key.encrypt(1) self.assertNotEqual(126870, enc_num2.ciphertext(False)) self.assertNotEqual(enc_num2.ciphertext(False), enc_num3.ciphertext(False))
def get_public_key_he(): #get public key for h.e. url_key = 'http://server_decrypt:90/key' key = requests.post( url_key ) #request a public key from the server_encrypt to encrypt the ballot llave = json.loads( key.text) # gets public key from the server_encrypt for h.e return paillier.PaillierPublicKey( n=int(llave['public_key'] ['n'])) # create public key obj from the key sent by the server
def HE_deserialize(received_dict_JSON): """take JSON and extract public_key and array of encrypted numbers""" received_dict = json.loads(received_dict_JSON) pk = received_dict['public_key'] public_key_rec = paillier.PaillierPublicKey(n=int(pk['n'])) enc_nums_rec = [ paillier.EncryptedNumber(public_key_rec, int(x[0]), int(x[1])) for x in received_dict['encrypted_numbers'] ] return public_key_rec, enc_nums_rec
def prediction(): try: query = request.json if request.method == "POST" and request.json else {} cipher = query.get("enc_feature_vector") pk_n = query.get("pub_key_n") except: return ERR_BAD_ENCODING, 400 if pk_n is None: return ERR_NO_PUB_KEY, 400 if cipher is None: return ERR_NO_INPUT, 400 if not isinstance(cipher, list) or len(cipher) != len(model_coeffs): return ERR_BAD_DIM, 400 if len(set(cipher)) <= 2: return ERR_ATTACK_DETECT, 403 try: pk = paillier.PaillierPublicKey(pk_n) model_coeffs_enc = [ paillier.EncodedNumber.encode(pk, coeff, precision=precision) for coeff in model_coeffs ] model_bias_enc = paillier.EncodedNumber.encode(pk, model_bias, precision=precision) except: return ERR_BAD_PK, 400 try: cts = [] for ct in cipher: if not isinstance(ct, int) or ct < 0 or ct > pk.nsquare: raise cts += [paillier.EncryptedNumber(pk, ct, -4)] cres = sum( (ct * coeff for (ct, coeff) in zip(cts, model_coeffs_enc))) + model_bias_enc ctres = cres.ciphertext() except: return ERR_BAD_IN, 400 return_dict = {"enc_prediction": ctres} return jsonify(return_dict), 200
def process(): if request.method == 'POST': received_dict = json.loads(request.data) public_key_rec = paillier.PaillierPublicKey( n=int(received_dict['public_key']['n'])) enc_nums_rec = [ paillier.EncryptedNumber(public_key_rec, int(x[0]), int(x[1])) for x in received_dict['values'] ] x = randint(1, 10) result = {} result['values'] = [(str(enc_num.ciphertext()), enc_num.exponent) for enc_num in [(num * x) for num in enc_nums_rec]] return json.dumps(result)
def _get_public_keys(self): ## http requests # headers = {'content-type': 'application/json'} ## phe res = http.get(self.provider_uri + '/phe_public_key') phe_n = res.json()['phe_pk'] ## fhe res = http.get(self.provider_uri + '/fhe_public_key') fhe_b64 = res.json()['fhe_pk'] fhe_bytes = base64.b64decode(fhe_b64.encode('utf-8')) # fhe_bytes_json = fhe_bytes_json.encode('utf-8') fhe_pk = self.ctx.load_cloud_key(fhe_bytes) phe_pk = paillier.PaillierPublicKey(n=int(phe_n)) return phe_pk, fhe_pk
def ot_server(m0, m1): n = int(sys.stdin.readline().strip()) pk = paillier.PaillierPublicKey(n) c = int(sys.stdin.readline().strip()) r0 = pk.get_random_lt_n() r1 = pk.get_random_lt_n() x0 = int.from_bytes(m0, 'big') x1 = int.from_bytes(m1, 'big') c0 = powmod( pk.raw_encrypt(1) * powmod(c, (pk.n - 1), pk.nsquare), x0, pk.nsquare) * powmod(c, r0, pk.nsquare) c1 = powmod(c, x1, pk.nsquare) * powmod( pk.raw_encrypt(1) * powmod(c, (pk.n - 1), pk.nsquare), r1, pk.nsquare) sys.stdout.write('{}\n'.format(c0)) sys.stdout.write('{}\n'.format(c1))
def client_sync(self, server_addr, target_data, method, params): dt = self.data.data url = f"http://{server_addr}/{method}" # print(url) while True: try: r = requests.get(url, params=params) print(params) except Exception as e: # print(f"request error: {e}") print(r.status_code, 'error') if r.status_code == 200: try: # print(r.json()) data = r.json()['content'] if type(data) is list: public_key = dt['public_key'] if type(data[0]) is list: data = [ paillier.EncryptedNumber( public_key, int(x[0]), int(x[1])) for x in data ] data = np.asarray(data) elif type(data[0]) is float: data = np.asarray(data) else: data = paillier.EncryptedNumber( public_key, int(data[0]), int(data[1])) elif type(data) is dict: data = paillier.PaillierPublicKey(n=int(data['n'])) dt.update({target_data: data}) break except Exception as e: print("fail to transform data error: %s" % e) print(data) else: print( f"{self.name} failed to run method {method}, waiting....") sleep(1) print(f"{self.name} successfully finished {method}")
def results(request): if request.method == 'POST': form = DecryptResultsForm(request.POST) if form.is_valid(): pub_key = paillier.PaillierPublicKey( int(PublicKey.objects.all()[0].n)) p = int(form.cleaned_data['p']) q = int(form.cleaned_data['q']) results = {} priv_key = paillier.PaillierPrivateKey(pub_key, p, q) for candidate in Candidate.objects.all(): if len(candidate.voted) == 0: results[candidate] = 0 else: results[candidate] = priv_key.decrypt( paillier.EncryptedNumber(pub_key, int(candidate.voted))) return render(request, 'results.html', {'results': results}) return render(request, 'decrypt_results.html', {'form': DecryptResultsForm()})
def vote(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = VoteForm(request.POST) # check whether it's valid: if form.is_valid(): key = paillier.PaillierPublicKey(int(PublicKey.objects.all()[0].n)) voted_for = form.cleaned_data['candidate'] for candidate in Candidate.objects.all(): if candidate == voted_for: value = 1 else: value = 0 new_vote = key.encrypt(value) if len(candidate.voted) > 0: new_vote = new_vote + paillier.EncryptedNumber( key, int(candidate.voted)) candidate.voted = new_vote.ciphertext() candidate.save() return render(request, 'thanks.html') return render(request, 'vote.html', {'form': VoteForm()})
def testEncryptRegression(self): public_key = paillier.PaillierPublicKey(126869) enc_num = public_key.encrypt(10100, r_value=74384) self.assertEqual(935906717, enc_num.ciphertext(False))
from phe import paillier from binascii import unhexlify from math import gcd import sys sys.setrecursionlimit(100000) p = 310013024566643256138761337388255591613 q = 319848228152346890121384041219876391791 n = p * q g = 99157116611790833573985267443453374677300242114595736901854871276546481648884 c = 2433283484328067719826123652791700922735828879195114568755579061061723786565164234075183183699826399799223318790711772573290060335232568738641793425546869 k = 1 l = ((p - 1) * (q - 1)) // gcd(p - 1, q - 1) pk = paillier.PaillierPublicKey(n) pp = paillier.PaillierPrivateKey(pk, p, q) en = paillier.EncryptedNumber(pk, c) m = pp.decrypt(en) print(unhexlify(hex(m)[2:])) #m = div(pow(c, l, n * n), pow(g, l, n * n)) ''' [msieve153] > .\msieve153.exe -q -v 99157116611790833573985267443453374677300242114595736901854871276546481648883 Msieve v. 1.53 (SVN 1005) Sat Apr 20 10:47:37 2019 random seeds: b3564e14 fdbd8498 factoring 99157116611790833573985267443453374677300242114595736901854871276546481648883 (77 digits) searching for 15-digit factors commencing quadratic sieve (77-digit input)
else: hedatadict[header].append( paillier.EncryptedNumber(pub_key, int(tmpdatalist[0]), int(tmpdatalist[1]))) line = f.readline() return hedatadict if __name__ == '__main__': PreProcess() #get public key with open('data/public_key.json', 'r') as f: received_dict = json.loads(f.read()) pk = received_dict['public_key'] public_key_rec = paillier.PaillierPublicKey(n=int(pk['n'])) #get private key with open('data/private_key.json', 'r') as f: received_dict = json.loads(f.read()) pk = received_dict['private_key'] private_key_rec = paillier.PaillierPrivateKey(public_key_rec, p=int(pk['p']), q=int(pk['q'])) #get rdd HeDataDict = GetRDDlist(public_key_rec, "data/HEfee.csv") for keylist in HeDataDict: HeDataList = HeDataDict[keylist] sum = reduce(lambda a, b: a + b, HeDataList) printstr = (keylist + ':{}').format(private_key_rec.decrypt(sum))
def deserialisePubKey(inputSerialisedKey): return paillier.PaillierPublicKey(int(inputSerialisedKey))
p = int(f.readline()) q = int(f.readline()) # N = p * q N = int(f.readline()) # d = lcm(p-1, q-1) d = int(f.readline()) # u = inverse_mod(d, N) u = int(f.readline()) N2 = N * N g = 1 while pow(g, d // 2, N) == 1: g = getRandomRange(0, N) ppub = paillier.PaillierPublicKey(n=N) ppri = paillier.PaillierPrivateKey(ppub, p, q) FLAG1 = f.readline().strip() FLAG2 = f.readline().strip() assert len(FLAG2) < 24 FLAG2 = FLAG2 + os.urandom(31 - len(FLAG2)) FLAG2 = int.from_bytes(FLAG2, 'little') # FLAG2 -= 2 f.close() def aesenc(m): aes = AES.new(aeskey, AES.MODE_CBC, aesiv) return aes.encrypt(m.to_bytes(2048 // 8, 'little')).hex()
full_msg += msg # print(len(full_msg)) if len(full_msg)-headersize == msglen: #print("full msg recvd") #print(full_msg[headersize:]) received_messeges_list.append(full_msg[headersize:]) new_msg = True full_msg = b"" i += 1 break return received_messeges_list pub_key = paillier.PaillierPublicKey(n=20918476852815906259448091380878946374846487276650566350526469504543445663363006375980464912046003771545816024129058558897178268328832892428243240325758816116809718007069804705445565528216535257753269775084363475484444731252249136528364485880450590478550481470180234291919073001105225222550340248448357283825562788397193502321253284246970379855378912631159893549706516122724903022561898802098365905740512394253180872362469204594849288169219051343346465473138330721772474356841242103555961863230650369004568170457199923595396226384215744451385588202919741103547377489727484513916853945581587278621259117042875720155503) # server # D:\KFUPM\COE449\project\my_text.txt # C:\Users\User\IdeaProjects\python training\.idea\myfile.txt # C:\Users\User\IdeaProjects\python training\.idea\lastcrashefile.txt directroy = input("if you have a previous file please inter it direcroty: (else just click enter)") directroy = directroy.strip() # he must have a table of all positions lets say a dictonary where the key is the row and the value is columns myTextFile = dict() if "" == directroy: myTextFile = dict() else: f=open(directroy,"rb") print('opned file') #my_file = f.read()
def _public_key_from_dict(public_key_dict): return paillier.PaillierPublicKey(public_key_dict['n'])
def _private_key_from_dict(public_key_dict, _private_key_dict): public_key = paillier.PaillierPublicKey(public_key_dict['n']) return paillier.PaillierPrivateKey(public_key, **_private_key_dict)
def main(): name =argv[1] # read the homomorphic public and private keys shared by Alice and Bob with open('homomorphic_key.txt') as json_file: data = json.load(json_file) public_key = paillier.PaillierPublicKey(n=int(data['public_key'])) private_key = paillier.PaillierPrivateKey(public_key, data['private_key'][0],data['private_key'][1]) # create an INET, STREAMing socket try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print('Failed to create socket') sys.exit() print('Socket Created') host = socket.gethostname() port = 4321; try: remote_ip = socket.gethostbyname(host) except socket.gaierror: # could not resolve print('Hostname could not be resolved. Exiting') sys.exit() # Connect to remote server s.connect((remote_ip, port)) print('Socket Connected to ' + host + ' on ip ' + remote_ip) # Saying hello to the server message = name try: # Set the whole string s.sendall(message.encode()) except socket.error: # Send failed print('Send failed') sys.exit() print('Message sent successfully') # Now receive data reply = s.recv(4096) print(reply) # encrypt the secret message with the homomorphic public key secret_message = int(argv[2]) cipher = public_key.encrypt(secret_message) secret = {} secret['cipher'] = (str(cipher.ciphertext()), cipher.exponent) serialised = json.dumps(secret).encode() try: # Set the whole string # print(serialised) s.sendall(serialised) print('I have sent the encrypted secret') except socket.error: # Send failed print('Send failed') sys.exit() # Now receive the answer back from the server reply = s.recv(4096) # print(reply) received_dict = json.loads(reply) answer = paillier.EncryptedNumber(public_key, int(received_dict['encrypted'][0]), int(received_dict['encrypted'][1])) # first check the signature, Alice has access to the verification key of the Server key = RSA.importKey(open("pubkey.pem").read()) h = SHA1.new() h.update(received_dict['encrypted'][0].encode()) h.update(str(received_dict['encrypted'][1]).encode()) signature =binascii.unhexlify(received_dict['signature'].encode('utf-8')) verifier = PKCS1_PSS.new(key) if verifier.verify(h, signature): print("The signature is authentic.") else: print("The signature is not authentic.") # now decrypt the answer using private key, if it is 0 then strings were equal otherwise unequal key_decrypt = private_key.decrypt(answer) if key_decrypt==0: print("The strings were equal!") else: print("The strings were unequal!") # close connections s.close()
def make_pk(n: int) -> paillier.PaillierPublicKey: pk = paillier.PaillierPublicKey(n) pk.max_int = _pick_max_int(pk) return pk
def main(): # create sockets s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = socket.gethostname( ) # Symbolic name meaning all available interfaces PORT = 4321 # Arbitrary non-privileged port print('Socket created') try: s.bind((HOST, PORT)) except socket.error as msg: print('Bind failed') sys.exit() print('Socket bind complete') s.listen(10) print('Socket now listening') dict = {} # say hello to Alice and Bob when they connect connAlice, addr = s.accept() print('Connected with ' + addr[0] + ':' + str(addr[1])) data = connAlice.recv(1024) if data.decode() == 'Alice': name = 'Alice' dict[addr] = 'Alice' else: print('Invalid client') reply = ('Hello' + name + '! ' + 'This is your connection: ' + addr[0] + ':' + str(addr[1]) + '. Please send me your encrypted secret.') connAlice.sendall(reply.encode()) print('I said Hello to Alice') connBob, addr = s.accept() print('Connected with ' + addr[0] + ':' + str(addr[1])) data = connBob.recv(1024) if data.decode() == 'Bob': name = 'Bob' dict[addr] = 'Bob' else: print('Invalid client') reply = ('Hello' + name + '! ' + 'This is your connection: ' + addr[0] + ':' + str(addr[1]) + '. Please send me your encrypted secret.') connBob.sendall(reply.encode()) print('I said Hello to Bob') #get homomorphic public key of Alice and Bob with open('homomorphic_key.txt') as json_file: data = json.load(json_file) public_key = paillier.PaillierPublicKey(n=int(data['public_key'])) # receive Alice's encrypted secret AliceJSON = connAlice.recv(4096) received_dict = json.loads(AliceJSON) cipherAlice = paillier.EncryptedNumber(public_key, int(received_dict['cipher'][0]), int(received_dict['cipher'][1])) # receive Bob's encrypted secret BobJSON = connBob.recv(4096) received_dict = json.loads(BobJSON) cipherBob = paillier.EncryptedNumber(public_key, int(received_dict['cipher'][0]), int(received_dict['cipher'][1])) print('I have received Alice and Bob\'s secrets') # add them homomorphically minus = phe.encoding.EncodedNumber.encode(public_key, -1) cipherBob = minus * cipherBob added = cipherAlice + cipherBob # multiply it by a blinding factor so as to not leak any information blinding_factor = random.randint(1, 100000) encoded_blinding_factor = phe.encoding.EncodedNumber.encode( public_key, blinding_factor) added = added * encoded_blinding_factor added_secrets = {} # using the Server's public key, sign the answer that is to be sent back key = RSA.importKey(open("privkey.pem").read()) h = SHA1.new() added_secrets['encrypted'] = str(added.ciphertext()), added.exponent h.update(str(added.ciphertext()).encode()) h.update(str(added.exponent).encode()) signer = PKCS1_PSS.new(key) signature = signer.sign(h) added_secrets['signature'] = binascii.hexlify(signature).decode('utf-8') answer = json.dumps(added_secrets).encode() # now send Alice and Bob the answer, they will decrypt it and find out if the secrets were equal try: # Set the whole string connAlice.sendall(answer) print('I have sent Alice the answer') except socket.error: # Send failed print('Send failed') sys.exit() try: # Set the whole string connBob.sendall(answer) print('I have sent Bob the answer') except socket.error: # Send failed print('Send failed') sys.exit() # close all connections connAlice.close() connBob.close() s.close()
def election(): verify_vote_form = None id = request.args.get("id") election = Election.query.filter_by(id=id).first() if election == None: flash('Election not found', "danger") return redirect(url_for('home')) organizer = User.query.filter_by(id=election.organizer_id).first() candidates = db.session.query(Candidate, User).filter_by( election_id=election.id).join(User, User.id == Candidate.user_id).all() voters = db.session.query(Voter, User).filter_by(election_id=election.id).join( User, User.id == Voter.user_id).all() vms = VotingMachine.query.filter_by(status=True).all() if (vms == []): flash("No voting machines online", "danger") return redirect(url_for('home')) vm = random.choice(vms) voting_link = "#" if vm != None: voting_link = "http://localhost:" + str(vm.port) + "/vote/" else: flash("No voting machines online", "danger") return redirect(url_for('home')) ciphertexts = defaultdict(lambda: 1) nonces = defaultdict(lambda: 1) tally = defaultdict(lambda: 1) candidate_dict = [] winners = [] num_votes = 0 user_voted = None percent_verified = 0 open_form = OpenElectionForm() close_form = CloseElectionForm() verified_vote_form = None form_type = request.form.get('type') if form_type == "open" and open_form.validate_on_submit(): election = Election.query.filter_by(id=election.id).filter_by( organizer_id=current_user.get_id()).filter_by( started=False).filter_by(ended=False).first() if election != None: election.started = True db.session.add(election) db.session.commit() flash("Election is now open", "success") if (form_type == "close" and close_form.validate_on_submit()) or election.ended: closing = False lam = lcm( int(election.private_key_p) - 1, int(election.private_key_q) - 1) if form_type == "close" and close_form.validate_on_submit(): closing = True election = Election.query.filter_by(id=election.id).filter_by( organizer_id=current_user.get_id()).first() if election != None: data_dict = { 'nonce_product': defaultdict(lambda: 1), 'votes': defaultdict(dict) } data_dict = get_all_votes(election) nonces = defaultdict(lambda: 1) ciphertexts = data_dict['votes'] tally = defaultdict(lambda: 0) public_key = paillier.PaillierPublicKey(int(election.public_key)) private_key = paillier.PaillierPrivateKey( public_key, int(election.private_key_p), int(election.private_key_q)) for candidate in candidates: for fingerprint in data_dict['votes']: tally[candidate.Candidate.id] += paillier.EncryptedNumber( public_key, int(data_dict['votes'][fingerprint][str( candidate.Candidate.id)])) if closing: candidate.Candidate.votes = private_key.decrypt( tally[candidate.Candidate.id]) db.session.add(candidate.Candidate) nonces[candidate.Candidate.id] = compute_nonce( candidate.Candidate.votes, tally[candidate.Candidate.id].ciphertext(False), int(election.public_key), int(election.public_key) + 1, lam) if closing: election.ended = True db.session.add(election) flash("Election is now closed", "success") db.session.commit() verify_vote_form = VerifyVoteForm() if form_type == "verify" and verify_vote_form.validate_on_submit(): temp_election_id = int(request.form.get("election")) temp_user_id = int(request.form.get("user")) temp_voter_id = int(request.form.get("voter")) temp_auth_token = request.form.get("authentication_token") temp_voter = Voter.query.filter_by(id=temp_voter_id).filter_by( election_id=temp_election_id).filter_by( user_id=temp_user_id).filter_by( authentication_token=temp_auth_token).filter_by( voted=True).filter_by(verified=False).first() if (temp_voter != None): temp_voter.verified = True if request.form.get("vote_exists"): temp_voter.vote_exists = True db.session.add(temp_voter) db.session.commit() user_voted = Voter.query.filter_by( election_id=election.id).filter_by(voted=True).filter_by( user_id=current_user.id).first() if (user_voted != None and user_voted.verified == False): flash("Please verify if you see your vote", "info") num_votes = 0 max_votes = 0 for candidate in candidates: num_votes += candidate.Candidate.votes if candidate.Candidate.votes > max_votes: max_votes = candidate.Candidate.votes for candidate in candidates: if candidate.Candidate.votes == max_votes: winners.append(candidates) voted_voters = Voter.query.filter_by( election_id=election.id).filter_by(voted=True).all() ax = 0 max = num_votes for voter in voted_voters: if voter.verified == True and voter.vote_exists == True: ax += 1 percent_verified = ax * 100 / max if (num_votes != len(voted_voters)): flash("Warning: More votes received than expected", "danger") nonces = nonces_to_dict(nonces) tally = encrypted_numbers_to_dict(tally) candidate_dict = candidates_to_dict(candidates) return render_template('election.html', election=election, organizer=organizer, candidates=candidates, voters=voters, open_form=open_form, close_form=close_form, voting_link=voting_link, votes=ciphertexts, nonces=nonces, tally=tally, candidate_dict=candidate_dict, winners=winners, num_votes=num_votes, user_voted=user_voted, percent_verified=percent_verified, verify_vote_form=verify_vote_form)