コード例 #1
0
ファイル: client.py プロジェクト: wcpun/DFS
def put(user_id, fileName):
    # read data from input file
    with open(fileName, 'rb') as fin:
        bytes = fin.read(BYTE_SIZE)
        fileSize = len(bytes)
        logging.debug("Bytes read with length {0}.".format(fileSize))

    # begin chunking
    chunkObj = Chunker()
    cuts = chunkObj.chunking(bytes)
    logging.debug("Num of Cuts: {0}".format(len(cuts)))
    # for index, chunk in enumerate(chunkObj.divide_chunk(bytes, cuts)):
    #     logging.debug("Chunk {0}: {1}".format(index, chunk))
    logging.info("Chunking completed.\n")

    # create meta data
    fid = fileName + str(user_id)
    cryptObj = Crypto(fid, 'client')
    iv = cryptObj.gen_iv(bytes)
    metaObj = Meta(user_id, fileName, fileSize, iv)
    logging.debug("FileName: {0}".format(metaObj.fileName))
    logging.debug("IV: {0}\n".format(iv))

    # gen keys
    try:
        keys = []
        with con("localhost", 18862) as keyserver:
            if keyserver.root.isExist(fid):
                logging.error("File Already Exist.")
                exit(1)
            for i, chunk in enumerate(chunkObj.divide_chunk(bytes, cuts)):
                key = keyserver.root.gen_key(fid, chunk)
                if not key:
                    logging.error("Key is empty.")
                    exit(1)
                keys.append(key)
                logging.debug("Key {0}: {1}".format(i, key))
    except:
        logging.error("Cannot generate key.")
        exit(1)
    logging.info("Key generation completed.\n")

    # encrypt chunks
    ciphers = []
    count = 0
    for chunk, key in zip(chunkObj.divide_chunk(bytes, cuts), keys):
        cipher = cryptObj.encode(chunk, key, iv)
        ciphers.append(cipher)
        # logging.debug("Cipher {0}: {1}".format(count, cipher))
        count += 1
    del bytes
    del keys
    logging.info("Encryption completed.\n")

    # send ciphers to server
    try:
        with con("localhost", 18861) as master:
            if master.root.put(metaObj):
                for cipher in ciphers:
                    master.root.put(metaObj, cipher)
                    logging.info("Chunk with size {0} uploaded.".format(
                        len(cipher)))
            else:
                logging.error("File Already Exist.")
                exit(1)
    except:
        logging.error("Cannot upload file.")
        exit(1)