예제 #1
0
def on_message(data):
    """Broadcast messages"""

    res = ""
    msg = data["msg"]
    # print(type(msg))
    # print(msg)
    if "#" in msg:
        temp_msg = msg.split("#")

        if temp_msg[-1][:3] == "aes":
            key = temp_msg[1].split(":")[-1]
            msg = aes_encrypt(temp_msg[:-1], key)
            if msg is None: 
                res = temp_msg[0]
            else:
                res = msg
    else:
        res = msg 

    username = data["username"]
    room = data["room"]
    # Set timestamp
    time_stamp = time.strftime('%b-%d %I:%M%p', time.localtime())
    send({"username": username, "msg": res, "time_stamp": time_stamp}, room=room)
    
    # decryption 
    if msg is None:
        return 0
    res = aes_decrypt(res, key)
    send({"username": username, "msg": res, "time_stamp": time_stamp}, room=room)
예제 #2
0
def show_entry_fields():
    text = e1.get()
    key = e2.get()
    error = "Please insert 16 character Key"
    if len(key) < 16:
        tkinter.messagebox.showerror("Error", error)
    encrypted = aes_encrypt(text, key)
    print("\n\tEncrypted message is:\n")
    print(encrypted.decode())
    tkinter.messagebox.showinfo("Encrypted Text",encrypted.decode())
예제 #3
0
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)
예제 #4
0
파일: VPNApp.py 프로젝트: rsingla92/a3-vpn
 def send_callback(self):
     """
     Encrypt and send the data to be sent
     """
     if self.state != CONNECTED:
         self.logger.info('No connection established')
         return
     to_send = self.send_entry.get()
     if to_send and self.connector:
         self.logger.info('Encrypting message')
         encrypted = aes.aes_encrypt(to_send, self.session_key)
         encoded = bytes(encrypted)
         self.logger.info('Calculating MAC')
         mac_val = mac.get_mac(to_send, MAC_KEY)
         self.logger.info('Sending encrypted message')
         self.connector.send(encoded + bytes(mac_val[0]) + bytes(mac_val[1]))
예제 #5
0
def encrypt_file(filename, header, key, mode = None, iv = None):
    f = open(filename, "rb").read()

    if mode is None:
        prefix = "otp_"
    else:
        prefix = "aes_" + mode + "_"

    c = open(prefix + filename, "wb")
    if mode is None:
        c.write(header + xor(f, key)[len(header):])
    else:
        from aes import aes_encrypt
        c.write(header + aes_encrypt(f, key, mode, iv)[len(header):])

    c.close()
    print("Encrypted file written to '" + prefix + filename + "'")
예제 #6
0
파일: VPNApp.py 프로젝트: rsingla92/a3-vpn
 def send_callback(self):
     """
     Encrypt and send the data to be sent
     """
     if self.state != CONNECTED:
         self.logger.info('No connection established')
         return
     to_send = self.send_entry.get()
     if to_send and self.connector:
         self.logger.info('Encrypting message')
         encrypted = aes.aes_encrypt(to_send, self.session_key)
         encoded = bytes(encrypted)
         self.logger.info('Calculating MAC')
         mac_val = mac.get_mac(to_send, MAC_KEY)
         self.logger.info('Sending encrypted message')
         self.connector.send(encoded + bytes(mac_val[0]) +
                             bytes(mac_val[1]))
예제 #7
0
def gen_public_transport(long_term_key, auth_arr):
    """
    generates a tuple containing the data to pass to the other computer,
    aka the public_transport, as well as the local-exponent which will
    be required later on to generate the session-key.

    Arguments:
    long_term_key - key used in aes encryption
    auth_arr - if present, is used as per the authentication DH scheme
               that is, it's prepended to the proper public_transport
               before encryption.

    Returns: tuple(public_transport, local_exponent)
    """
    if debug:
        print("generating public transport data")

    local_exponent, pub_transport, pub_transport_arr = None, None, None
    while True:
        local_exponent = random.getrandbits(128)
        if debug:
            print("local_exponent: " + str(local_exponent))

        pub_transport = pow(gen, local_exponent, prime)
        if debug:
            print("pub_transport:" + str(pub_transport))

        # -pub_transport is an array of bytes, if encrypted
        # -Encrypt the public_transport
        # with the authorization_array (the ID and nonce) prepended to
        # the transport data
        pub_transport_arr = int_to_byte_array(pub_transport)
        if pub_transport_arr[-1] != 128:
            # We are okay as long as the last byte is not the same as the padding byte
            # for AES. Otherwise it will be stripped. If it is 128, continue generating
            # local exponents until it is not.
            break

    pub_transport = list(auth_arr) + list(pub_transport_arr)
    print("generating public transport - public transport: " +
          str(pub_transport))
    pub_transport = aes.aes_encrypt(pub_transport, long_term_key)
    if debug:
        print("public_transport, encrypted: " + str(pub_transport))
    return pub_transport, local_exponent
