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