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 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 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 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 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 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 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 _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 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 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 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 generateKeyShares(self, key): return Shamir.split(self.F + 1, self.N, key)
def generate_shares(secret): return Shamir.split(3, 6, secret)
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]))
# 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 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()
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}')
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[:])
pt += "x" return (pt) print( "\nHuiHui Industries is on a hiring spree of freshers for the role of a true Assistant to the Network Administrator." ) print("Their test is very basic. Wanna try?\n") flag = "xxxxx cjumz evlz{Y0u_4r3_h1r3d}ctf fwmadug " key = "huiRandom_Keyhui".encode() cipher = aes.new(key, aes.MODE_ECB) encrypted_flag = binascii.hexlify(cipher.encrypt(pad(flag).encode())).decode() n = random.randint(20, 24) shares = Shamir.split(19, n, key, ssss=True) score = 0 for i in range(n): cipher = aes.new(shares[i][1], aes.MODE_ECB) random_pt = PTs[random.randint(0, 24)] encrypted_random_pt = binascii.hexlify( cipher.encrypt(pad(random_pt).encode())).decode() ED = random.randint(0, 1) if ED == 0: print("haiyaa! Encrypt this: ") print(random_pt) print("using:", binascii.hexlify(shares[i][1]).decode())