Advertisement
Guest User

Untitled

a guest
Jun 12th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.52 KB | None | 0 0
  1. import os
  2. import sys
  3. import time
  4. import socket
  5. from Cryptodome.PublicKey import RSA
  6. from Cryptodome.Cipher import AES, PKCS1_OAEP
  7.  
  8. PORT = 50001
  9. RUNNING_DIRECTORY = os.getcwd()
  10.  
  11.  
  12. def receive_file(file_name, key, sock):
  13.     """
  14.  
  15.    :param file_name:
  16.    :param key:
  17.    :param sock:
  18.  
  19.    alerts server for file download
  20.    read's from the file and each time encrypts it and send's
  21.    it away
  22.    """
  23.     send_small("download " + file_name, key, sock)
  24.     print "receiving file"
  25.     file_out = open(RUNNING_DIRECTORY + os.sep + "Recived_files" + os.sep + file_name, 'wb')
  26.     l1 = recive_small(key, sock)
  27.     while not l1 == "!@#":
  28.         file_out.write(l1)
  29.         l1 = recive_small(key, sock)
  30.     file_out.close()
  31.     print "finished"
  32.     return
  33.  
  34.  
  35. def send_small(text, key, sock):
  36.     """
  37.  
  38.    :param text:
  39.    :param key:
  40.    :param sock:
  41.    encrypte's a given string and sends it
  42.    without alerting the server
  43.    """
  44.     print "Key: " + key
  45.     cipher = AES.new(key, AES.MODE_EAX)
  46.     nonce = cipher.nonce
  47.     ciphertext, tag = Encryptsmall(cipher, text)
  48.     sock.send(ciphertext)
  49.     time.sleep(0.5)
  50.     sock.send(tag)
  51.     time.sleep(0.5)
  52.     sock.send(nonce)
  53.  
  54.  
  55. def recive_small(key, sock):
  56.     """
  57.  
  58.    :param key:
  59.    :param sock:
  60.    receive's massage and decrypts it
  61.    :return returns plain text if decryption successfully
  62.    """
  63.     text = sock.recv(4096)
  64.     tag = sock.recv(4096)
  65.     nonce = sock.recv(4096)
  66.     cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
  67.     return Decryptsmall(cipher, text, tag)
  68.  
  69.  
  70. def Encryptsmall(cipher, data="Testing"):
  71.     """
  72.  
  73.    :param cipher:
  74.    :param data:
  75.    :return: encrypted data
  76.    just encrypts a given string
  77.    """
  78.     ciphertext, tag = cipher.encrypt_and_digest(data)
  79.     return ciphertext, tag
  80.  
  81.  
  82. def Decryptsmall(cipher, ciphertext, tag):
  83.     """
  84.  
  85.    :param cipher:
  86.    :param ciphertext:
  87.    :param tag:
  88.    :return: plain text of received message
  89.    """
  90.     plaintext = cipher.decrypt(ciphertext)
  91.     try:
  92.         cipher.verify(tag)
  93.         print("The message is authentic:", plaintext)
  94.     except ValueError:
  95.         print("Key incorrect or message corrupted")
  96.  
  97.     return plaintext
  98.  
  99.  
  100. def send_file(sending_file, key, sock):
  101.     """
  102.  
  103.    :param sending_file:
  104.    :param key:
  105.    :param sock:
  106.    alerts server for an upload encrypts and sends the
  107.    encrypted data
  108.    """
  109.     send_small("upload " + sending_file.split(os.sep)[-1], key, sock)
  110.     file_to_send = open(sending_file, "rb")
  111.     l = file_to_send.read(4096)
  112.     while l:
  113.         send_small(l, key, sock)
  114.         l = file_to_send.read(4096)
  115.         print "."
  116.     send_small("!@#", key, sock)
  117.     print "Finished uploading"
  118.  
  119.  
  120. def decrypt_data(opened_file):
  121.     """
  122.  
  123.    :param opened_file:
  124.    :gets encrypted data
  125.    using rsa decrypts it used for the key transfer
  126.    """
  127.     file_out = open("temp2.bin", "wb")
  128.     private_key = RSA.import_key(open('private.pem').read())
  129.  
  130.     print "."
  131.  
  132.     enc_session_key, nonce, tag, ciphertext = \
  133.         [opened_file.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1)]
  134.  
  135.     print "."
  136.  
  137.     # Decrypt the session key with the private RSA key
  138.     cipher_rsa = PKCS1_OAEP.new(private_key)
  139.     session_key = cipher_rsa.decrypt(enc_session_key)
  140.  
  141.     print "."
  142.  
  143.     # Decrypt the data with the AES session key
  144.     cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
  145.     data = cipher_aes.decrypt_and_verify(ciphertext, tag)
  146.     file_out.write(data)
  147.     print "finished decrypting"
  148.  
  149.  
  150. def generate_keys():
  151.     '''
  152.    Generate an RSA keypair with an exponent of 65537 in PEM format
  153.    param: bits The key length in bits
  154.    Return private key and public key
  155.    '''
  156.  
  157.     key = RSA.generate(2048)
  158.     private_key = key.export_key()
  159.     file_out = open("Private.pem", "wb+")
  160.     file_out.write(private_key)
  161.     file_out.close()
  162.  
  163.     public_key = key.publickey().export_key()
  164.     file_out = open("Public.pem", "wb+")
  165.     file_out.write(public_key)
  166.     file_out.close()
  167.  
  168.  
  169. def starting_up():
  170.     """
  171.    makes sure all the folder's that are needed exists
  172.    including the private and public key
  173.    also connects the client to the server by asking for ip
  174.    :return connected socket and the encryption key
  175.    """
  176.  
  177.     Pass = False
  178.  
  179.     if not (os.path.exists(RUNNING_DIRECTORY + '/Public.pem')):
  180.         print ("Generating Private and Public key.......")
  181.         generate_keys()
  182.  
  183.     else:
  184.         print ("Private and Public keys found")
  185.  
  186.     if not (os.path.exists(RUNNING_DIRECTORY + '/Recived_files')):
  187.         os.mkdir(RUNNING_DIRECTORY + '/Recived_files')
  188.  
  189.     print "Enter IP Of the Server"
  190.  
  191.     while not Pass:
  192.         ip = raw_input()
  193.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  194.         address = (ip, 50001)
  195.         try:
  196.             sock.connect(address)
  197.             Pass = True
  198.         except Exception, e:
  199.             print (e)
  200.             print "wrong ip\server isn't open try again"
  201.  
  202.     f = open("Public.pem", 'rb')
  203.     sock.send(f.read(4096))
  204.  
  205.     f = open("temp.bin", 'wb')  # opens file for encrypted data
  206.     f.write(sock.recv(4096))
  207.     f.close()
  208.     f = open("temp.bin", 'rb')  # opens file in read mode
  209.  
  210.     decrypt_data(f)
  211.     f.close()
  212.  
  213.     os.remove("temp.bin")  # removes uneccesery files
  214.  
  215.     f = open('temp2.bin')
  216.     key = f.read(4096)
  217.     f.close()
  218.  
  219.     os.remove('temp2.bin')
  220.  
  221.     print key
  222.  
  223.     return key, sock
  224.  
  225.  
  226. def main():
  227.  
  228.     command = ""
  229.     password = ""
  230.     username = ""
  231.     server_response = ""
  232.     key, sock = starting_up()
  233.  
  234.     repassword = "!"
  235.  
  236.     while True:
  237.  
  238.         print 'would you like to:'
  239.         print '1) sign in'
  240.         print '2) sign up'
  241.         print '3) exit'
  242.  
  243.         response = raw_input()
  244.  
  245.         if response == "1":
  246.             print ("Username: ")
  247.             username = raw_input()
  248.             print ("Password: ")
  249.             password = raw_input()
  250.             send_small("SI " + username + " " + password, key, sock)
  251.  
  252.             server_response = recive_small(key, sock)
  253.  
  254.             if server_response == "Cool":
  255.                 print "Welcome back " + username
  256.                 break
  257.             else:
  258.                 print "wrong username/password"
  259.                 continue
  260.  
  261.         elif response == "2":
  262.             print ("Username: ")
  263.             username = raw_input()
  264.             while password != repassword:
  265.                 print ("Password: ")
  266.                 password = raw_input()
  267.                 print "Repeat password"
  268.                 repassword = raw_input()
  269.                 if password == repassword:
  270.                     send_small("S_U " + username + " " + password, key, sock)
  271.  
  272.                     server_response = recive_small(key, sock)
  273.  
  274.                     if server_response == "Cool":
  275.                         print "welcome " + username
  276.                         break
  277.                 else:
  278.                     print "passwords don't match try again"
  279.                     continue
  280.  
  281.             if server_response == "Cool":
  282.                 break
  283.             else:
  284.                 print "username already taken"
  285.                 continue
  286.  
  287.         elif response == "3":
  288.             send_small("bye", key, sock)
  289.             sock.close()
  290.             sys.exit()
  291.  
  292.         else:
  293.             continue
  294.  
  295.     while command != "disconnect":
  296.         print "command:"
  297.         command = raw_input()
  298.  
  299.         if command.split(" ")[0] == "list":
  300.             send_small("list", key, sock)
  301.             print recive_small(key, sock)
  302.  
  303.         elif command.split(" ")[0] == "upload":
  304.             send_file(command.split(" ")[1], key, sock)
  305.  
  306.         elif command.split(" ")[0] == 'download':
  307.             receive_file(command.split(" ")[1], key, sock)
  308.  
  309.         elif command.split(" ")[0] == "rm":
  310.             send_small("rm " + command.split(" ")[1], key, sock)
  311.             print recive_small(key, sock)
  312.         elif command.split(" ")[0] == "help":
  313.             print "list: shows the files names in ur storage \n"
  314.             print "upload + file path will send to the cloud the \n" \
  315.                   "file that you gave the path to \n"
  316.             print "download + file name will download the file that\n" \
  317.                   "you desire REMEMBER TO ADD THE FILE TYPE\n"
  318.             print "rm + file will remove the file you desire from the cloud \n"
  319.             print "disconnect will literally disconnect you\n"
  320.         else:
  321.             print "no such command " + command + " use 'help'"
  322.     send_small("bye", key, sock)
  323.  
  324.  
  325. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement