def test4(self): # Loopback split/recombine (SSSS) secret = unhexlify(b("000102030405060708090a0b0c0d0e0f")) shares = Shamir.split(2, 3, secret, ssss=True) secret2 = Shamir.combine(shares[:2], ssss=True) self.assertEqual(secret, secret2)
def test3(self): # Loopback split/recombine secret = unhexlify(b("000102030405060708090a0b0c0d0e0f")) shares = Shamir.split(2, 3, secret) secret2 = Shamir.combine(shares[:2]) self.assertEqual(secret, secret2) secret3 = Shamir.combine([shares[0], shares[2]]) self.assertEqual(secret, secret3)
def udp_broadcaster(): global port, broadcast_hash, priv_key, old_hash # create socket broadcast_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP) broadcast_socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) # create new ephID and generate recv_shares priv_key, broadcast_id = generate_ephid() broadcast_id_recv_shares = Shamir.split(3, 6, broadcast_id) # hash of ephid broadcast_hash = sha256(broadcast_id).hexdigest() # print recv_shares and id print_id(broadcast_id, broadcast_id_recv_shares) # timer start_time = time.time() broadcast_timer = 10 # 10 seconds id_timer = 60 # 1 minute curr_timer = time.time() - start_time while True: # broadcast id every 10 seconds if curr_timer > broadcast_timer and len(broadcast_id_recv_shares) != 0: print(f"[TASK 3A] Broadcasting shares: {broadcast_id_recv_shares[0][0], hexlify(broadcast_id_recv_shares[0][1])}") send_str = str(broadcast_id_recv_shares[0][0]) + "|" + hexlify(broadcast_id_recv_shares[0][1]).decode() + "|" + broadcast_hash broadcast_socket.sendto(send_str.encode('utf-8'), ('192.168.4.255', port)) broadcast_id_recv_shares.pop(0) broadcast_timer += 10 # create new id every minute elif curr_timer > id_timer: # create new ephID and generate recv_shares priv_key, broadcast_id = generate_ephid() broadcast_id_recv_shares = Shamir.split(3, 6, broadcast_id) # hash of ephid old_hash = broadcast_hash broadcast_hash = sha256(broadcast_id).hexdigest() # print recv_shares and id print_id(broadcast_id, broadcast_id_recv_shares) # set timer id_timer += 60 # update timer curr_timer = time.time() - start_time
def test3(self): # Loopback split/recombine secret = unhexlify(b("000102030405060708090a0b0c0d0e0f")) shares = Shamir.split(2, 3, secret) secret2 = Shamir.combine(shares[:2]) self.assertEqual(secret, secret2) secret3 = Shamir.combine([ shares[0], shares[2] ]) self.assertEqual(secret, secret3) secret4 = Shamir.combine(shares) self.assertEqual(secret, secret4) # One share too many
def test1(self): # Test splitting shares = Shamir.split(2, 3, bchr(90) * 16) self.assertEqual(len(shares), 3) for index in range(3): self.assertEqual(shares[index][0], index + 1) self.assertEqual(len(shares[index][1]), 16)
def chop(self, min_shards, shards): """chop """ self.shares = Shamir.split(min_shards, shards, self.kekHex) for share in self.shares: self.string_shares.append(hexlify(share))
def read(self, container): maxVersion, metadata_list = self.getMetadataFromClouds( filename=container.duId + 'metadata') count = 0 # Flush the metadata queue - cancel the remaining requests try: while True: self.metadataQ.get_nowait() except Empty: pass # Flushing complete if maxVersion == 0: print('No data to read! Sorry!!!') return dataFileName = container.duId + 'value' + str(maxVersion) secret_unit_list = self.readDataFromClouds(metadata_list, dataFileName) shares = [] fragments = [] for unit in secret_unit_list: shares.append((unit.secret_id, unit.share)) fragments.append(unit.value) key = Shamir.combine(shares) encrypted_data = self.ec_driver.decode(fragments) cipher = getAESCiphers(key) data = cipher.decrypt(encrypted_data) return data
def create_shares(filename, content): key = get_random_bytes(16) shares = Shamir.split(2, 3, key) share_dict = {} for idx, share in shares: share_dict["%d" % idx] = hexlify(share) cipher = AES.new(key, AES.MODE_EAX) ct, tag = cipher.encrypt(content), cipher.digest() try_count = 0 while try_count < 10: tmp_filename = secrets.token_hex() if not check_if_filename_duplicated(tmp_filename): file_content = cipher.nonce + tag + ct with open(PATH + tmp_filename, "wb") as fo: fo.write(cipher.nonce + tag + ct) insert_db(filename, tmp_filename, share_dict) break try_count += 1 if try_count >= 10: return {}, "error" return share_dict, tmp_filename
def change_format(self): msg = [] tmp = shamir.split(3, 6, self.encmgr.pub_key) for i in tmp: add = str(i[0]).encode('utf-8') + ' '.encode('utf-8') + i[1] msg.append(add) return msg
def test1(self): # Test splitting shares = Shamir.split(2, 3, bchr(90)*16) self.assertEqual(len(shares), 3) for index in xrange(3): self.assertEqual(shares[index][0], index+1) self.assertEqual(len(shares[index][1]), 16)
def decode_ephid(self, items): # print(type(items)) tmp = [] for i in items: num = int(i[0:1]) words = i[2:] tmp.append((num, words)) id = shamir.combine(tmp) return id
def main(): # Encryption Process # We will use padding because pycryptodome sss supports 16 bytes key = get_random_bytes(16) key_padded = pad(key, 32) key_sol = Web3.toHex(key_padded) key_hash = Web3.solidityKeccak(['bytes32'], [key_sol]) shares = Shamir.split(2, 5, key) print("************* ENCRYPTION ************") print("Generating Shamir Secrets") print() print("Padded Key Generated = ", key_sol) print("Hash Generated = ", key_hash.hex()) print() print("Shamir Shares") for idx, share in shares: print("{}-{}".format(idx, Web3.toHex(share))) # Decryption Process print() print("************* DECRYPTION ************") # Get shares new_shares = [] for x in range(2): inp = input("Input Share: ") inp = inp.strip() # clean white space idx, key = inp.split('-') byte_key = Web3.toBytes(hexstr=key) new_shares.append((int(idx), byte_key)) # Get Key re_key = Shamir.combine(new_shares) re_key_pad = pad(re_key, 32) re_key_hash = Web3.solidityKeccak(['bytes32'], [re_key_pad]) print() print("Key reconstructed = ", Web3.toHex(re_key)) print("Padded key = ", Web3.toHex(re_key_pad)) print("Hash Generated = ", Web3.toHex(re_key_hash)) print() print("Hash Match = {}".format(re_key_hash == key_hash))
def _recombine_128b_shares_into_bytestring(shares: List[tuple]) -> bytes: """Recombine shares of exactly 128 bits into a bytestring. :param bytestring: bytestring to split :param shares_count: number of shares to create :param threshold_count: number of shares needed to reconstitute the secret :return: list of tuples (index, share)""" secret = Shamir.combine(shares) return secret
def compute_hmac(): base = "http://crypto.chal.csaw.io:5005" usernames = [ 'Jere', 'Lakisha', 'Loraine', 'Ingrid', 'Orlando', 'Berry', 'Alton', 'Bryan', 'Kathryn', 'Brigitte', 'Dannie', 'Jo', 'Leslie', 'Adrian', 'Autumn', 'Kellie', 'Alphonso', 'Joel', 'Alissa', 'Rubin' ] secrets = [] for username in usernames: user = "******" + username query = { "username": username, "token1": "240813191444383683610874141529779860149197802230704769987870099100087528009907833040793311446806654962619628779479768893754046830059506665136223928945955844493985860589048372285183371960781762148318571728054479065130190173251314874819258678950694281789476446925580245284216649024815216185549537539602050443878" } decoded = None with requests.Session() as sess: r = sess.post(base, data=query) try: decoded = json.loads(r.text) except: pass if not decoded: raise salt = decoded["nacl"] #print(salt) K = hashlib.sha256(str(0).encode()).digest() hmac = hmac_sha256(K, salt.encode()) #print(hmac) query = {"hmac": hmac} r = sess.get(user, params=query) idx, share = re.findall(pattern, r.text)[0].split(":") secrets.append((int(idx), unhexlify(share))) key = Shamir.combine(secrets) print(key) iv = unhexlify("254dc5ae7bb063ceaf3c2da953386948") ctext = unhexlify( "08589c6b40ab64c434064ec4be41c9089eefc599603bc7441898c2e8511d03f6") c = AES.new(key, AES.MODE_CBC, iv) print(c.decrypt(ctext))
def _split_128b_bytestring_into_shares(secret: bytes, shares_count: int, threshold_count: int) -> list: """Split a bytestring of exactly 128 bits into shares. :param bytestring: bytestring to split :param shares_count: number of shares to create :param threshold_count: number of shares needed to reconstitute the secret :return: list of tuples (index, share)""" assert len(secret) == 16 shares = Shamir.split(k=threshold_count, n=shares_count, secret=secret) assert len(shares) == shares_count, shares return shares
def test2(self): # Test recombine # These shares were obtained with ssss v0.5: # ssss-split -t 2 -n 3 -s 128 -D -x secret = b("000102030405060708090a0b0c0d0e0f") shares = ((1, "0b8cbb92e2a750defa563537d72942a2"), (2, "171a7120c941abb4ecb77472ba459753"), (3, "1c97c8b12fe3fd6d1ee84b4e6161dbfe")) bin_shares = [] for share in shares: bin_shares.append((share[0], unhexlify(b(share[1])))) result = Shamir.combine(bin_shares) self.assertEqual(hexlify(result), secret)
def test2(self): # Test recombine # These shares were obtained with ssss v0.5: # ssss-split -t 2 -n 3 -s 128 -D -x secret = b("000102030405060708090a0b0c0d0e0f") shares = ( (1,"0b8cbb92e2a750defa563537d72942a2"), (2,"171a7120c941abb4ecb77472ba459753"), (3,"1c97c8b12fe3fd6d1ee84b4e6161dbfe") ) bin_shares = [] for share in shares: bin_shares.append((share[0], unhexlify(b(share[1])))) result = Shamir.combine(bin_shares) self.assertEqual(hexlify(result), secret)
def decrypt_file(code, shares): key = Shamir.combine(shares) db_share = (session.query(Himitsu_lun).filter( Himitsu_lun.enc_filename == code).first()) filename = f"{db_share.filename}" with open(PATH + code, "rb") as fi: nonce, tag = [fi.read(16) for i in range(2)] cipher = AES.new(key, AES.MODE_EAX, nonce) try: result = cipher.decrypt(fi.read()) cipher.verify(tag) return result, filename except ValueError: return "error", ""
def combine(shards, judo_file): """combine this class is passed the """ # Recombine the shards to create the kek combined_shares = Shamir.combine(shards) combined_shares_string = "{}".format(combined_shares) # decrypt the dek uysing the recombined kek decrypted_dek = decrypt(judo_file['wrappedKey'], unhexlify(combined_shares_string)) # decrypt the data using the dek decrypted_data = decrypt(judo_file['data'], unhexlify(decrypted_dek)) decrypted_text = unhexlify(decrypted_data) return (decrypted_data, decrypted_text)
def send_file(self, filename, port_list=None, ip=None, shamir_on=True): if ip == None: ip = self.CNC if port_list == None: port_list = self.PORTLIST comms = [Communication(ip, port) for port in port_list] sockets = [comm.create_socket() for comm in comms] with open(filename, "rb") as f: plain_data = f.read() encrypted_data = encrypt_message(plain_data, b"", self.dh_sharedkey) print(encrypted_data) counter = 0 left = len(encrypted_data) # amount of data left to be sent self.send_file_info(filename, left, shamir_on=shamir_on) msg_type, result = TCP_Listener.get_next_message() if msg_type == 2: filecounter = result print("Filecounter received: ", filecounter) else: exit() while True: size = 16 if (left // size): sent = size else: sent = left % size bytes_read = encrypted_data[counter * size:counter * size + size] if len(bytes_read) != 0 and len(bytes_read) != 16: bytes_read += b'\x00' * (16 - len(bytes_read)) if len(bytes_read) == 0: # break when there's nothing to be sent break if shamir_on: shares = Shamir.split(2, 3, bytes_read) for ctr, (idx, share) in enumerate(shares): packet = bytearray() packet.extend(bytearray((counter).to_bytes(4, 'big'))) packet.extend(bytearray((idx).to_bytes(4, 'big'))) packet.extend(bytearray((filecounter).to_bytes(4, 'big'))) packet.extend(bytes_read) sockets[ctr].sendall(packet) else: packet = bytearray() idx = 10 # Random value for shamir on/off check on the receiver end packet.extend(bytearray((counter).to_bytes(4, 'big'))) packet.extend(bytearray((idx).to_bytes(4, 'big'))) packet.extend(bytearray((filecounter).to_bytes(4, 'big'))) packet.extend(bytes_read) ctr = random.randint(0, 2) sockets[ctr].sendall(packet) left -= (sent) # update amount of data that will be sent counter += 1 for socket in sockets: socket.close()
def generateKeyShares(self, key): return Shamir.split(self.F + 1, self.N, key)
return (ciphertext, aes_cipher.nonce, auth_tag) def decrypt_AES_GCM(encrypted_msg, secret_key): (ciphertext, nonce, auth_tag) = encrypted_msg aes_cipher = AES.new(secret_key, AES.MODE_GCM, nonce) plaintext = aes_cipher.decrypt_and_verify(ciphertext, auth_tag) return plaintext message = b'a message to sign via AES-GCM' secret_key = get_random_bytes(16) print(f'Secret key:\n\t{binascii.hexlify(secret_key)}') shares = Shamir.split(2, 5, secret_key) print('Shared keys:') for idx, share in shares: print(f'\t{binascii.hexlify(share)} ({idx})') encrypted_msg = encrypt_AES_GCM(message, secret_key) print('Encrypted message and parameters:') print(f'\tAES with Galois/Counter Mode (GCM)') print(f'\t{binascii.hexlify(encrypted_msg[0])} (ciphertext)') print(f'\t{binascii.hexlify(encrypted_msg[1])} (nonce)') print(f'\t{binascii.hexlify(encrypted_msg[2])} (auth_tag)') combined_secret_key = Shamir.combine([shares[2], shares[4]]) decrypted_msg = decrypt_AES_GCM(encrypted_msg, combined_secret_key) print('Decrypted message:') print(f'\t{decrypted_msg}')
def main(): r = requests.Session() # get salt and B value shares = [] for username in gen_db.NAMES: # manually regenerate A value a = server.gen_seed() #A = server.modular_pow(g, a, N) A = server.N * 3 resp = r.post(URL, data={"username": username, "token1": A}).json() salt = resp.get("nacl") B = resp.get("token2") print(username) # generate u u = server.hasher(str(A) + str(B)) x = server.hasher(salt + password) # compute S and K #S = server.modular_pow(B - k * server.modular_pow(g, x, N), a + u * x, N) S = hex(0)[2:] K = hashlib.sha256(S.encode()).digest() # Compute HMAC hm = server.hmac_sha256(K, salt.encode()) # validate and retrieve the share resp = r.post(URL, data={"username": username, "computed": hm}).text if "Incorrect" in resp: print("Failed") return 1 # parse out share share = resp.splitlines()[-7].replace(" ", "").replace("<td>", "").replace( "</td>", "") print(share) # append to reconstruct share = share.split(":") shares += [(int(share[0]), binascii.unhexlify(share[1]))] # reconstruct secret to file with shares key = Shamir.combine(shares) print(key) # decrypt encrypted file with reconstructed secret with open("encrypted.txt", "rb") as fd: ctstr = str(fd.read().decode()).split(":") iv = binascii.unhexlify(ctstr[1]) ct = binascii.unhexlify(ctstr[2]) cipher = AES.new(key, AES.MODE_CBC, iv) result = cipher.decrypt(ct) print(result)
def test5(self): # Detect duplicate shares secret = unhexlify(b("000102030405060708090a0b0c0d0e0f")) shares = Shamir.split(2, 3, secret) self.assertRaises(ValueError, Shamir.combine, (shares[0], shares[0]))
def reconstruct_secret(shares): return Shamir.combine(shares)
def generate_shares(secret): return Shamir.split(3, 6, secret)
def test2(self): # Test recombine from itertools import permutations test_vectors = ( (2, "d9fe73909bae28b3757854c0af7ad405", "1-594ae8964294174d95c33756d2504170", "2-d897459d29da574eb40e93ec552ffe6e", "3-5823de9bf0e068b054b5f07a28056b1b", "4-db2c1f8bff46d748f795da995bd080cb"), (2, "bf4f902d9a7efafd1f3ffd9291fd5de9", "1-557bd3b0748064b533469722d1cc7935", "2-6b2717164783c66d47cd28f2119f14d0", "3-8113548ba97d58256bb4424251ae300c", "4-179e9e5a218483ddaeda57539139cf04"), (3, "ec96aa5c14c9faa699354cf1da74e904", "1-64579fbf1908d66f7239bf6e2b4e41e1", "2-6cd9428df8017b52322561e8c672ae3e", "3-e418776ef5c0579bd9299277374806dd", "4-ab3f77a0107398d23b323e581bb43f5d", "5-23fe42431db2b41bd03ecdc7ea8e97ac"), (3, "44cf249b68b80fcdc27b47be60c2c145", "1-d6515a3905cd755119b86e311c801e31", "2-16693d9ac9f10c254036ced5f8917fa3", "3-84f74338a48476b99bf5e75a84d3a0d1", "4-3fe8878dc4a5d35811cf3cbcd33dbe52", "5-ad76f92fa9d0a9c4ca0c1533af7f6132"), (5, "5398717c982db935d968eebe53a47f5a", "1-be7be2dd4c068e7ef576aaa1b1c11b01", "2-f821f5848441cb98b3eb467e2733ee21", "3-25ee52f53e203f6e29a0297b5ab486b5", "4-fc9fb58ef74dab947fbf9acd9d5d83cd", "5-b1949cce46d81552e65f248d3f74cc5c", "6-d64797f59977c4d4a7956ad916da7699", "7-ab608a6546a8b9af8820ff832b1135c7"), (5, "4a78db90fbf35da5545d2fb728e87596", "1-08daf9a25d8aa184cfbf02b30a0ed6a0", "2-dda28261e36f0b14168c2cf153fb734e", "3-e9fdec5505d674a57f9836c417c1ecaa", "4-4dce5636ae06dee42d2c82e65f06c735", "5-3963dc118afc2ba798fa1d452b28ef00", "6-6dfe6ff5b09e94d2f84c382b12f42424", "7-6faea9d4d4a4e201bf6c90b9000630c3"), (10, "eccbf6d66d680b49b073c4f1ddf804aa", "01-7d8ac32fe4ae209ead1f3220fda34466", "02-f9144e76988aad647d2e61353a6e96d5", "03-b14c3b80179203363922d60760271c98", "04-770bb2a8c28f6cee89e00f4d5cc7f861", "05-6e3d7073ea368334ef67467871c66799", "06-248792bc74a98ce024477c13c8fb5f8d", "07-fcea4640d2db820c0604851e293d2487", "08-2776c36fb714bb1f8525a0be36fc7dba", "09-6ee7ac8be773e473a4bf75ee5f065762", "10-33657fc073354cf91d4a68c735aacfc8", "11-7645c65094a5868bf225c516fdee2d0c", "12-840485aacb8226631ecd9c70e3018086"), (10, "377e63bdbb5f7d4dc58a483d035212bb", "01-32c53260103be431c843b1a633afe3bd", "02-0107eb16cb8695084d452d2cc50bc7d6", "03-df1e5c66cd755287fb0446faccd72a06", "04-361bbcd5d40797f49dfa1898652da197", "05-160d3ad1512f7dec7fd9344aed318591", "06-659af6d95df4f25beca4fb9bfee3b7e8", "07-37f3b208977bad50b3724566b72bfa9d", "08-6c1de2dfc69c2986142c26a8248eb316", "09-5e19220837a396bd4bc8cd685ff314c3", "10-86e7b864fb0f3d628e46d50c1ba92f1c", "11-065d0082c80b1aea18f4abe0c49df72e", "12-84a09430c1d20ea9f388f3123c3733a3"), ) def get_share(p): pos = p.find('-') return int(p[:pos]), unhexlify(p[pos + 1:]) for tv in test_vectors: k = tv[0] secret = unhexlify(tv[1]) max_perms = 10 for perm, shares_idx in enumerate( permutations(range(2, len(tv)), k)): if perm > max_perms: break shares = [get_share(tv[x]) for x in shares_idx] result = Shamir.combine(shares, True) self.assertEqual(secret, result)
import random from Crypto.Protocol.SecretSharing import Shamir as shamir msg = 'ABCDGERT23456780' msg = msg.encode('utf-8') shares = shamir.split(3, 6, msg, ssss=True) print(shares) pool_1 = random.sample(shares, 3) pool_2 = random.sample(shares, 2) pool_3 = random.sample(shares, 4) tmp = [] count = 1 for i in pool_3: shit = (count, i[1]) tmp.append(shit) count = count + 1 remake_1 = shamir.combine(pool_1) remake_2 = shamir.combine(pool_2) remake_3 = shamir.combine(pool_3) remake_4 = shamir.combine(tmp) what = [] for i in pool_1: add = str(i[0]).encode('utf-8') + ' '.encode('utf-8') + i[1] what.append(add) for i in what: # print(len(i[2:])) print(int(i[0:1])) print(remake_1, remake_2) print(type(shares[1]))
("08", "04ed6f6bf5ec8c8c2a4d18dcce04ae48"), ("09", "430ad338b7b603d1770f94580f23cb38"), ("10", "d51669551515b6d31ce3510de343370f"), ("11", "b303ee7908dcbc07b8e9dac7e925a417"), ("12", "3c4a692ad1b13e27886e2b4893f8d761"), ("13", "a8e53ef9ee51cf682f621cb4ea0cb398"), ("14", "feb294f9380c462807bb3ea0c7402e12"), ("15", "9b2b15a72430189048dee8e9594c9885"), ("16", "f4d52e11f6f9b2a4bfbe23526160fdfd"), ("17", "d0f902472175a3f2c47a88b3b3108bb2"), ("18", "cc29eb96af9c82ab0ba6263a6e5a3768"), ("19", "913227d2d7e1a01b4ec52ff630053b73"), ("20", "8669dd2b508c2a5dfd24945f8577bd62")] shares = [(int(idx, 10), bytes.fromhex(h)) for (idx, h) in data] key = Shamir.combine(shares) print(key) # cbc:254dc5ae7bb063ceaf3c2da953386948:08589c6b40ab64c434064ec4be41c9089eefc599603bc7441898c2e8511d03f6 cipher = AES.new(key, AES.MODE_CBC, iv=bytes.fromhex("254dc5ae7bb063ceaf3c2da953386948")) pt = cipher.decrypt( bytes.fromhex( "08589c6b40ab64c434064ec4be41c9089eefc599603bc7441898c2e8511d03f6")) print(pt) # b'_z3r0_kn0wl3dg3_' # b'flag{n0t_s0_s3cur3_4ft3r_4ll}\n\x00\x00'
# from binascii import hexlify # from Crypto.Cipher import AES # from Crypto.Random import get_random_bytes # from Crypto.Protocol.SecretSharing import Shamir # # # message = '我是大帅哥!' # key = message.encode('utf-8') # print(key) # shares = Shamir.split(2, 5, key) # for idx, share in shares: # print("Index #%d: %s" % (idx, hexlify(share))) from binascii import hexlify from Crypto.Cipher import AES from Crypto.Random import get_random_bytes from Crypto.Protocol.SecretSharing import Shamir #from sss import Shamir message = '我是大帅哥!' key = message.encode('utf-8') print(key) shares = Shamir.split(2, 5, key) for idx, share in shares: print("Index #%d: %s" % (idx, hexlify(share)))
def udp_receiver(): global port, broadcast_hash, priv_key, dbf, old_hash new_contact_list = {} dbf.restart() # create socket server_socket = socket(AF_INET, SOCK_DGRAM) # UDP server_socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) server_socket.bind(("", port)) print("Waiting to receive shares from other devices...") print() while True: # receive message recv_msg, _ = server_socket.recvfrom(2048) recv_index, recv_share, recv_hash = recv_msg.decode("utf-8").split("|") # skip if receive own message if recv_hash == broadcast_hash or recv_hash == old_hash: continue else: # recv_index recv_index = int(recv_index) # recv_share recv_share = unhexlify(recv_share.encode()) if recv_hash not in new_contact_list.keys(): new_contact_list[recv_hash] = [(recv_index, recv_share)] else: new_contact_list[recv_hash].append((recv_index, recv_share)) # keep track of number of recv_shares received num_recv_shares = len(new_contact_list[recv_hash]) # print() print(f"[TASK 3B/3C] Received {num_recv_shares} recv_shares for {recv_hash}.") print() # Check if the hash contains 3 entries if num_recv_shares == 3: sec = Shamir.combine(new_contact_list[recv_hash]) print() print(f"[TASK 4A] Reconstructing EphID: {hexlify(sec)}") print("[TASK 4B] Verifying integrity of EphID...") new_hash = sha256(sec).hexdigest() print() print(f"Received hash: {recv_hash}") print(f"Recontructed hash: {new_hash}") print() if recv_hash == new_hash: print("Verified hash. Computing EncID...") enc_id = int(hexlify(sec), 16) * priv_key print(f"[TASK 5A/5B] EncID is: {enc_id}") print("[TASK 6] Adding EncID to DBF and deleting EncID...") dbf.add(str(enc_id)) print() print(f"[TASK 7A] Current state of DBF: {dbf.get_indices()}") print() else: print("Error: Hash not verified.") print()
from Crypto.Protocol.SecretSharing import Shamir from Crypto import Random from Crypto.Random import get_random_bytes text = 'hello world' password = input("Type ascii") print("it is....") for ch in text: print(ord(ch), end="") #print(str(ch), end='') for k in password: d = [] d.append(k) s = list(enumerate(d, start=0)) iv = [get_random_bytes(d) for x in range(2)] res = Shamir.split(2, 5, iv) #print (ord(k)) print(res) #print(d[:])
def handle(self): global MESSAGE_LIST, COMBINER_RUNNING, IP_FILE_LIST print("Combiner Running...") # begin = time.time() for ip_addr in list(MESSAGE_LIST): for filecounter in list(MESSAGE_LIST[ip_addr]): total_count = IP_FILE_LIST[ip_addr]['files'][filecounter][ 'filesize'] // 16 + 1 ### TIMING ### combine_start_timestamp = time.time() IP_FILE_LIST[ip_addr]['files'][filecounter][ 'combine_start'] = combine_start_timestamp IP_FILE_LIST[ip_addr]['files'][filecounter][ 'combiner_started'] = True ### TIMING ### for counter in list(MESSAGE_LIST[ip_addr][filecounter]): if counter != 'combined_count': if 'combined' not in MESSAGE_LIST[ip_addr][ filecounter][counter].keys() and len( MESSAGE_LIST[ip_addr][filecounter][counter] ["msgs"]) >= 2: shares = MESSAGE_LIST[ip_addr][filecounter][ counter]["msgs"] combined = Shamir.combine(shares) if counter + 1 == total_count: combined = combined[:IP_FILE_LIST[ip_addr][ 'files'][filecounter]['filesize'] % 16] MESSAGE_LIST[ip_addr][filecounter][counter][ 'combined'] = combined if 'combined_count' not in MESSAGE_LIST[ip_addr][ filecounter].keys(): MESSAGE_LIST[ip_addr][filecounter][ 'combined_count'] = 1 else: MESSAGE_LIST[ip_addr][filecounter][ 'combined_count'] += 1 IP_FILE_LIST[ip_addr]['files'][filecounter][ 'combine_status'] = f"{MESSAGE_LIST[ip_addr][filecounter]['combined_count']}/{total_count - 1}" ### TIMING ### combine_end_timestamp = time.time() IP_FILE_LIST[ip_addr]['files'][filecounter][ 'combine_end'] = combine_end_timestamp time_diff = ("%.4gs" % (combine_end_timestamp - combine_start_timestamp)) IP_FILE_LIST[ip_addr]['files'][filecounter][ 'combine_timespent'] = time_diff ### TIMING ### # print("MESSAGE LIST: ", MESSAGE_LIST) for ip_addr in list(MESSAGE_LIST): for filecounter in list(MESSAGE_LIST[ip_addr]): if IP_FILE_LIST[ip_addr]['files'][filecounter][ 'filesize'] % 16 != 0: total_count = IP_FILE_LIST[ip_addr]['files'][filecounter][ 'filesize'] // 16 + 1 else: total_count = IP_FILE_LIST[ip_addr]['files'][filecounter][ 'filesize'] // 16 if 'combined_count' in MESSAGE_LIST[ip_addr][filecounter].keys( ): # print(MESSAGE_LIST) # print("_________________________\n\n") # print(IP_FILE_LIST) # print(MESSAGE_LIST[ip_addr][filecounter]['combined_count'], total_count) # print(MESSAGE_LIST) # print("CHECK\n\n") # print(MESSAGE_LIST[ip_addr][filecounter]['combined_count'], total_count) # print("\n") if MESSAGE_LIST[ip_addr][filecounter][ 'combined_count'] == total_count: total_bytes = bytearray() for i in range(total_count): total_bytes.extend(MESSAGE_LIST[ip_addr] [filecounter][i]['combined']) IP_FILE_LIST[ip_addr]['files'][filecounter][ 'combined'] = True # print(total_bytes) plaintext, header = decrypt_message( total_bytes, DH_KEYS[ip_addr]['SHARED_KEY']) print(f"[+] Writing to file...") with open( os.path.join( RECEIVE_PATH, IP_FILE_LIST[ip_addr] ['files'][filecounter]['filename']), "wb") as f: f.write(plaintext) del (MESSAGE_LIST[ip_addr][filecounter]) # print("MESSAGE LIST AFTER DELETION: ", MESSAGE_LIST) ### TIMING ### dec_end_timestamp = time.time() IP_FILE_LIST[ip_addr]['files'][filecounter][ 'decrypt_end'] = dec_end_timestamp time_diff = ("%.4gs" % (dec_end_timestamp - IP_FILE_LIST[ip_addr] ['files'][filecounter]['combine_start'])) IP_FILE_LIST[ip_addr]['files'][filecounter][ 'decrypt_timespent'] = time_diff ### TIMING ### # end = time.time() with lock: COMBINER_RUNNING = False