def show_decryption_fields(): text = e1.get() key = e2.get() error = "Please insert 16 character Key" if len(key) < 16: tkinter.messagebox.showerror("Error", error) decrypted = aes_decrypt(text, key) print("\n\tDecrypted message is:\n") print(decrypted.decode()) tkinter.messagebox.showinfo("Decrypted Text",decrypted.decode())
def server_on_recv(s, data, channel, addr, fwd_host, fwd_port, a,b,c,d): aes_encryption_remaining = a.get() aes_decryption_remaining = b.get() data_incoming_remaining = c.get() data_outgoing_remaining = d.get() #print data #channel[s].send(data) # here we can parse and/or modify the data before send forward if addr[s] == (fwd_host, fwd_port): # Use a string of length 5 to represent the length of data data = str(len(data)).zfill(5) + data all_data, data_incoming_remaining = encode_as_ntp_no_fte.handle_data(data, 63, data_incoming_remaining) print 'udp' if all_data != []: #print 'yes' for j in range(len(all_data)): # Transform the packet into NTP #output = encode_as_ntp.transform_string(data) # AES encryption and convert into hex aes_output = aes.aes_encrypt(all_data[j], key, padding, block_size).encode('hex') # Combine the data with the AES remaining from last connection #aes_output += self.aes_encryption_remaining aes_encryption_remaining = aes_encryption_remaining + aes_output # Map AES result into NTP output, aes_encryption_remaining = encode_as_ntp_no_fte.transform_aes_into_ntp(aes_encryption_remaining) for i in range(0, len(output)): channel[s].sendto(output[i].decode('hex'), addr[s]) else: print 'tcp' #self.channel[self.s].send('hello world') # When there is an NTP packet coming, decode it #print 'there is data' #print data output2 = decode_ntp_no_fte.recover_ntp_into_aes(data.encode('hex')) aes_decryption_remaining += output2 if len(aes_decryption_remaining) >= 176: tmp = aes_decryption_remaining[:176] aes_decryption_remaining = aes_decryption_remaining[176:] aes_encoded = binascii.unhexlify(tmp).decode('utf-8') aes_decrypted = aes.aes_decrypt(aes_encoded, key, padding, block_size) data_outgoing_remaining = data_outgoing_remaining + aes_decrypted (to_send_str, data_outgoing_remaining) = aes.parse_output(data_outgoing_remaining) for i in range(len(to_send_str)): channel[s].send(to_send_str[i]) print 'packet is sent to tcp client' a.put(aes_encryption_remaining) b.put(aes_decryption_remaining) c.put(data_incoming_remaining) d.put(data_outgoing_remaining)
def gen_session_key(inc_pub_transport, local_exponent, long_term_key, auth_arr): """ generates a session key Arguments: inc_pub_transport - The value of the public_transport generated by a different computer, incoming. local_exponent - Secret value computed by gen_public_transport, used to combine with the inc_pub_transport to generate the session_key long_term_key - key used for aes decryption if encrypt_protocol set True auth_arr - To perform authentication, therefore including data/nonce in decryption data. This array is used as comparison with the received array to authenticate. returns: unique session key (only known to client/server), or 0 if using auth_arr, and data not authenticated """ inc_pub_transport_bytes = aes.aes_decrypt(inc_pub_transport, long_term_key) print("generating session key - public transport: " + str(inc_pub_transport_bytes)) inc_auth_arr = inc_pub_transport_bytes[:20] for inc_byte, auth_byte in zip(inc_auth_arr, auth_arr): if not inc_byte == auth_byte: print("Not authenticated.") return 0 # reduce bytes to actual data inc_pub_transport_bytes = inc_pub_transport_bytes[20:] inc_pub_transport = byte_array_to_int(inc_pub_transport_bytes) session_key = pow(inc_pub_transport, local_exponent, prime) # get first 16 bytes, so that key corresponds to a true aes key. session_key = int_to_byte_array(session_key)[:16] if debug: print("private session key is: " + str(session_key)) return session_key
def receive(self): """ Receive and decrypt data and populate the received entry field. """ if self.connector is None: return encrypted = self.connector.receive() if encrypted: self.logger.info('Encrypted data, received: ' + connector.bytestring_as_hex_string(encrypted)) msg_bytes = aes.aes_decrypt(encrypted[:-32], self.session_key) message = bytes(msg_bytes) self.logger.info('Decrypted message: ' + str(message)) mac_val = encrypted[-16:] mac_iv = encrypted[-32:-16] verified = mac.check_mac(message, mac_val, MAC_KEY, mac_iv) if verified: self.logger.info('MAC check SUCCESS') self.received_entry.delete(0, END) self.received_entry.insert(0, message) else: self.logger.info.info("MAC check FAILURE")
def gen_session_key(inc_pub_transport, local_exponent, long_term_key, auth_arr): """ generates a session key Arguments: inc_pub_transport - The value of the public_transport generated by a different computer, incoming. local_exponent - Secret value computed by gen_public_transport, used to combine with the inc_pub_transport to generate the session_key long_term_key - key used for aes decryption if encrypt_protocol set True auth_arr - To perform authentication, therefore including data/nonce in decryption data. This array is used as comparison with the received array to authenticate. returns: unique session key (only known to client/server), or 0 if using auth_arr, and data not authenticated """ inc_pub_transport_bytes = aes.aes_decrypt(inc_pub_transport, long_term_key) print("generating session key - public transport: " + str(inc_pub_transport_bytes)) inc_auth_arr = inc_pub_transport_bytes[:20] for inc_byte,auth_byte in zip(inc_auth_arr, auth_arr): if not inc_byte == auth_byte: print("Not authenticated.") return 0 # reduce bytes to actual data inc_pub_transport_bytes = inc_pub_transport_bytes[20:] inc_pub_transport = byte_array_to_int(inc_pub_transport_bytes) session_key = pow(inc_pub_transport, local_exponent, prime) # get first 16 bytes, so that key corresponds to a true aes key. session_key = int_to_byte_array(session_key)[:16] if debug: print("private session key is: " + str(session_key)) return session_key
def __init__(self, input, aes_key): if not RE_TOKEN.match(input): raise InvalidToken('Invalid token. A token should be 34 to 64 ModHex characters.') if not RE_AES_KEY.match(aes_key): raise InvalidAESKey('Invalid AES key. The key should be 32 hexadecimal characters.') self.public_id = input[:-32] self.token = input[-32:] self.aes_key = aes_key token_bin = ''.join(modhex_decode(self.token)) aes_key_bin = self.aes_key.decode('hex') decoded = aes_decrypt(token_bin, aes_key_bin) self.secret_id = decoded[0:6].encode('hex') self.counter = ord(decoded[7]) * 256 + ord(decoded[6]) self.timestamp = ord(decoded[10]) * 65536 + ord(decoded[9]) * 256 + ord(decoded[8]) self.counter_session = ord(decoded[11]) self.random_number = ord(decoded[13]) * 256 + ord(decoded[12]) self.crc = ord(decoded[15]) * 256 + ord(decoded[14]) self.crc_ok = crc_check(decoded)
def unlock_file(cipherfile, rsa_private_key, rsa_public_key): """Unlock archive. This function unlock an archive `cipherfile` using RSA private key `rsa_private_key` and RSA public key `rsa_public_key`. :parameter: cipherfile : string Name of the archive to unlock. rsa_private_key : string RSA private key rsa_public_key : string RSA public key """ try: starttime = time.time() # Importe RSA key from PEM rsa_private_key = RSA.importKey(open(rsa_private_key).read()) rsa_public_key = RSA.importKey(open(rsa_public_key).read()) # Extract encrypted tar and signature tar = tarfile.open(cipherfile) for file in tar.getnames(): tar.extract(file) tar.close() # Verification of the payload archive_data = open('encrypted_files_and_key.lkd.sign', mode='rb') raw_signature = archive_data.read() archive_data.close() archive_data = open('encrypted_files_and_key.lkd', mode='rb') raw_files = archive_data.read() archive_data.close() if not rsa.rsa_verify_sign(rsa_public_key, raw_signature, raw_files): print("[warning] This file has been corrupted ! Don't use it !") # clean tar filed files_to_delete = ["encrypted_files_and_key.lkd.sign", "encrypted_files_and_key.lkd"] for eachfile in files_to_delete: if os.path.isfile(eachfile): tools.secure_delete(eachfile, passes=1) else: print("[info] This file is authentic !") # Extract encrypted files and symetric key tar = tarfile.open('encrypted_files_and_key.lkd') for eachfile in tar.getnames(): tar.extract(eachfile) tar.close() # Decryption of the keys archive_data = open('cipherkey.lkd', mode='rb') raw = archive_data.read() archive_data.close() aes_key = rsa.rsa_decrypt(rsa_private_key, raw) # Decrypt files archive_data = open('encrypted_files.lkd', mode='rb') raw_files = archive_data.read() archive_data.close() bytestar = io.BytesIO( str(aes.aes_decrypt(AES_BLOCK_SIZE, aes_key, raw_files))) # Untar files tar = tarfile.open(fileobj=bytestar) for eachfile in tar.getnames(): tar.extract(eachfile) # Delete container related files files_to_delete = ["cipherkey.lkd", "encrypted_files_and_key.lkd", "encrypted_files_and_key.lkd.sign", "encrypted_files.lkd", cipherfile] for eachfile in files_to_delete: tools.secure_delete(eachfile, passes=1) endtime = time.time() elapsedtime = endtime - starttime print("[info] The files have been successfuly " "unlocked in %f seconds." % elapsedtime) except AttributeError: print('[error] A method was called with a false attribute.') sys.exit() except: print('[error] An unexpected error occurred when unlocking files.') files_to_delete = ["cipherkey.lkd", "encrypted_files_and_key.lkd", "encrypted_files_and_key.lkd.sign", "encrypted_files.lkd"] for eachfile in files_to_delete: if os.path.isfile(eachfile): tools.secure_delete(eachfile, passes=1) sys.exit()
def unpack_message_general(encoded_message, crypto_dict, machine, verbose = False): if machine == "client": verify_nonce = "client_nonces" updated_nonce = "server_nonces" required_rsa_key = "rsa_server_public_key" else: verify_nonce = "server_nonces" updated_nonce = "client_nonces" required_rsa_key = "rsa_user_public_keys" debug(verbose, "encoded_message", encoded_message) if machine != "client": # Strip User ID encoded_message = encoded_message.split(".") user_id = encoded_message[0] encoded_message = encoded_message[1] debug(verbose, "aes_session_id", user_id) # Decode message try: decoded_message = base64.b64decode(encoded_message) except Exception as inst: return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> base64.b64decode (encrypt) ]: " + str(inst)] if machine != "client": crypto_dict["rsa_user_public_key_hash"] = None for key in crypto_dict["aes_session_ids"]: value = crypto_dict["aes_session_ids"][key] if value == user_id: crypto_dict["rsa_user_public_key_hash"] = key break if crypto_dict["rsa_user_public_key_hash"] == None: return [False, "Error [ " + str(inspect.stack()[0][3]) + " ]: User ID invalid"] # Decrypt message try: key = crypto_dict["aes_session_keys"][crypto_dict["rsa_user_public_key_hash"]] debug(verbose, "key", key) aes_decrypted_message = str(aes.aes_decrypt(key, decoded_message)) except Exception as inst: return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> aes.decrypt ]: " + str(inst)] debug(verbose, "aes_decrypted_message", aes_decrypted_message) # Message Parsing try: rdmSplit = aes_decrypted_message.split("|") message_content, message_hash, message_signature = rdmSplit[0], rdmSplit[1], rdmSplit[2] # Remove any AES padding from signature message_signature = message_signature.strip(".") debug(verbose, "message_content", message_content) debug(verbose, "message_hash", message_hash) debug(verbose, "message_signature", message_signature) mcSplit = message_content.split(",") message, client_nonce, server_nonce = mcSplit[0], mcSplit[1], mcSplit[2] debug(verbose, "message", message) debug(verbose, "client_nonce", client_nonce) debug(verbose, "server_nonce", server_nonce) if machine != "client": temp = message.split(";") temp = temp[1] crypto_dict["rsa_user_public_key"] = crypto_dict["rsa_user_public_keys"][temp][0] if crypto_dict["rsa_user_public_keys"][temp][1]: return [False, "Error [ " + str(inspect.stack()[0][3]) + " ]: user hash already voted"] except Exception as inst: return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> Message Parsing ]: " + str(inst)] # Decode signature try: message_signature_decoded = base64.b64decode(message_signature) except Exception as inst: return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> base64.b64decode (signature) ]: " + str(inst)] # Verify Signature try: if str(rsa.unsign(crypto_dict[required_rsa_key][crypto_dict["rsa_user_public_key_hash"]][0], message_signature_decoded)) != message_hash: return [False, "Error [ " + str(inspect.stack()[0][3]) + " ]: signature verification failed"] elif verbose: print debug_spacing + "Debug [ " + str(inspect.stack()[0][3]) + " ]: signature verification passed" except Exception as inst: return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> rsa.unsign (Signature Verification) ]: " + str(inst)] # Verify Hash try: if str(sha.sha256(message_content)) != message_hash: return [False, "Error [ " + str(inspect.stack()[0][3]) + " ]: hash verification failed"] elif verbose: print debug_spacing + "Debug [ " + str(inspect.stack()[0][3]) + " ]: hash verification passed" except Exception as inst: return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> sha.sha256 (Hash Verification) ]: " + str(inst)] # Verify Nonce if machine == "client": nonce = client_nonce nonce_updated = server_nonce else: nonce = server_nonce nonce_updated = client_nonce if nonce != crypto_dict[verify_nonce][crypto_dict["rsa_user_public_key_hash"]]: return [False, "Error [ " + str(inspect.stack()[0][3]) + " ]: nonce verification failed"] elif verbose: print debug_spacing + "Debug [ " + str(inspect.stack()[0][3]) + " ]: nonce verification passed" # Upadte crypto_dictionary crypto_dict[updated_nonce][crypto_dict["rsa_user_public_key_hash"]] = nonce_updated if verbose: print "\n" if machine == "client": return [True, message] else: try: encoded_public_key = base64.b64encode(crypto_dict[required_rsa_key][crypto_dict["rsa_user_public_key_hash"]][0].publickey().exportKey("PEM")) except Exception as inst: return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> base64.b64encode (Public Key) ]: " + str(inst)] return [True, [encoded_public_key, message, base64.b64encode(message_signature)]]
#!/usr/bin/env python # encoding: utf-8 from aes import testAll, aes_encrypt, aes_decrypt testAll() Default_Text = ( "The Advanced Encryption Standard (AES), also known by its " "original name Rijndael, is a specification for the encryption " "of electronic data established by the U.S. National Institute " "of Standards and Technology (NIST) in 2001.") key = "AES_ENCRIPT_TEST" text = input("\tData you want to encrypt: \n") if not text: text = Default_Text print("\n\tThis string will be encrypted:\n") print(text) encrypted = aes_encrypt(text, key) print("\n\tEncrypted message is:\n") print(encrypted.decode()) decrypted = aes_decrypt(encrypted, key) print("\n\tDecrypted message is:\n") print(decrypted.decode())
def decrypt(self, c, iv): return aes_decrypt(c, self.key, "CBC", iv)