2017-05-11 5 views
0

Ich habe den folgenden Code, wobei 'Passwort' eine Zeichenfolge ist, die in die Funktion übergeben wird. Das Problem ist so, dass Python beim Versuch, die in der ersten Hälfte des Codes erstellte Datei zu lesen, sie als leer interpretiert (obwohl der Datei-Explorer und die Texteditoren mir mitteilen, dass sie Inhalt enthält). Die 4 print-Anweisungen sollen beim Debuggen helfen (gefunden here).Python 3.6: Das Lesen einer nicht leeren Binärdatei wird von Python als leer interpretiert

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)] 

Die Konsolenausgabe ist als solche:

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.

Es scheint, dass es in der .bin-Datei auf [file_out.write(x) for x in (cipher.nonce, tag, ciphertext)] produzierte Inhalte, aber ich kann nicht Python bekommen, es zu lesen .

Alle Vorschläge begrüßen. Ich verwende Python 3.6, 32-Bit.

Antwort

0

Sie müssen close oder sogar flush die Datei nach file_out.write(x), so dass Ihre Daten von buffer in die Datei schreiben.

[file_out.write(x) for x in (cipher.nonce, tag, ciphertext)] 
file_out.close() 
+0

Dank @stovfl - das hat den Trick. – doubleknavery