def download(filename, destination, privpath, user):
    """Download function, creates a temporary file to
    where the encrypted file is streamed to, then it is read
    chunk by chunk and decrypted.

    Security:
        - Authentication
        - File is decrypted with AES
        - hasher is created for File Integrity Control
        - Public key is accessed for decrypting the AES
          key
        - Private Key is accessed for verifying the file signature
        - All relevant information is kept client-side"""

    (username, session) = user.getInfo()
    message = {'filename': filename}
    messageToSend = security.encryptS_AES(json.dumps(message),
                                          session.decode('hex')).encode('hex')
    params = {'data': messageToSend, 'username': username}
    datagen, headers = multipart_encode(params)
    try:
        resp = urllib2.Request('https://localhost:8080/download', datagen,
                               headers)
        data = urllib2.urlopen(resp)
        fn = data.info().getheader('filename')
        date = json.loads(
            security.decryptS_AES(data.info().getheader('data').decode('hex'),
                                  session.decode('hex')))
        aes = data.info().getheader('aes').decode('hex')
        iv = date['iv'].decode('hex')
        signature = date['sign'].decode('hex')

        with open(privpath, 'rb') as f:
            priv = security.importkey_RSA(f.read())
        pub = security.importkey_RSA(getPubKey(username))
        RsaAES = security.decrypt_RSA(priv, aes)
        decipher = security.getDecipher(iv, RsaAES)
        tf = tempfile.NamedTemporaryFile(delete=True)

        CHUNK = 16 * 1024
        while True:
            chunk = data.read(CHUNK)
            if not chunk:
                break
            tf.write(chunk)
        tf.seek(0)

        hasher = security.Hasher()
        with open(os.path.join(str(destination), filename), 'wb') as out:
            security.decrypt_AES(decipher, tf, out, hasher)
        new = hasher.get()
        if security.verifyFile(pub, new, signature):
            print 'The File was not changed!'
        else:
            print 'The File was changed!'
        tf.close()
    except urllib2.HTTPError as e:
        print str(e.code) + ': ' + e.reason
        print 'Currently, you are not a valid user!\nSafeBox Team'
def diff(user, filename, privpath, filefp):
    """Function for getting the difference between a file in
    the server and a user file, works like download except no file
    is written.

    Security:
        - Authentication
        - File is decrypted with AES
        - hasher is created for File Integrity Control
        - Public key is accessed for decrypting the AES
          key
        - Private Key is accessed for verifying the file signature
        - All relevant information is kept client-side"   """
    (username, session) = user.getInfo()
    message = {'filename': filename}
    messageToSend = security.encryptS_AES(json.dumps(message),
                                          session.decode('hex')).encode('hex')
    params = {'data': messageToSend, 'username': username}
    datagen, headers = multipart_encode(params)

    try:
        resp = urllib2.Request('https://localhost:8080/download', datagen,
                               headers)
        data = urllib2.urlopen(resp)
        fn = data.info().getheader('filename')
        date = json.loads(
            security.decryptS_AES(data.info().getheader('data').decode('hex'),
                                  session.decode('hex')))
        aes = data.info().getheader('aes').decode('hex')
        iv = date['iv'].decode('hex')
        signature = date['sign'].decode('hex')
        with open(privpath, 'rb') as f:
            priv = security.importkey_RSA(f.read())
        pub = security.importkey_RSA(getPubKey(username))
        RsaAES = security.decrypt_RSA(priv, aes)
        decipher = security.getDecipher(iv, RsaAES)
        tf = tempfile.NamedTemporaryFile(delete=True)
        out = tempfile.NamedTemporaryFile(delete=True)
        CHUNK = 16 * 1024
        while True:
            chunk = data.read(CHUNK)
            if not chunk:
                break
            tf.write(chunk)
        tf.seek(0)

        hasher = security.Hasher()
        security.decrypt_AES(decipher, tf, out, hasher)
        out.seek(0)
        new = hasher.get()
        comp = open(filefp, 'rb').readlines()
        cenas = out.readlines()
        return diffchecker(comp, cenas)
    except urllib2.HTTPError as e:
        print str(e.code) + ': ' + e.reason
        print 'Currently, you are not a valid user!\nSafeBox Team'
