def _default_encryption_padding(): return asym_padding.OAEP(mgf=asym_padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)
def Main(): global cryptokeys, bitcommits, selfcommit, pseudonym, server_session_key, client_keys, server_pub_key, play_order with open('server_public_key', 'rb') as kf: server_pub_key = serialization.load_pem_public_key( kf.read(), default_backend()) global s s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((addr, port)) except ConnectionRefusedError: print("Error! The server is not online!") return server_session_key, iv, dh_a = server_handshake() crypto.init(crypto.get_bytes(iv)) signature = b'' cert_pem = b'' if not test: pkcs11 = PyKCS11.PyKCS11Lib() if path.exists("/usr/local/lib/libpteidpkcs11.so"): pkcs11.load('/usr/local/lib/libpteidpkcs11.so') else: pkcs11.load('/usr/lib/libpteidpkcs11.so') slots = pkcs11.getSlotList() found_cc = False for slot in slots: if 'CARTAO DE CIDADAO' in pkcs11.getTokenInfo(slot).label: found_cc = True session = pkcs11.openSession(slot) privKey = session.findObjects([ (CKA_CLASS, CKO_PRIVATE_KEY), (CKA_LABEL, 'CITIZEN AUTHENTICATION KEY') ])[0] certificate = session.findObjects( template=[(PyKCS11.CKA_LABEL, "CITIZEN AUTHENTICATION CERTIFICATE" ), (PyKCS11.CKA_CLASS, PyKCS11.CKO_CERTIFICATE)])[0] all_attr = [ e for e in list(PyKCS11.CKA.keys()) if isinstance(e, int) ] attr = session.getAttributeValue(certificate, all_attr) attr = dict(zip(map(PyKCS11.CKA.get, all_attr), attr)) cert_der = x509.load_der_x509_certificate( bytes(attr['CKA_VALUE']), default_backend()) cert_pem = cert_der.public_bytes(Encoding.PEM) while True: pseudonym = 'steve' + str(randint(00000000, 99999999)) send({ 'type': messages.REGISTER_REQUEST, 'sig': bytes( session.sign(privKey, bytes(pseudonym, 'utf-8'), Mechanism(CKM_SHA1_RSA_PKCS))).hex(), 'name': pseudonym }) data = receive() if data['type'] != messages.REGISTER_REPLY: raise UnexpectedMessageException() if data['accepted']: break session.closeSession() if not found_cc: print("\nNo citizenship card connected") return # If Test mode is enabled else: while True: pseudonym = 'steve' + str(randint(00000000, 99999999)) send({ 'type': messages.REGISTER_REQUEST, 'sig': signature.hex(), 'name': pseudonym }) data = receive() if data['type'] != messages.REGISTER_REPLY: raise UnexpectedMessageException() if data['accepted']: break print("Hi I am {}".format(pseudonym)) while True: try: print("Starting new game...") cryptokeys = {} # Ci: Ki bitcommits = {} selfcommit = None client_keys = None play_order, client_keys = clients_handshake(dh_a) numPlayers = len(play_order) data = receive() if data['type'] != messages.RANDOMIZATION_REQUEST: raise UnexpectedMessageException() # --- ENCRYPTION/RANDOMIZATION new_tiles = [] for i, tile in enumerate(data['tiles']): if not isinstance(tile, str): tile = crypto.get_string(str(tile).encode('utf-8')) btile = crypto.get_bytes(tile) collision = True key = None while collision: key = crypto.get_key() cr = crypto.encrypt(btile, key) collision = cr in cryptokeys cryptokeys[cr] = key data['tiles'][i] = crypto.get_string(cr) secret_s = secrets.SystemRandom() secret_s.shuffle(data['tiles']) hand_size = data['tile_num'] final_stocksize = len(data['tiles']) - numPlayers * hand_size next_player = play_order[(play_order.index(pseudonym) + 1) % numPlayers] players_without_self = play_order.copy() players_without_self.pop(players_without_self.index(pseudonym)) randomization_reply = { 'type': messages.RANDOMIZATION_REPLY, 'tiles': data['tiles'] } send(randomization_reply) pseudo_hand = [] data = receive() setup = True # --- SELECTION while setup: if data['type'] != messages.ROUTING and data[ 'type'] != messages.SELECTION_REQUEST and data[ 'type'] != messages.SELECTION_END: raise UnexpectedMessageException() else: if data['type'] == messages.SELECTION_END: if len(pseudo_hand) < hand_size: print( "\nSelection ended before hand was complete. Deck distribution cheating occured!" ) send({'type': messages.COMPLAIN, 'cheater': None}) data = receive() else: setup = False send({'type': messages.OK}) break else: tiles = [] picked = [] if data['type'] == messages.ROUTING: if data['data']['type'] != messages.SELECTION_REPLY: raise UnexpectedMessageException() tiles = data['data']['tiles'] picked = data['data']['picked'] else: tiles = data['tiles'] picked = data['picked'] if len(tiles) == final_stocksize or ( randint(0, 99) < prob_deck_cheating and randint(0, 99) < 50 ): # second randint servers to have even smaller probability action = randint(0, 99) if (action < prob_select_end): setup = False selection_end = { 'type': messages.SELECTION_REPLY, 'tiles': tiles, 'picked': picked } send(selection_end) break action = randint(0, 99) if action < prob_pick_tile and len( pseudo_hand) < hand_size: tile_choice = randint(0, len(tiles) - 1) pic_tile = tiles.pop(tile_choice) pseudo_hand.append(pic_tile) picked.append(pic_tile) else: action = randint(0, 99) if action < prob_swap_tiles and len( pseudo_hand) > 0: number_of_swaps = randint(1, len(pseudo_hand)) for i in range(number_of_swaps): tile_choice = randint(0, len(tiles) - 1) temp_tile = pseudo_hand.pop(i) picked.remove(temp_tile) pic_tile = tiles.pop(tile_choice) pseudo_hand.insert(i, pic_tile) picked.append(pic_tile) tiles.insert(tile_choice, temp_tile) player_selection = randint( 0, len(players_without_self) - 1) selection_reply = { 'type': messages.ROUTING, 'destination': players_without_self[player_selection], 'data': { 'type': messages.SELECTION_REPLY, 'tiles': tiles, 'picked': picked } } send(selection_reply) data = receive() # --- COMMIT index_hand = pseudo_hand.copy() while len(bitcommits) < numPlayers: data = receive() if data['type'] == messages.COMMIT_REQUEST: selfcommit = commit(pseudo_hand) send({ 'type': messages.COMMIT_REPLY, 'commit': selfcommit, 'sig': rsa_priv.sign( hashlib.sha256(bytes.fromhex(selfcommit)).digest(), padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()).hex() }) stock = data['stock'] pseudo_hand = [ crypto.get_bytes(data['deck'][t_ix]) for t_ix in pseudo_hand ] bitcommits[str(pseudonym)] = None #self commit print("Sent my bit commitment {}".format(selfcommit)) elif data['type'] == messages.COMMIT_FORWARD: bitcommits[play_order[data['player']]] = data['commit'] print("Received bit commitment {} from player {}".format( data['commit'], play_order[data['player']])) send({'type': messages.OK}) else: raise UnexpectedMessageException() for i, t in enumerate(stock): stock[i] = crypto.get_bytes(t) # --- DECRYPTION new_crypts = {} while True: data = receive() if data['type'] != messages.REVELATION_REQUEST: raise UnexpectedMessageException() if data['reveal']: to_send = {} for tile, key in cryptokeys.items(): if (new_crypts != {} and tile in new_crypts.values( )) or ( new_crypts == {} and tile not in stock ): # if first to decrypt, tile not in stock, else new_crypts has stuff in it t_str = crypto.get_string(tile) k_str = crypto.get_string(key) to_send[t_str] = k_str for i, tile in enumerate(pseudo_hand): dec = crypto.decrypt(tile, cryptokeys[tile]) pseudo_hand[i] = dec send({'type': messages.REVELATION_REPLY, 'keys': to_send}) else: new_crypts = {} for crypt, key in data['keys'].items(): crypt = crypto.get_bytes(crypt) key = crypto.get_bytes(key) dec = crypto.decrypt(crypt, key) new_crypts[crypt] = dec try: ix = pseudo_hand.index(crypt) pseudo_hand[ ix] = dec # client uses received keys to "decrypt" hand except ValueError as e: pass send({'type': messages.OK}) if data['end']: break pseudo_hand = [ ast.literal_eval(t.decode('utf-8')) for t in pseudo_hand ] # --- DE-ANON de_anon = True my_private_keys = [] #missing_keys = [t[1] for t in pseudo_hand] missing_keys = index_hand.copy() while de_anon: data = receive() if data['type'] == messages.DE_ANON_REQUEST: break elif data['type'] != messages.ROUTING and data[ 'type'] != messages.DE_ANON_PREP_REQUEST: raise UnexpectedMessageException() else: key_array = [] if data['type'] == messages.ROUTING: if data['data']['type'] != messages.DE_ANON_PREP_REPLY: raise UnexpectedMessageException() key_array = data['data']['array'] else: key_array = data['array'] if key_array.count('0' * 852) <= final_stocksize: action = randint(0, 99) if action < prob_end_deanon: selection_reply = { 'type': messages.DE_ANON_PREP_REPLY, 'array': key_array } send(selection_reply) continue action = randint(0, 99) if action < prob_add_keys and len(missing_keys) > 0: key_choice = randint(0, len(missing_keys) - 1) chosen_key = missing_keys.pop(key_choice) key_array.pop(chosen_key) priv_key, pub_key = crypto.generate_RSA_keys() my_private_keys.append([chosen_key, priv_key]) key_array.insert(chosen_key, pub_key.hex()) cheating_key = randint(0, 27) if randint( 0, 99) < prob_deck_cheating and cheating_key not in ( [a[0] for a in my_private_keys] + missing_keys): priv_key, pub_key = crypto.generate_RSA_keys() key_array.pop(cheating_key) key_array.insert(cheating_key, pub_key.hex()) player_selection = randint(0, len(players_without_self) - 1) selection_reply = { 'type': messages.ROUTING, 'destination': players_without_self[player_selection], 'data': { 'type': messages.DE_ANON_PREP_REPLY, 'array': key_array } } send(selection_reply) if data['type'] != messages.DE_ANON_REQUEST: raise UnexpectedMessageException() encrypted_deck = data['array'] current_hand = [] ki_values = [] try: for i in range(len(my_private_keys)): tmp = ast.literal_eval(my_private_keys[i][1].decrypt( bytes.fromhex(encrypted_deck[my_private_keys[i][0]]), padding.OAEP(padding.MGF1(hashes.SHA256()), hashes.SHA256(), None)).decode('utf-8')) ki_values.append(tmp[0]) current_hand.append(tmp[1]) # Verify hand for i in range(len(current_hand)): try: pseudo = h(ki_values[i], current_hand[i]) except: ValueError() if pseudo not in [a[0] for a in pseudo_hand]: raise ValueError() except ValueError: print( "\nCould not de-anonimize deck. Deck distribution cheating occured!" ) send({'type': messages.COMPLAIN, 'cheater': None}) data = receive() send({'type': messages.OK}) game = Logic(numPlayers, hand_size) drawing = False drawn_tile = None stock_empty = len(stock) <= 0 option = 0 while True: data = receive() if data['type'] == messages.CONFIRM_ACTION: #Send OK, opponent played if data['action']['ac'] == 'draw': rec_tile = crypto.get_bytes(data['action']['tile']) send({'type': messages.OK}) stock.remove(rec_tile) drawProcess(False, rec_tile) stock_empty = len(stock) <= 0 else: print( "Opponent", play_order[data['player']], "played", str(data['action']['tile']) + "!") if data['action']['ac'] == 'play' else print( "Opponent", play_order[data['player']], "passed!") game.playTile( data['action']['tile'], data['action']['right'] ) if data['action']['ac'] == 'play' else game.playPass( ) send( protesting.checkForDuplicatedTiles( game, current_hand, play_order)) #Pos Validation elif data[ 'type'] == messages.ACTION_REQUEST: #Send ACTION_REPLY, this client played print("I'm playing with current hand:", current_hand) tileToPlay = game.chooseValidTile(current_hand) if tileToPlay == None: cheating_chance = randint(0, 99) if cheating_chance < prob_cheat: #Cheating chance = 20% send(cheating.cheatingWithRandomTile(game)) elif not stock_empty: if False and cheating_chance < prob_cheat: print("Fake Pass like Ronaldinho Gaúcho") send(game.playPass()) else: print("No valid play found, gib tile") print(len(stock) - 1) tile_choice = randint(0, len(stock) - 1) drawn_tile = stock.pop(tile_choice) send( game.playDraw( crypto.get_string(drawn_tile))) drawing = True else: print("Passing...") send(game.playPass()) else: send({ 'type': messages.ACTION_REPLY, 'action': { 'ac': 'play', 'tile': tileToPlay[0], 'right': tileToPlay[1] } }) elif data['type'] == messages.OK: if drawing: #This client requested a piece from stock, once all players validate his request, they will enter draw process new_tile = drawProcess(True, drawn_tile) current_hand.append(new_tile) drawing = False draw_tile = None stock_empty = len(stock) <= 0 #stock_empty = True #for testing purposes elif tileToPlay != None: #This client's play validated, removing tile game.playTile(tileToPlay[0], tileToPlay[1]) current_hand.remove(tileToPlay[0]) elif data[ 'type'] == messages.INITIAL_HAND_REQUEST: #Someone complained about cheating!! send({ 'type': messages.INITIAL_HAND_REPLY, 'initial_hand': index_hand }) elif data[ 'type'] == messages.COMMIT_VALIDATION_REQUEST: #Comparison between initial and final bit commits print( "\n\nGame {}! Proceeding to validate everyone's bit commitments for the game recap.\n" .format( "aborted because there was a suspicion of cheating" if data['cheating'] else "finished successfully")) #Generate bit commitment from the data that originated the initial one finalBitcommits = {} for player, hand in data['initial_hands'].items(): if str(player) == str(pseudonym): continue dk = hashlib.sha256() for t in hand: dk.update(t.to_bytes(1, 'big')) finalBitcommits[player] = dk.hexdigest() #Compare both bit commitments for initPlayer, initCommit in bitcommits.items(): for finalPlayer, finalCommit in finalBitcommits.items( ): if str(initPlayer) == str(pseudonym): continue if str(initPlayer) == str(finalPlayer): print( "Comparing initial bit commitment with data sent from {}..." .format(initPlayer), end=" ") if initCommit != finalCommit: print( "\nCould NOT validate {}'s bit commitment! Player sent wrong data" .format(initPlayer)) #Punish player else: print("Validated!".format(initPlayer)) send({'type': messages.OK}) elif data['type'] == messages.POINTS_VALIDATION_REQUEST: print() clientPoints = countPoints(data['final_hands'], data['cheaters'], data['penalty']) for player in clientPoints.keys(): print("Comparing server's score for {}...".format( player), end=" ") if data['points'][player] != clientPoints[player]: print("\nCould NOT validate {}'s points!".format( initPlayer)) else: print("Validated!".format(initPlayer)) send({'type': messages.OK}) elif data['type'] == messages.GAME_END: option = get_end_option(0, data['points']) break except GameEndedException as gee: option = get_end_option(gee.reason, gee.points) if option == 2: claim_points = { 'type': messages.CLAIM_POINTS_REQUEST, 'certificate': cert_pem.hex() } send(claim_points) data = receive() if data['type'] != messages.CLAIM_POINTS_REPLY: raise UnexpectedMessageException() print("\nVerification " + (("confirmed.\nYou are " + data['name'] + " and have a total of " + str(data['points']) + " points.") if data['points'] is not None else "failed.")) print("Closing") # close the connection s.close() return send({"type": messages.OK}) print()
def decrypt(self, ciphertext, key): return key.decrypt( ciphertext, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
def decipher_with_private_key(self, private_key, message): return private_key.decrypt( message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
def test_rsa_padding_unsupported_oaep_sha1_ripemd160(self): assert backend.rsa_padding_supported( padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.RIPEMD160(), label=None), ) is False
def data_received(self, data): print("###SSL layer data received called!###") self.deserializer.update(data) for packet in self.deserializer.nextPackets(): #print(packet.Certs[0], packet.Certs[1], packet.Certs[2]) if isinstance(packet, PlsHello): self.incoming_cert.append(CipherUtil.getCertFromBytes(str.encode(packet.Certs[0]))) self.incoming_cert.append(CipherUtil.getCertFromBytes(str.encode(packet.Certs[1]))) self.incoming_cert.append(CipherUtil.getCertFromBytes(str.encode(packet.Certs[2]))) print("\nReceived Client Hello packet. Trying to verify issuer...") #print(packet.Certs) if self.validate(self.incoming_cert): self.nc = packet.Nonce self.m = hashlib.sha1() self.m.update(packet.__serialize__()) print("Certificate Validated. Sending Server hello!\n") self.clientnonce = packet.Nonce serverhello = PlsHello() serverhello.Nonce = 12345678 self.ns = serverhello.Nonce idcert = getIDCertsForAddr() pubkey = getCertsForAddr() root = getRootCertsForAddr() serverhello.Certs = [] serverhello.Certs.append(idcert) serverhello.Certs.append(pubkey) serverhello.Certs.append(root) srvhello = serverhello.__serialize__() print("Sent Server Hello!\n") self.m.update(srvhello) self.transport.write(srvhello) if isinstance(packet, PlsKeyExchange): print("Received Client Key Exchange. Server Server Keys\n\n") self.m.update(packet.__serialize__()) serverpriv = CipherUtil.loadPrivateKeyFromPemFile("/root/keys/server/sagar-server.key") decrypted = serverpriv.decrypt(packet.PreKey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(), label=None)) print("Decrypted Pre-Master Secret: ", decrypted) self.pkc = decrypted.decode() #==================================== #Creating Server Pre-Master serverkey = PlsKeyExchange() randomvalue = b'1234567887654321' self.pks = randomvalue.decode() serverkey.NoncePlusOne = self.clientnonce + 1 pub_key = self.incoming_cert[0].public_key() encrypted1 = pub_key.encrypt(randomvalue, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),algorithm=hashes.SHA256(), label=None)) print("Encrypted String is: ", encrypted1) serverkey.PreKey = encrypted1 skey = serverkey.__serialize__() print("Sent the Prekey to Client.\n\n") self.m.update(skey) self.transport.write(skey) if isinstance(packet, PlsHandshakeDone): print("Received Client Handshake done message.") clientdigest = packet.ValidationHash serverdigest = self.m.digest() print("Hash digest is: ", serverdigest) hdone = PlsHandshakeDone() hdone.ValidationHash = serverdigest if (serverdigest == clientdigest): print("Digest verification done!") self.key_generator() hdone_s = hdone.__serialize__() self.transport.write(hdone_s)
iqmp = rsa_crt_iqmp(p, q) dmp1 = rsa_crt_dmp1(d, p) dmq1 = rsa_crt_dmq1(d, q) public_numbers = RSAPublicNumbers(e, N) secret_key = RSAPrivateNumbers(p, q, d, dmp1, dmq1, iqmp, public_numbers).private_key( default_backend()) with open(constants.CIPHERED_PATH, 'rb') as f: print("Reading ciphered version of text...") cipheredDoc = f.read() decipheredDoc = secret_key.decrypt( cipheredDoc, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) with open("./deciphered-MANUAL.txt", 'wb') as f: print( "Saving hacked deciphered version of text in deciphered-MANUAL.txt..." ) print( "To check results, compare deciphered.txt with deciphered-MANUAL.txt" ) f.write(decipheredDoc) end = time.time() print("h4cK C0mP1et3D !") else: print("ERROR: p & q not found :(") print("Time elapsed: " + str((end - start) / 60) + " minutos")
def get_padding() -> padding.AsymmetricPadding: return padding.OAEP(padding.MGF1(hashes.SHA256()), hashes.SHA256(), None)
def main(pubpath, privpath): # generate a list of the keys to test publist = os.listdir(pubpath) privlist = os.listdir(privpath) matches = 0 if debug: print("content of publist " + str(publist)) print("content of privlist " + str(privlist)) for pub in publist: with open(pubpath + '/' + pub, 'rb') as pubfile: pubdata = pubfile.read() pubfile.close() if debug: print("pubdata " + str(pubdata)) try: pubkey = serialization.load_ssh_public_key(pubdata,\ backends.default_backend()) except: try: pubkey = serialization.load_pem_public_key(pubdata,\ backends.default_backend()) except: print("Wrong keytype on " + pub) continue if debug: print("pubkey: " + str(pub)) pad= padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),\ algorithm=hashes.SHA1(),\ label=None) for priv in privlist: with open(privpath + '/' + priv, 'rb') as privfile: privdata = privfile.read() privfile.close() if debug: print("privdata " + str(privdata)) try: privkey = serialization.load_pem_private_key(privdata,\ None, backends.default_backend()) except: print("Wrong keytype on " + priv) privlist.remove(priv) continue if debug: print("privkey: " + str(privkey)) msg = pubkey.encrypt(b"True", pad) try: privkey.decrypt(msg, pad) print("Match: " + pubpath + "/" + pub + " " + privpath +\ "/" + priv) matches += 1 except ValueError: pass print("Total number of matches: " + str(matches)) print("Nr of public keys: " + str(len(publist))) print("Nr of private keys: " + str(len(privlist)))
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.asymmetric import padding DEFAULT_PEM = './assets/private.pem' DEFAULT_PADDING = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None) class Crypto: pem_file = DEFAULT_PEM def __init__(self, pem_file=None): self._pem_file = pem_file or DEFAULT_PEM with open(self.pem_file, "rb") as key_file: self._private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) @property def _public_key(self): return self._private_key.public_key() def encrypt(self, text): return self._public_key.encrypt(text.encode(), DEFAULT_PADDING) def decrypt(self, text): return self._private_key.decrypt(text, DEFAULT_PADDING).decode()
def create(self, key, public_key_format, enckey, dependencies=None, sw_type=None): self.enckey = enckey # Calculate the hash of the public key if key is not None: pub = key.get_public_bytes() sha = hashlib.sha256() sha.update(pub) pubbytes = sha.digest() else: pubbytes = bytes(hashlib.sha256().digest_size) protected_tlv_size = 0 if self.security_counter is not None: # Size of the security counter TLV: header ('HH') + payload ('I') # = 4 + 4 = 8 Bytes protected_tlv_size += TLV_SIZE + 4 if sw_type is not None: if len(sw_type) > MAX_SW_TYPE_LENGTH: msg = "'{}' is too long ({} characters) for sw_type. Its " \ "maximum allowed length is 12 characters.".format( sw_type, len(sw_type)) raise click.UsageError(msg) image_version = (str(self.version.major) + '.' + str(self.version.minor) + '.' + str(self.version.revision)) # The image hash is computed over the image header, the image # itself and the protected TLV area. However, the boot record TLV # (which is part of the protected area) should contain this hash # before it is even calculated. For this reason the script fills # this field with zeros and the bootloader will insert the right # value later. digest = bytes(hashlib.sha256().digest_size) # Create CBOR encoded boot record boot_record = create_sw_component_data(sw_type, image_version, "SHA256", digest, pubbytes) protected_tlv_size += TLV_SIZE + len(boot_record) if dependencies is not None: # Size of a Dependency TLV = Header ('HH') + Payload('IBBHI') # = 4 + 12 = 16 Bytes dependencies_num = len(dependencies[DEP_IMAGES_KEY]) protected_tlv_size += (dependencies_num * 16) if protected_tlv_size != 0: # Add the size of the TLV info header protected_tlv_size += TLV_INFO_SIZE # At this point the image is already on the payload, this adds # the header to the payload as well self.add_header(enckey, protected_tlv_size) prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC) # Protected TLVs must be added first, because they are also included # in the hash calculation protected_tlv_off = None if protected_tlv_size != 0: e = STRUCT_ENDIAN_DICT[self.endian] if self.security_counter is not None: payload = struct.pack(e + 'I', self.security_counter) prot_tlv.add('SEC_CNT', payload) if sw_type is not None: prot_tlv.add('BOOT_RECORD', boot_record) if dependencies is not None: for i in range(dependencies_num): payload = struct.pack( e + 'B3x' + 'BBHI', int(dependencies[DEP_IMAGES_KEY][i]), dependencies[DEP_VERSIONS_KEY][i].major, dependencies[DEP_VERSIONS_KEY][i].minor, dependencies[DEP_VERSIONS_KEY][i].revision, dependencies[DEP_VERSIONS_KEY][i].build) prot_tlv.add('DEPENDENCY', payload) protected_tlv_off = len(self.payload) self.payload += prot_tlv.get() tlv = TLV(self.endian) # Note that ecdsa wants to do the hashing itself, which means # we get to hash it twice. sha = hashlib.sha256() sha.update(self.payload) digest = sha.digest() tlv.add('SHA256', digest) if key is not None: if public_key_format == 'hash': tlv.add('KEYHASH', pubbytes) else: tlv.add('PUBKEY', pub) # `sign` expects the full image payload (sha256 done internally), # while `sign_digest` expects only the digest of the payload if hasattr(key, 'sign'): sig = key.sign(bytes(self.payload)) else: sig = key.sign_digest(digest) tlv.add(key.sig_tlv(), sig) # At this point the image was hashed + signed, we can remove the # protected TLVs from the payload (will be re-added later) if protected_tlv_off is not None: self.payload = self.payload[:protected_tlv_off] if enckey is not None: plainkey = os.urandom(16) if isinstance(enckey, rsa.RSAPublic): cipherkey = enckey._get_public().encrypt( plainkey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) self.enctlv_len = len(cipherkey) tlv.add('ENCRSA2048', cipherkey) elif isinstance(enckey, (ecdsa.ECDSA256P1Public, x25519.X25519Public)): cipherkey, mac, pubk = self.ecies_hkdf(enckey, plainkey) enctlv = pubk + mac + cipherkey self.enctlv_len = len(enctlv) if isinstance(enckey, ecdsa.ECDSA256P1Public): tlv.add('ENCEC256', enctlv) else: tlv.add('ENCX25519', enctlv) nonce = bytes([0] * 16) cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce), backend=default_backend()) encryptor = cipher.encryptor() img = bytes(self.payload[self.header_size:]) self.payload[self.header_size:] = \ encryptor.update(img) + encryptor.finalize() self.payload += prot_tlv.get() self.payload += tlv.get() self.check_trailer()
def load_recv(self,parsed): try: lst = parsed["result"] except Exception: log(logging.ERROR,"{}\n".format(parsed["error"])) return None certificate = crypto.load_certificate(crypto.FILETYPE_PEM, lst[5].encode()) chain = [v for v in lst[6].values()] #verify the certificate try: self.cc.verify(certificate, chain) #log(logging.DEBUG, "Certificate is valid\n") except Exception as e: log(logging.ERROR, e) return None # Verify the sender's signature try: crypto.verify(certificate,base64.b64decode(lst[4]),base64.b64decode(lst[1]),"SHA256") #log(logging.DEBUG, "Signature is Valid") except Exception as e: log(logging.ERROR, e) return None try: # Decipher the symmetric key symmKey = self.private_key.decrypt(base64.b64decode(lst[2]), padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) except Exception as e: log(logging.ERROR, e) return None # Decipher the message ctr = base64.b64decode(lst[3].encode()) msg = base64.b64decode(lst[1].encode()) d_msg = AES_decrypt(symmKey,ctr,msg).decode('utf-8') #log(logging.DEBUG,"SENDER ID: {}".format(lst[0])) print("Sender ID: {}".format(lst[0])) #log(logging.DEBUG,"MESSAGE: {}".format(d_msg)) print("Message: {}".format(d_msg)) while True: save = str(input("Save message?(y/n): ")) if save == 'y': # Save deciphered message try: with open(os.path.join(self.dirname,str(lst[7])),"w") as f: f.write(d_msg) print("Message saved successfully\n") except Exception as e: log(logging.ERROR, e) # Send the receipt after reading the message self.issueReceipt(lst[7],d_msg) break elif save == 'n': print("\n") # Send the receipt after reading the message self.issueReceipt(lst[7],d_msg) break else: print("Invalid input\n")
def issueSend(self): self.enable_help = False tipo = "send" #log(logging.DEBUG, "%s" % json.dumps(tipo)) try: dst = int(input("DESTINATION ID: ")) except ValueError: log(logging.ERROR,"Destinatio ID must be a integer\n") return None msg = input("MESSAGE TO SEND: ") if msg is None: log(logging.ERROR,"Message can't be empty\n") return None # Get certificate to sign cert_name, cert_ec = self.cc.getCert(self.uuid) # Get the certificate's chain chain = self.cc.getChain(self.uuid, cert_name) for i in chain: chain[chain.index(i)] = i.decode('utf-8') # Request receiver's public key dst_pubKey = self.request_PubKey(dst) if dst_pubKey is None: return None try: # Generate a random number for the CTR mode ctr = counterMode() # Cipher the message with the the symmetric key c_msg = AES_encrypt(self.shared_key, ctr, msg) # Cipher the symmetric key with the receiver's public key c_key = dst_pubKey.encrypt(self.shared_key, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) # Create the client's signature signature = self.cc.sign(c_msg) # Cipher copy with the client's public key copy = self.public_key.encrypt(msg.encode('utf-8'), padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) except: log(logging.ERROR, "Couldn't send message, either it was too long or it didn't meet the requirements\n") # Generate a random number for the CTR mode sctr = counterMode() # Cipher the message with the session key smsg = AES_encrypt(self.session_key, sctr, json.dumps({ "type": tipo, "src": self.id, "dst": dst, "msg": base64.b64encode(c_msg).decode("utf-8"), "symkey": base64.b64encode(c_key).decode("utf-8"), "ctr": base64.b64encode(ctr).decode("utf-8"), "signature": base64.b64encode(signature).decode("utf-8"), "certificate": cert_name.decode("utf-8"), "chain": chain, "copy": base64.b64encode(copy).decode("utf-8") })+TERMINATOR) self.socket.send(base64.b64encode(smsg)+"\n".encode('utf-8')+base64.b64encode(sctr))
def create(self, key, enckey, dependencies=None, sw_type=None): self.enckey = enckey # Calculate the hash of the public key if key is not None: pub = key.get_public_bytes() sha = hashlib.sha256() sha.update(pub) pubbytes = sha.digest() else: pubbytes = bytes(hashlib.sha256().digest_size) protected_tlv_size = 0 if self.security_counter is not None: # Size of the security counter TLV: header ('HH') + payload ('I') # = 4 + 4 = 8 Bytes protected_tlv_size += TLV_SIZE + 4 if sw_type is not None: if len(sw_type) > MAX_SW_TYPE_LENGTH: msg = "'{}' is too long ({} characters) for sw_type. Its " \ "maximum allowed length is 12 characters.".format( sw_type, len(sw_type)) raise click.UsageError(msg) image_version = (str(self.version.major) + '.' + str(self.version.minor) + '.' + str(self.version.revision)) # The image hash is computed over the image header, the image # itself and the protected TLV area. However, the boot record TLV # (which is part of the protected area) should contain this hash # before it is even calculated. For this reason the script fills # this field with zeros and the bootloader will insert the right # value later. digest = bytes(hashlib.sha256().digest_size) # Create CBOR encoded boot record boot_record = create_sw_component_data(sw_type, image_version, "SHA256", digest, pubbytes) protected_tlv_size += TLV_SIZE + len(boot_record) if dependencies is not None: # Size of a Dependency TLV = Header ('HH') + Payload('IBBHI') # = 4 + 12 = 16 Bytes dependencies_num = len(dependencies[DEP_IMAGES_KEY]) protected_tlv_size += (dependencies_num * 16) if protected_tlv_size != 0: # Add the size of the TLV info header protected_tlv_size += TLV_INFO_SIZE # At this point the image is already on the payload, this adds # the header to the payload as well self.add_header(enckey, protected_tlv_size) prot_tlv = TLV(self.endian, TLV_PROT_INFO_MAGIC) # Protected TLVs must be added first, because they are also included # in the hash calculation protected_tlv_off = None if protected_tlv_size != 0: e = STRUCT_ENDIAN_DICT[self.endian] if self.security_counter is not None: payload = struct.pack(e + 'I', self.security_counter) prot_tlv.add('SEC_CNT', payload) if sw_type is not None: prot_tlv.add('BOOT_RECORD', boot_record) if dependencies is not None: for i in range(dependencies_num): payload = struct.pack( e + 'B3x' + 'BBHI', int(dependencies[DEP_IMAGES_KEY][i]), dependencies[DEP_VERSIONS_KEY][i].major, dependencies[DEP_VERSIONS_KEY][i].minor, dependencies[DEP_VERSIONS_KEY][i].revision, dependencies[DEP_VERSIONS_KEY][i].build) prot_tlv.add('DEPENDENCY', payload) protected_tlv_off = len(self.payload) self.payload += prot_tlv.get() tlv = TLV(self.endian) # Note that ecdsa wants to do the hashing itself, which means # we get to hash it twice. if self.flags != 'OTFDEC': sha = hashlib.sha256() sha.update(self.payload) digest = sha.digest() tlv.add('SHA256', digest) print("digest" + str(binascii.hexlify(digest))) if key is not None: tlv.add('KEYHASH', pubbytes) # `sign` expects the full image payload (sha256 done internally), # while `sign_digest` expects only the digest of the payload if hasattr(key, 'sign'): sig = key.sign(bytes(self.payload)) else: sig = key.sign_digest(digest) tlv.add(key.sig_tlv(), sig) # At this point the image was hashed + signed, we can remove the # protected TLVs from the payload (will be re-added later) if protected_tlv_off is not None: self.payload = self.payload[:protected_tlv_off] if enckey is not None: plainkey = os.urandom(16) #value_key=0 #plainkey = value_key.to_bytes(16, byteorder = 'little') print("aes key value" + bytes(plainkey).hex()) if isinstance(enckey, RSAPublic): cipherkey = enckey._get_public().encrypt( plainkey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) self.enctlv_len = len(cipherkey) tlv.add('ENCRSA2048', cipherkey) elif isinstance(enckey, ECDSA256P1Public): cipherkey, mac, pubk = self.ecies_p256_hkdf(enckey, plainkey) enctlv = pubk + mac + cipherkey self.enctlv_len = len(enctlv) tlv.add('ENCEC256', enctlv) address = int(self.address / 16) #address_other = 0 #nonce_other = address_other.to_bytes(8, byteorder = 'little') nonce = address.to_bytes(16, byteorder='big') #print(nonce_other) #perform 2 encryptor #encryptor_other = AES.new(plainkey, AES.MODE_CTR, nonce= nonce_other, initial_value=address); cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce), backend=default_backend()) encryptor = cipher.encryptor() img = bytes(self.payload[self.header_size:]) if self.flags == 'OTFDEC': #add bytes to reach 16 bytes print("initial len img" + hex(len(img))) toadd = (16 - len(img) % 16) img += toadd * b'0' #Swap bytes inside 16 bytes block for OTFDEC inarr = numpy.asarray(list(img), numpy.int8).reshape(-1, 16) outarr = numpy.fliplr(inarr) img = bytearray(outarr) #print("modified len img"+hex(len(img))) #encrypt image #img_other = img #encrypted = encryptor_other.encrypt(img_other) #nonce_other = encryptor_other.nonce #print("nonce encryptor"+bytes(nonce_other).hex()) #print("encrypted "+bytes(encrypted[:16]).hex()) img = encryptor.update(img) + encryptor.finalize() #print("img "+bytes(img[:16]).hex()) #img=encrypted #print("img "+bytes(img[:16]).hex()) if self.flags == 'OTFDEC': #Swap bytes inside 16 bytes block for OTFDEC inarr = numpy.asarray(list(img), numpy.int8).reshape(-1, 16) outarr = numpy.fliplr(inarr) img = bytearray(outarr) #print("modify len img"+hex(len(img))) img = img[:-toadd] #print("final len img"+hex(len(img))) #update image self.payload[self.header_size:] = img if self.flags == 'OTFDEC': # add the protected TLV self.payload += prot_tlv.get() sha = hashlib.sha256() sha.update(self.payload) digest = sha.digest() tlv.add('SHA256', digest) #print("otfdec digest"+str(binascii.hexlify(digest))) if key is not None: tlv.add('KEYHASH', pubbytes) # `sign` expects the full image payload (sha256 done internally), # while `sign_digest` expects only the digest of the payload if hasattr(key, 'sign'): sig = key.sign(bytes(self.payload)) else: sig = key.sign_digest(digest) tlv.add(key.sig_tlv(), sig) if self.flags == 'PRIMARY_ONLY' and enckey is not None: self.add_header(enckey, protected_tlv_size, True) if self.flags != 'OTFDEC': self.payload += prot_tlv.get() #add encrypted flag if image has been encrypted self.payload += tlv.get() self.check_trailer()
def decryptRSA(priv_key,ciphertext): message = priv_key.decrypt(ciphertext,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(),label=None)) return message
with open('private_key.pem','rb') as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=none, backend=default_backend() ) public_key = private_key.public_key() message=b"hello world" ciphertext=public_key.encrypt( message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), lable=None ) ) print(ciphertext) plaintext=private_key.decrypt( ciphertext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), lable=None ) ) print(plaintext)
def rsa_encrypt(key, data): return key.encrypt(data, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None))
def _get_padding(): return padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None)
def create(self, key, enckey, dependencies=None): if dependencies is None: dependencies_num = 0 protected_tlv_size = 0 else: # Size of a Dependency TLV = Header ('BBH') + Payload('IBBHI') # = 16 Bytes dependencies_num = len(dependencies[DEP_IMAGES_KEY]) protected_tlv_size = (dependencies_num * 16) + TLV_INFO_SIZE self.add_header(enckey, protected_tlv_size) tlv = TLV(self.endian) if protected_tlv_size != 0: for i in range(dependencies_num): e = STRUCT_ENDIAN_DICT[self.endian] payload = struct.pack( e + 'B3x' + 'BBHI', int(dependencies[DEP_IMAGES_KEY][i]), dependencies[DEP_VERSIONS_KEY][i].major, dependencies[DEP_VERSIONS_KEY][i].minor, dependencies[DEP_VERSIONS_KEY][i].revision, dependencies[DEP_VERSIONS_KEY][i].build) tlv.add('DEPENDENCY', payload) # Full TLV size needs to be calculated in advance, because the # header will be protected as well tlv_header_size = 4 payload_digest_size = 32 keyhash_size = 32 cipherkey_size = 32 full_size = TLV_INFO_SIZE + len(tlv.buf) + tlv_header_size \ + payload_digest_size if key is not None: full_size += tlv_header_size + keyhash_size \ + tlv_header_size + key.sig_len() if enckey is not None: full_size += tlv_header_size + cipherkey_size tlv_header = struct.pack(e + 'HH', TLV_INFO_MAGIC, full_size) self.payload += tlv_header + bytes(tlv.buf) # Note that ecdsa wants to do the hashing itself, which means # we get to hash it twice. sha = hashlib.sha256() sha.update(self.payload) digest = sha.digest() tlv.add('SHA256', digest) if key is not None: pub = key.get_public_bytes() sha = hashlib.sha256() sha.update(pub) pubbytes = sha.digest() tlv.add('KEYHASH', pubbytes) # `sign` expects the full image payload (sha256 done internally), # while `sign_digest` expects only the digest of the payload if hasattr(key, 'sign'): sig = key.sign(bytes(self.payload)) else: sig = key.sign_digest(digest) tlv.add(key.sig_tlv(), sig) if enckey is not None: plainkey = os.urandom(16) cipherkey = enckey._get_public().encrypt( plainkey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) tlv.add('ENCRSA2048', cipherkey) nonce = bytes([0] * 16) cipher = Cipher(algorithms.AES(plainkey), modes.CTR(nonce), backend=default_backend()) encryptor = cipher.encryptor() img = bytes(self.payload[self.header_size:]) self.payload[self.header_size:] = encryptor.update(img) + \ encryptor.finalize() self.payload += tlv.get()[protected_tlv_size:]
def client(): # local host IP '127.0.0.1' availability = True no_rtattempt = True ca_certificate = True no_retransmission = True no_delay = True delay_val = 0 host = str(input("Enter IP address of the device to communicate with: ")) urlp = "http://10.0.2.5:8000/getvals/" headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} # Define the port on which you want to connect port = 1234 try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # connect to server on local computer s.connect((host, port)) except OSError: print('Device unavailable') availability = False no_retransmission = False no_delay = False delay_val = 100 url = "http://10.0.2.5:8000/sendca/" data = {'ipaddress': host} headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, data=json.dumps(data), headers=headers) if (not str(r.text) == 'FileNotFound'): with open(host + '_ca.crt', 'w') as f: f.write(r.text) else: print('Certificate does not exist for secure communication') ca_certificate = False no_retransmission = False no_delay = False delay_val = 100 if (availability and ca_certificate): check = verify(host) print(check) if (check != 'signature verified'): print('Integrity check failed') s.close() with open(host + '_ca.crt', 'rb') as f: cert = x509.load_pem_x509_certificate(f.read(), default_backend()) public_key = cert.public_key() key = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) print('key to be shared is: ', key) message = key.encode('ascii') ciphertext = public_key.encrypt( message, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) print(ciphertext) stamp = True attempt = 0 while (stamp): s.send(base64.b64encode(ciphertext)) print('key sent') t = time() print(s.recv(1024).decode('ascii')) t2 = time() tt = round((t2 - t) * 1000, 2) delay = 1000 print('Timeout time: ', delay) print('Delay is:', tt) if (tt > 1000): attempt = attempt + 1 if (attempt == 1): no_rtattempt = False print('attempt1') s.send('resend'.encode('ascii')) sleep(1) continue else: no_retransmission = False availability = False no_delay = False delay_val = 100 stamp = False print('timed out') s.send('exit'.encode('ascii')) else: s.send('proceed'.encode('ascii')) stamp = False if (tt > 100 and tt < 200): delay_val = tt - 100 delay_val = round(delay_val, 2) no_delay = False elif (tt >= 200): delay_val = 100 no_delay = False print(delay_val) if (no_retransmission): while True: msg = str(input("Enter message: ")) a = AesCrypt() c = a.encrypt(key, msg) s.send(c) print('message sent') data = s.recv(1024) d = a.decrypt(key, data) print('message received: ', d.decode('utf-8')) ans = input('\nDo you want to continue(y/n) :') if ans == 'y': continue else: break data = { 'host_ipaddress': get_primary_ip(), 'eval_ipaddress': host, 'availability': availability, 'ca_certificate': ca_certificate, 'no_retransmission': no_retransmission, 'no_rtattempt': no_rtattempt, 'no_delay': no_delay, 'delay_val': delay_val } # close the connection data = json.dumps(data) r = requests.post(urlp, data, headers=headers) print(data) s.close()
def cipher_public_key(self, public_key, message): return public_key.encrypt( message, padding=padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None))
def encrypt(self, data): return self.public_key.encrypt( data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None))
def test_rsa_padding_supported_oaep(self): assert backend.rsa_padding_supported( padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None), ) is True
def decrypt(self, data): return self.private_key.decrypt( data, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None))
def data_received(self, data): print( "####################SSL layer data received called!#####################" ) self.deserializer.update(data) for packet in self.deserializer.nextPackets(): if isinstance(packet, PlsHello): self.incoming_cert.append( CipherUtil.getCertFromBytes(str.encode(packet.Certs[0]))) self.incoming_cert.append( CipherUtil.getCertFromBytes(str.encode(packet.Certs[1]))) self.incoming_cert.append( CipherUtil.getCertFromBytes(str.encode(packet.Certs[2]))) print("\nReceived Client Hello packet. Beginning Validation.") if self.validate(self.incoming_cert): self.nc = packet.Nonce self.m = hashlib.sha1() self.m.update(packet.__serialize__()) print("Certificate Validated. Sending Server hello!\n") self.clientnonce = packet.Nonce serverhello = PlsHello() serverhello.Nonce = int.from_bytes( os.urandom(8), byteorder='big') #12345678 self.ns = serverhello.Nonce idcert = getIDCertsForAddr() pubkey = getCertsForAddr() root = getRootCertsForAddr() serverhello.Certs = [] serverhello.Certs.append(idcert) serverhello.Certs.append(pubkey) serverhello.Certs.append(root) srvhello = serverhello.__serialize__() print("Sent Server Hello!\n") self.m.update(srvhello) self.transport.write(srvhello) if isinstance(packet, PlsKeyExchange): print("Received Client Key Exchange. Server Server Keys\n\n") self.m.update(packet.__serialize__()) serverpriv = CipherUtil.loadPrivateKeyFromPemFile( "/root/Downloads/prashanth.key") decrypted = serverpriv.decrypt( packet.PreKey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) #print("Decrypted Pre-Master Secret: ", decrypted) self.pkc = int.from_bytes(decrypted, byteorder='big') #==================================== #Creating Server Pre-Master serverkey = PlsKeyExchange() randomvalue = os.urandom(16) #b'1234567887654321' self.pks = int.from_bytes(randomvalue, byteorder='big') serverkey.NoncePlusOne = self.clientnonce + 1 pub_key = self.incoming_cert[0].public_key() encrypted = pub_key.encrypt( randomvalue, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) #print("Encrypted String is: ", encrypted) serverkey.PreKey = encrypted skey = serverkey.__serialize__() print("Sent the Prekey to Client.\n\n") self.m.update(skey) self.transport.write(skey) if isinstance(packet, PlsHandshakeDone): print("Received Client Handshake done message.") clientdigest = packet.ValidationHash serverdigest = self.m.digest() #print("Hash digest is: ", serverdigest) hdone = PlsHandshakeDone() hdone.ValidationHash = serverdigest if (serverdigest == clientdigest): print("Digest verification done!") # calling higher connection made since we have received the ACK self.key_generator() plstransport = PLSStackingTransport(self, self.transport) higherTransport = StackingTransport(plstransport) self.higherProtocol().connection_made(higherTransport) hdone_s = hdone.__serialize__() self.transport.write(hdone_s) if isinstance(packet, PlsData): print( "##################Recieved Data Packet from PLSClient###########################" ) self.ctr = 0 if self.mac_verification_engine(packet.Ciphertext, packet.Mac): DecryptedPacket = self.decryption_engine(packet.Ciphertext) self.higherProtocol().data_received(DecryptedPacket) self.ctr = 0 else: self.ctr += 1 if self.ctr != 5: print("Verification Failed. Try Again. Failed {}" ).format(self.ctr) else: print( "Verification failed 5 times. Killing Connection and Sending PlsClose." ) self.ctr = 0 #Creating and Sending PlsClose Close = PlsClose() #Close.Error = "Closing Connection due to 5 Verification failures. Aggrresive Close" serializeClose = Close.__serialize__() self.transport.write(serializeClose) self.transport.close() if isinstance(packet, PlsClose): print( "######################Received PlsClose from Client######################### " ) #self.connection_lost(self) self.transport.close()
def main(): inputi = input() komanda = inputi.split('"') try: mesazhi = komanda[1] try: shtegu = komanda[2] shtegu = shtegu[1:] print(shtegu) except: print("") except: print("Ju lutem vendosni mesazhin ne thonjeza!\nShemb: Write-Message emri \"mesazhi\" shtegu") Provo() komanda = inputi.split() type = komanda[0] emri = komanda[1] if type.upper() == "WRITE-MESSAGE": emri = ""+emri+".pub.xml" try: file = open("Keys/" + emri, "r") if file.mode == "r": private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) public_key = private_key.public_key() #konverton mesazhin ne bytes arr = bytes(mesazhi, 'utf-8') #enkriptimi i mesazhit duke perdoreur qelesin publik te gjeneruar nga vet sistemi rsa ciphertext = public_key.encrypt( arr, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None ) ) try: file = open("Keys/"+shtegu, "a+") file.write(str(ciphertext)) print("Mesazhi i enkriptuar u ruajt ne fajllin "+shtegu+".") Provo() except: print(ciphertext) Provo() except: print("Gabim: Celesi publik "+emri+" nuk ekziston") Provo() else: print("Vendos komanda valide!") Provo()
def drawProcess(mine, og_tile): if mine: print( '\n --- I requested piece {} from the board ---'.format(og_tile)) else: print('\n --- Someone requested piece {} from the board ---'.format( og_tile)) tile = og_tile # --- DECRYPTION while True: data = receive() if data['type'] != messages.REVELATION_REQUEST: raise UnexpectedMessageException() if data['reveal']: key_pair = {} key = cryptokeys[tile] t_str = crypto.get_string(tile) k_str = crypto.get_string(key) key_pair[t_str] = k_str send({'type': messages.REVELATION_REPLY, 'keys': key_pair}) else: tile = list(data['keys'])[0] key = data['keys'][tile] tile = crypto.get_bytes(tile) key = crypto.get_bytes(key) send({'type': messages.OK}) tile = crypto.decrypt(tile, key) if data['end']: break print('I got this pseudonym {}'.format(tile)) if mine: data = receive() if data['type'] != messages.DRAW_PREP: raise UnexpectedMessageException() priv_key, pub_key = crypto.generate_RSA_keys() send({'type': messages.DRAW_REQUEST, 'key': pub_key.hex()}) data = receive() if data['type'] != messages.DRAW_REPLY: raise UnexpectedMessageException() try: tmp = ast.literal_eval( priv_key.decrypt( bytes.fromhex(data['ciph']), padding.OAEP(padding.MGF1(hashes.SHA256()), hashes.SHA256(), None)).decode('utf-8')) ki = tmp[0] new_tile = tmp[1] # Verify try: pseudo = h(ki, new_tile) tile = ast.literal_eval(tile.decode('utf-8'))[0] except: raise ValueError() if pseudo != tile: raise ValueError() except ValueError: print("\nCould not de-anonimize draw. Draw cheating occured!") send({'type': messages.COMPLAIN, 'cheater': None}) data = receive() print('The resulting tile is {}'.format(new_tile)) send({'type': messages.OK}) print(' --- Draw process finished successfully ---\n') return new_tile data = receive() if data['type'] != messages.DRAW_END: raise UnexpectedMessageException() send({'type': messages.OK}) print(' --- Draw process finished successfully ---\n') return None
def encryptRSA(pub_key, message): ciphertext = pub_key.encrypt(message,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),algorithm=hashes.SHA1(),label=None)) return ciphertext
def get_pad_func(cls, hash_cls): return padding.OAEP(mgf=padding.MGF1(hash_cls()), algorithm=hash_cls(), label=None)
def __init__(self): super(_RsaOaep256, self).__init__( padding.OAEP(padding.MGF1(hashes.SHA256()), hashes.SHA256(), None))