2017-05-11 14 views
0

다음 코드를 가지고 있습니다. 여기서 '암호'는 함수에 전달되는 문자열입니다. 문제는 코드의 첫 번째 절반에서 작성된 파일을 읽으려고 할 때 파이썬이 파일 탐색기와 텍스트 편집기가 컨텐츠를 포함한다고 알려주고 있음에도 불구하고 파이썬이 파일을 비어있는 것으로 해석한다는 것입니다. 4 개의 print 서술문은 디버깅을 돕기위한 것입니다 (here 발견).파이썬 3.6 : 비어 있지 않은 바이너리 파일 읽기는 파이썬에서 비어있는 것으로 해석됩니다.

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 파일의 내용이 있다고 나타납니다,하지만 난 파이썬은 그것을 읽을 얻을 수 없다 .

모든 제안을 환영합니다. 32 비트 Python 3.6을 실행 중입니다.

답변

0

close 또는 file_out.write(x) 다음 파일이므로 buffer에서 파일에 쓰고 있습니다.

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

감사합니다. @stovfl -이 트릭을했습니다. – doubleknavery