예제 #8
0
파일: dh_auth.py 프로젝트: rsingla92/a3-vpn
def gen_public_transport(long_term_key, auth_arr):
    """
    generates a tuple containing the data to pass to the other computer,
    aka the public_transport, as well as the local-exponent which will
    be required later on to generate the session-key.

    Arguments:
    long_term_key - key used in aes encryption
    auth_arr - if present, is used as per the authentication DH scheme
               that is, it's prepended to the proper public_transport
               before encryption.

    Returns: tuple(public_transport, local_exponent)
    """
    if debug:
        print("generating public transport data")

    local_exponent, pub_transport, pub_transport_arr = None, None, None
    while True:
        local_exponent = random.getrandbits(128)
        if debug:
            print("local_exponent: " + str(local_exponent))

        pub_transport = pow(gen, local_exponent, prime)
        if debug:
            print("pub_transport:" + str(pub_transport))

        # -pub_transport is an array of bytes, if encrypted
        # -Encrypt the public_transport
        # with the authorization_array (the ID and nonce) prepended to
        # the transport data
        pub_transport_arr = int_to_byte_array(pub_transport)
        if pub_transport_arr[-1] != 128:
            # We are okay as long as the last byte is not the same as the padding byte
            # for AES. Otherwise it will be stripped. If it is 128, continue generating
            # local exponents until it is not.
            break;

    pub_transport = list(auth_arr) + list(pub_transport_arr)
    print("generating public transport - public transport: " + str(pub_transport))
    pub_transport = aes.aes_encrypt(pub_transport, long_term_key)
    if debug:
        print("public_transport, encrypted: " + str(pub_transport))
    return pub_transport, local_exponent
예제 #9
0
def get_mac(plaintext, mac_key, mac_iv=None):
    """
    Return CBC-MAC block as bytes
    """
    ciphertext = aes.aes_encrypt(plaintext, mac_key, mac_iv)
    return ciphertext[:BLOCK_SIZE_BYTES], take_last_aes_block(ciphertext)
예제 #10
0
def lock_files(files_to_lock, rsa_private_key, rsa_public_key,
               output='archive', secure_delete=False):
    """Lock files.

    This function lock `files_to_lock` in an archive `output` using RSA
    private key `rsa_private_key` and RSA public key `rsa_public_key`.

    :parameter:
     files_to_lock : list
        A list of files to lock.
     rsa_private_key : string
        RSA private key
     rsa_public_key : string
        RSA public key
     output : string
        The output name of the archive. "archive" by default.
     secure_delete : boolean
        True if the user want to securely delete his `files_to_lock`.
    """
    try:
        starttime = time.time()

        #######################################################################
        # Keys generation and importation
        #######################################################################

        # 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())

        # Generate AES key and iv
        aes_key = aes.gen_aes_key(AES_KEY_SIZE)
        aes_iv = aes.gen_iv(AES_BLOCK_SIZE)

        encrypted_key = rsa.rsa_encrypt(rsa_public_key, aes_key)

        f = open('cipherkey.lkd', 'w')
        f.write(encrypted_key)
        f.close()

        #######################################################################
        # Encryption and MAC of the files
        #######################################################################

        # Put file in a tar archive
        archive = tools.tarfiles(files_to_lock, 'source.tar')
        archive_data = open(archive, mode='rb')
        raw = archive_data.read()
        archive_data.close()

        # Encrypt the tar file
        cipherdata = \
            aes.aes_encrypt(AES_BLOCK_SIZE, aes_iv, aes_key, raw)

        # Save cipher data
        out = open('encrypted_files.lkd', 'w')
        out.write(str(cipherdata))
        out.close()

        # Tar cipherkeys, cipherfile and mac file toghether
        finalfiles = ['cipherkey.lkd', 'encrypted_files.lkd']
        ciphertar = tools.tarfiles(finalfiles, 'encrypted_files_and_key.lkd')
        f = open(ciphertar, mode='rb')
        ciphertardata = f.read()
        f.close()

        # Sign data with private key
        rsa_signature = rsa.rsa_sign(rsa_private_key, ciphertardata)

        # Save signature
        f = open('encrypted_files_and_key.lkd.sign', 'w')
        f.write(rsa_signature)
        f.close()

        # Archive signed file and signature together
        tools.tarfiles(['encrypted_files_and_key.lkd.sign',
                        'encrypted_files_and_key.lkd'], output+'.lkd')

        # Secure delete temp files
        files_to_delete = ['encrypted_files_and_key.lkd.sign',
                           'encrypted_files.lkd', 'cipherkey.lkd', archive,
                           ciphertar]

        for file in files_to_delete:
            success = tools.secure_delete(file)
            if not success:
                print('[error] Something went wrong during the secure file '
                      'delete '
                      'of ' + file + ', make sure your erase it manually.')
        # Secure delete sources files
        if secure_delete:
            for file in files_to_lock:
                success = tools.secure_delete(file)
                if not success:
                    print('[error] Something went wrong during the secure'
                          ' file delete of ' + file +
                          ', make sure your erase it manually.')

        endtime = time.time()
        elapsedtime = endtime - starttime

        print("[info] The files have been successfuly "
              "locked in %f seconds." % elapsedtime)

    except AttributeError:
        print('[error] A method was called with a false attribute.')
        sys.exit()
    except IOError:
        print('[error] Maybe one of your files does not exist')
        sys.exit()
    except:
        print('[error] An unexpected error occurred when locking files.')
        sys.exit()
