2022 – Python File Transfer with Secure Connection

Python File Transfer with Secure Connection Over TCP:

There are many reasons to transfer files securely over the internet. Most often, the reason to transfer files is so that the files can be securely transferred online. This blog will look at how to use a python file transfer to transfer files securely over the internet. The process will be stressed with a step-by-step guide of how to transfer files securely.This blog discusses how to use python file transfer with encrypted secured transfer. It also discusses how to establish a socket connection between two computers.The article looks at how a python file transfer can be run as an optional additional option as well as a socket connection output. A Python file transfer is an alternative method of transferring data that is not a standard file transfer. Learning how to transfer files with python is beneficial because of the increased flexibility and options you have.python file transfer with encrypted secured tcp connection and socket is a Python tutorial blog on how to transfer files using a python class.

 

Required Modules:

pip install pybase64
pip install pycryptodome
pip install art
pip install pwntools

 

Server_Login.py

import csv
from art import *
import pybase64
from getpass import getpass

# server signup is a simple authentication model which is used to register by specific members for server side access where super admin can register a new user who can initiate the server 
tprint('Server Signup')

def options(x):
    # this option is for a new user signup 
    if x == 1:
        with open('names.csv', 'a', newline='') as csvfile:
            writer = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)
            user_ = input('Enter username: ')
            pass_ = getpass('Enter password: ')
            pass_conf = getpass('confirm password:')
            if pass_ == pass_conf:
                print('Server admin added successfully')
                writer.writerow([user_,pass_])
            else:
                print('passwords dont match! exiting!!!')
                exit()

    # this option is for listing of available users who have server access  
    if x == 2:
        print('List of users in server:')
        with open('names.csv',newline='') as csvreadfile:
            spamreader = csv.reader(csvreadfile, delimiter=' ', quotechar='|')
            for row in spamreader:
                print(f'user:{row[0]}:::pass:{row[1]}')
                
    if x == 3:
        exit()

# checking the username and password of the super admin by encrypted credentials check
user_ = input('Enter Username:').encode()
pass_ = getpass('Enter password: ').encode()
if user_ == pybase64.b64decode(bytes.fromhex('595752746157343d')) and pass_ == pybase64.b64decode(bytes.fromhex('5147524e4d57343d')):
    print('Welcome to Server User registration')
    while True:
        x = int(input('Enter your choice:\n1.New User\n2.List Users\n3.Exit\n'))
        options(x)
else:
    print('Wrong Credentials!! Terminating Process')

 

File Transfer with Encrypted Connection:

The python file transfer tool is one of the most used tools for transferring files. It allows one to transfer files from one computer, or from one machine to another. However, when you transfer files with a python file transfer tool, you can face a lot of challenges. These challenges may be because of certain firewall and settings that your computer may be set up with. This blog will look at a python file transfer tool with an encrypted secured socket connection and TCP connection.

Python file transfer is a python package to transfer multiple files between two computers, for example, between a desktop computer and a laptop. It can only transfer files in binary, not text files. It can be used for file sharing and for backup purposes. It is based on the file transfer model of ssh.

python file transfer is a free python file transfer software that can be used to transfer files over a network. It uses the Network File System (NFS) and the Secure Shell (SSH) to transfer files. This tutorial covers how to set up and run a connection between two computers, using python file transfer.

This is a Python script that allows you to transfer files encrypted and securely to a remote computer. It utilizes a TCP connection and a socket. The script uses the secure socket layer protocol to set up the TCP connection and enables encryption to ensure that the files are secure while they are being transferred. This works by using a third party service called the “https version of the python file transfer library” to ensure that secure files are being transferred to remote computers.

Server.py

import socket
import os
import pybase64
import time
import csv
from datetime import datetime
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from art import *
from getpass import getpass
from pwn import *

# this is the server side program of the project
tprint('Secure Server')

def server_code():

    # assigning necessary information for the initialization of the server
    ip = socket.gethostbyname(socket.gethostname())
    port = 5002
    addr = (ip,port)

    # creating a log file to write server activities based on server run time
    log_name = time.ctime()
    log_name = 'server_log_'+log_name.replace(' ','-')
    log_file = open('server_logs_'+str(time.ctime()).replace(' ','-').replace(':','.')+'.txt','w')
    log.info('[' + datetime.now().strftime('%H:%M:%S')+'] server starting')
    log_file.write('[' + datetime.now().strftime('%H:%M:%S')+'] server starting\n')

    # initialization of the server
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(addr)
    server.listen()
    log.info('listening to the server')
    log_file.write('[' + datetime.now().strftime('%H:%M:%S')+'] listening to the server\n')

    # client connecting to the server
    while True:
        conn,addr = server.accept()
        name = conn.recv(4096).decode()
        log.info(f'new connection established with {addr} on {port}\nClient Name:{name}')
        log_file.write('[' + datetime.now().strftime('%H:%M:%S')+'] new connection established '+ip+'\n['+datetime.now().strftime('%H:%M:%S')+'] Client Name : '+name+'\n')
        
        try:
            # receiving the filename and writing it in the server side
            filename = conn.recv(1024).decode('utf-8')    
            file = open(filename, 'w')
            conn.send('file received from client'.encode())
            log_file.write('[' + datetime.now().strftime('%H:%M:%S')+f'] file {filename} received from client\n')

            # Collecting file data
            data = conn.recv(1024)
            log.info('file received from client')
            log_file.write('[' + datetime.now().strftime('%H:%M:%S')+'] file data collected\n')

            # Decrypting file data using RSA
            f = open('private_key.pem','rb')
            private_key = RSA.importKey(f.read())
            rsa_private_key = PKCS1_OAEP.new(private_key)
            data = rsa_private_key.decrypt(data)

            # decoding file data using base64 and writing it into a file
            data = pybase64.b64decode(data)
            file.write(data.decode())
            conn.send('[server] file data received from client'.encode())
            log_file.write('[' + datetime.now().strftime('%H:%M:%S')+'] file data received from client\n')
            file.close()
            conn.close()
            log.info('file successfully decrypted')
            log.info('client disconnected')
            log_file.write('[' + datetime.now().strftime('%H:%M:%S')+'] client disconnect\n')
            log_file.close()
            exit()

        # This excpetion is triggered when the file is not uploaded from the client
        except ValueError:
            log.info('Valid file not uploaded from Client Side')
            log_file.write('[' + datetime.now().strftime('%H:%M:%S')+'] Valid file not uploaded from Client Side\n')
            log_file.write('[' + datetime.now().strftime('%H:%M:%S')+'] client disconnect\n')
            exit()

