def update_pall_keys(self, pall_keys): """ Updates local pallier key dict given encrypted pallier key dictionary mapping {user_pub_key: (PALL_PK, ENC(PALL_SK))} where ENC uses the current user's secret key """ for rsa_pub, pair in pall_keys.items(): if rsa_pub in self.pall_keys: continue #pub_key = ast.literal_eval(pair[0]) #g = pub_key[0] #n = pub_key[1] pall_pub = pair[0] #paillier.PaillierPublicKey(n) #pall_pub.g = g #print("DEBUG - pub_key = " + str((self.rsa_priv.n, self.rsa_priv.e))) #print("DEBUG - priv_key = " + str((self.rsa_priv.d))) cipher_data = ast.literal_eval(pair[1]) #print("DEBUG - ciphertexts = " + str(cipher_data)) cipher = PKCS1_OAEP.new(self.rsa_priv) p = pickle.loads(cipher.decrypt(cipher_data[0])) q = pickle.loads(cipher.decrypt(cipher_data[1])) #print("DEBUG - private_p = " + str(private_p)) #print("DEBUG - private_q = " + str(private_q)) #priv_data = pickle.loads(private_bytes) #print("DEBUG - " + str(priv_data)) #p = priv_data[0] #q = priv_data[1] #print("DEBUG - (p: {},\n q: {},\n n: {}".format(p, q, n)) pall_priv = paillier.PaillierPrivateKey(pall_pub, p, q) self.pall_keys[rsa_pub] = (pall_pub, pall_priv)
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 sk_from_file(skfile) -> paillier.PaillierPrivateKey: data = json.load(skfile) if any(attr not in data for attr in ('n', 'p', 'q')): raise ValueError("Missing keys in sk file") pk = make_pk(data['n']) sk = paillier.PaillierPrivateKey(pk, data['p'], data['q']) return sk
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()})
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) using multiplier of 3
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)) print(printstr)
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()
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 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)
def make_sk(n: int, p: int, q: int): pk = make_pk(n) return paillier.PaillierPrivateKey(pk, p, q)
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()