예제 #11
0
def pack_message_general(message, crypto_dict, machine, verbose = False):

	if machine == "client":
		updated_nonce = "client_nonces"
		required_rsa_key = "rsa_user_private_key"
	else:
		updated_nonce = "server_nonces"
		required_rsa_key = "rsa_server_private_key"
	
	# Update machine's nonce
	try:
		crypto_dict[updated_nonce][crypto_dict["rsa_user_public_key_hash"]] = str(rand.rand_byte(32))[:32]
	except Exception as inst:
		return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> rand ]: " + str(inst)]

	debug(verbose, updated_nonce, crypto_dict[updated_nonce][crypto_dict["rsa_user_public_key_hash"]])

	# Compile message
	nonced_message = message + "," + crypto_dict["client_nonces"][crypto_dict["rsa_user_public_key_hash"]] + "," + crypto_dict["server_nonces"][crypto_dict["rsa_user_public_key_hash"]] + ","

	# Padding nonced_message to length of 128
	while len(nonced_message) < padding_length:
		nonced_message += "."

	debug(verbose, "nonced_message", nonced_message)

	# Hash message
	try:
		message_hash = sha.sha256(nonced_message)
		hashed_message = nonced_message + "|" + message_hash
	except Exception as inst:
		return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> sha.sha256 ]: " + str(inst)]

	debug(verbose, "hashed_message", hashed_message)

	# Sign message
	try:
		message_signature = str(rsa.sign(crypto_dict[required_rsa_key], message_hash))
	except Exception as inst:
		return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> rsa.sign ]: " + str(inst)]
	
	# Encode signature and append
	try:
		signed_message = hashed_message + "|" + base64.b64encode(message_signature)
	except Exception as inst:
		return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> base64.b64encode (signature) ]: " + str(inst)]

	# Padding signed_message to length of 128 (AES encryption needs message to be a length of multiple 16)
	while len(signed_message) % 16 != 0:
		signed_message += "."

	debug(verbose, "signed_message", signed_message)

	# Encrypt message
	try:
		key = crypto_dict["aes_session_keys"][crypto_dict["rsa_user_public_key_hash"]]
		debug(verbose, "key", key)
		aes_encrypted_message = str(aes.aes_encrypt(key, signed_message))
	except Exception as inst:
		return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> aes.aes_encrypt ]: " + str(inst)]

	# Encode message
	try:
		encoded_message = base64.b64encode(aes_encrypted_message)
	except Exception as inst:
		return [False, "Error [ " + str(inspect.stack()[0][3]) + " -> base64.b64encode (encrypt) ]: " + str(inst)]

	debug(verbose, "encoded_message", encoded_message)

	if verbose:
		print "\n"
		
	return [True, encoded_message]
예제 #12
0
#!/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())
예제 #13
0
파일: dh.py 프로젝트: aaron-otis/Security
 def encrypt(self, m):
     self.iv = urandom(BLOCK_SIZE())
     return [aes_encrypt(m, self.key, "CBC", self.iv), self.iv]
예제 #14
0
if __name__ == '__main__':
    # The message to encode (0-15 --> 24)
    input_str = 'hello'
    filename = '500KL3.fsa'
    full_symbol = [
        'e', 'g', 'r', 's', 't', 'u', 'v', 'y', 'z', '1', '2', '3', '4', '5',
        '6', '7', '8', '9'
    ]
    prefix = 1
    # AES part
    block_size = 16
    key_file = 'aes_key'
    padding = '{'
    ##aes.aes_gen_key(block_size, key_file)
    key = aes.aes_read_key(block_size, key_file)
    aes_encoded = aes.aes_encrypt(input_str, key, padding, block_size)
    print len(aes_encoded)
    input_str = aes_encoded
    print aes_encoded

    finished_message = ''
    final_output = ''
    remaining_message = 'long'
    index = 0
    # The loop
    f = open('dm_output', 'w')
    while remaining_message != '':
        # Add a random character in the beginning
        #input_str = add_random_prefix(input_str)
        symbol = full_symbol
        input_str, symbol = add_prefix(input_str, symbol)
예제 #15
0
파일: mac.py 프로젝트: rsingla92/a3-vpn
def get_mac(plaintext, mac_key, mac_iv = None):
    """
    Return CBC-MAC block as bytes
    """
    ciphertext = aes.aes_encrypt(plaintext, mac_key, mac_iv)
    return ciphertext[:BLOCK_SIZE_BYTES], take_last_aes_block(ciphertext)