Exemple #1
0
def save_bits_to_file(file_path: str, bits: str, key: bytes, zfec: bool):
    """
    save/write bits to a file

    file_path -- the path to write to
    bits -- the bits to write
    key -- key userd for file decryption
    zfec -- needed if reed solomon was used to encode bits
    """

    bitstring = Bits(bin=bits)

    # zip
    print("Unziping...")
    in_ = io.BytesIO()
    in_.write(bitstring.bytes)
    in_.seek(0)
    # always fails without this but sometimes work with this, unsure why
    filetype = magic.from_buffer(in_.read())
    print(filetype)
    in_.seek(0)
    with gzip.GzipFile(fileobj=in_, mode="rb") as fo:
        bitstring = fo.read()
    # zip

    # loading data back from bytes to utf-8 string to deserialize
    data = json.loads(bitstring.decode("utf-8"))

    # decoding previously encoded base64 bytes data to get bytes back
    tag = base64.b64decode(data["tag"])
    ciphertext = base64.b64decode(data["data"])

    filename = data["filename"]

    # decrypting data
    cipher = AES.new(key, AES.MODE_EAX, nonce=SALT)
    data_bytes = cipher.decrypt(ciphertext)

    print("Checking integrity...")

    try:
        cipher.verify(tag)
    except ValueError:
        raise WrongPassword("Key incorrect or message corrupted")

    bitstring = Bits(data_bytes)

    if zfec:
        bitstring = Bits("0b" + decode_zfec(data_bytes).decode("utf-8"))

    # If filepath not passed in use default otherwise used passed in filepath
    if file_path == None:
        filepath = filename
    else:
        filepath = file_path

    with open(filepath, "wb") as f:
        bitstring.tofile(f)