0
我有以下代码,其中'password'是传递给函数的字符串。问题是,当我试图读取在前半段代码中创建的文件时,Python将其解释为空(尽管文件资源管理器和文本编辑器告诉我它包含内容)。这4个打印语句是为了协助调试(发现here)。Python 3.6:读取一个非空的二进制文件被Python解释为空
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 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.
看来,有在[file_out.write(x) for x in (cipher.nonce, tag, ciphertext)]
产生的.bin文件的内容,但我不能让Python阅读。
欢迎所有建议。我正在运行Python 3.6,32位。
谢谢@stovfl - 这个伎俩。 – doubleknavery