# checking user and password credentials for server side initialization access        
user_ip = input('Enter Username: ').strip('\n')
pass_ip = getpass('Enter Password: ')
flag = 0
with open('names.csv',newline='') as csvreadfile:
    spamreader = csv.reader(csvreadfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        if user_ip == row[0] and pass_ip == row[1]:
            flag=1
if flag == 1:
    server_code()
else:
    log.info('Wrong Admin credentials Exiting!!')

 

Client.py

import socket
import os
import pybase64
import time
import csv
from Crypto.PublicKey import RSA
from tkinter import Tk, filedialog
from datetime import datetime
from Crypto.Cipher import PKCS1_OAEP
from getpass import getpass
from pwn import *

# assigning necessary information for the initialization of the server
ip = socket.gethostbyname(socket.gethostname())
port = 5002
addr = (ip,port)

# generation of RSA key pair
key_gen = RSA.generate(2048, e=65537) 
public_key = key_gen.publickey().exportKey("PEM") 
private_key = key_gen.exportKey("PEM") 

# saving private key for decryption purposes
private_key_file = open('private_key.pem','wb')
private_key_file.write(private_key)
private_key_file.close()

# importing public key and implementing Pkcs1 padding
pub = RSA.importKey(public_key)
rsa_public_key = PKCS1_OAEP.new(pub)

# formally getting client's name
log.info('client starting')
x = input('Enter Client Name: ')

# initialization of Tkinter GUI for selection of file in an interactive enironment
root = Tk()
root.withdraw()
root.attributes('-topmost', True)

# intiating socket connection to the server and throws an exception if the server is not initiated before client
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    client.connect(addr)
except:
    log.info('[Exception] Server not found Exiting')   
    exit() 
client.send(x.encode())

try:
    # selecting file to transfer
    print('Choose the file which you want to transfer:')
    time.sleep(2)
    filepath = filedialog.askopenfilename()
    fileshared = open(filepath,'rb')
    filename = filepath.split('/')

    # reading the file data and sending the filename to the server
    data = fileshared.read()
    client.send(filename[-1].encode())
    msg = client.recv(1024).decode()
    

    # encoding the file first and then encrypting it and sending it to the server
    data = pybase64.b64encode(data)
    data = rsa_public_key.encrypt(data)
    print('File encrypted successfully')
    client.send(data)
    print('File transferred Successfully')
    print(f'[server] {msg}')
    fileshared.close()
    client.close()

# This excpetion is triggered when file of size more than 1 kb is uploaded. This exception is included because for files more than 1kb value error of 'plaintext is too long' is shown.
except ValueError as e:
    log.info("File size of 1kb can only be transferred!!!")

 

Conclusion:

Python is a widely used computer programming language. It is often used for developing data processing applications because it provides a simple syntax and a large standard library. It is also used for web application development and other software development tasks. Python’s flexibility and portability make it a popular choice for programming. In this article, we will talk about a python file transfer with encrypted secured tcp connection and socket.

We have compiled a list of the most commonly used codes to transfer files between two or more users.python file transfer is now the fastest, easiest, and cheapest way to transfer data on the internet. This blog post will teach you how to use the python file transfer method in a secure way, with an encrypted secured tcp connection and socket.

If you are looking for a solution to send files to another computer via TCP socket then this is the right blog post for you. In this blog post, you will learn how to use a python file transfer that supports encrypted secured communication via a TCP socket.
Python is a high-level programming language that can be used to write software. The Python language syntax has been very influential, and it is used in many programming areas. The most common function in python is the “file” function. This function is used to transfer files, but it can also be used for other purposes. The function “file” has many different methods that can be used to transfer files. The function “socket” can be used to transfer files through a secured, encrypted connection.

This tutorial will show you how to use python to securely transfer files over a TCP connection and a socket.This article demonstrates how to create a python file transfer program with a secure encrypted secured tcp connection and socket. It is possible to create a file transfer program with a socket and a tcp connection but this article demonstrates how to use python to create a file transfer program with a secure tcp connection and socket.