def download(filename, destination, privpath, user):
    """Download function, creates a temporary file to
    where the encrypted file is streamed to, then it is read
    chunk by chunk and decrypted.

    Security:
        - Authentication
        - File is decrypted with AES
        - hasher is created for File Integrity Control
        - Public key is accessed for decrypting the AES
          key
        - Private Key is accessed for verifying the file signature
        - All relevant information is kept client-side"""

    (username, session) = user.getInfo()
    message = {"filename": filename}
    messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex")
    params = {"data": messageToSend, "username": username}
    datagen, headers = multipart_encode(params)
    try:
        resp = urllib2.Request("https://localhost:8080/download", datagen, headers)
        data = urllib2.urlopen(resp)
        fn = data.info().getheader("filename")
        date = json.loads(security.decryptS_AES(data.info().getheader("data").decode("hex"), session.decode("hex")))
        aes = data.info().getheader("aes").decode("hex")
        iv = date["iv"].decode("hex")
        signature = date["sign"].decode("hex")

        with open(privpath, "rb") as f:
            priv = security.importkey_RSA(f.read())
        pub = security.importkey_RSA(getPubKey(username))
        RsaAES = security.decrypt_RSA(priv, aes)
        decipher = security.getDecipher(iv, RsaAES)
        tf = tempfile.NamedTemporaryFile(delete=True)

        CHUNK = 16 * 1024
        while True:
            chunk = data.read(CHUNK)
            if not chunk:
                break
            tf.write(chunk)
        tf.seek(0)

        hasher = security.Hasher()
        with open(os.path.join(str(destination), filename), "wb") as out:
            security.decrypt_AES(decipher, tf, out, hasher)
        new = hasher.get()
        if security.verifyFile(pub, new, signature):
            print "The File was not changed!"
        else:
            print "The File was changed!"
        tf.close()
    except urllib2.HTTPError as e:
        print str(e.code) + ": " + e.reason
        print "Currently, you are not a valid user!\nSafeBox Team"
def diff(user, filename, privpath, filefp):
    """Function for getting the difference between a file in
    the server and a user file, works like download except no file
    is written.

    Security:
        - Authentication
        - File is decrypted with AES
        - hasher is created for File Integrity Control
        - Public key is accessed for decrypting the AES
          key
        - Private Key is accessed for verifying the file signature
        - All relevant information is kept client-side"   """
    (username, session) = user.getInfo()
    message = {"filename": filename}
    messageToSend = security.encryptS_AES(json.dumps(message), session.decode("hex")).encode("hex")
    params = {"data": messageToSend, "username": username}
    datagen, headers = multipart_encode(params)

    try:
        resp = urllib2.Request("https://localhost:8080/download", datagen, headers)
        data = urllib2.urlopen(resp)
        fn = data.info().getheader("filename")
        date = json.loads(security.decryptS_AES(data.info().getheader("data").decode("hex"), session.decode("hex")))
        aes = data.info().getheader("aes").decode("hex")
        iv = date["iv"].decode("hex")
        signature = date["sign"].decode("hex")
        with open(privpath, "rb") as f:
            priv = security.importkey_RSA(f.read())
        pub = security.importkey_RSA(getPubKey(username))
        RsaAES = security.decrypt_RSA(priv, aes)
        decipher = security.getDecipher(iv, RsaAES)
        tf = tempfile.NamedTemporaryFile(delete=True)
        out = tempfile.NamedTemporaryFile(delete=True)
        CHUNK = 16 * 1024
        while True:
            chunk = data.read(CHUNK)
            if not chunk:
                break
            tf.write(chunk)
        tf.seek(0)

        hasher = security.Hasher()
        security.decrypt_AES(decipher, tf, out, hasher)
        out.seek(0)
        new = hasher.get()
        comp = open(filefp, "rb").readlines()
        cenas = out.readlines()
        return diffchecker(comp, cenas)
    except urllib2.HTTPError as e:
        print str(e.code) + ": " + e.reason
        print "Currently, you are not a valid user!\nSafeBox Team"