0

I have the following code, where 'password' is a string which is passed into the function. The issue is such that when I attempt to read the file created in the first half of the code, Python interprets it as being empty (despite the fact that File Explorer and text editors tell me it contains content). The 4 print statements are to assist with debugging (found here).

def encryptcredentials(username, password):
    # Create key randomly and save to file
    key = get_random_bytes(16)
    keyfile = open("key.bin", "wb").write(key)

    password = password.encode('utf-8')

    path = "encrypted.bin"

    # The following code generates a new AES128 key and encrypts a piece of data into a file
    cipher = AES.new(key, AES.MODE_EAX)
    ciphertext, tag = cipher.encrypt_and_digest(password)

    file_out = open(path, "wb")
    [file_out.write(x) for x in (cipher.nonce, tag, ciphertext)]

    print("the path is {!r}".format(path))
    print("path exists: ", os.path.exists(path))
    print("it is a file: ", os.path.isfile(path))
    print("file size is: ", os.path.getsize(path))

    # At the other end, the receiver can securely load the piece of data back, if they know the key.
    file_in = open(path, "rb")
    nonce, tag, ciphertext = [file_in.read(x) for x in (16, 16, -1)]

The console output is as such:

the path is 'encrypted.bin'
path exists: True
it is a file: True
file size is: 0

Here's an image of how the file is displayed in File Explorer.

It appears that there's content in the .bin file produced at [file_out.write(x) for x in (cipher.nonce, tag, ciphertext)], but I can't get Python to read it.

Welcoming all suggestions. I'm running Python 3.6, 32-bit.

1 Answer 1

0

You have to close or even flush the file after file_out.write(x), so your data are writing from buffer to the file.

[file_out.write(x) for x in (cipher.nonce, tag, ciphertext)]
file_out.close()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.