- 
                Notifications
    
You must be signed in to change notification settings  - Fork 1.7k
 
Closed
Description
Encrypting files with AES-GCM is raising an error when I try to verify, and I'm utterly stumped on how to fix it. This is a trimmed version which reproduces the error, and hashlib is included to check input/output data.
Running cryptography 2.8 and python 3.7 on windows 10 and CPython.
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from hashlib import sha256
with open('test.txt', 'rb') as infile:
    aes = Cipher(algorithms.AES(b'legoroojlegorooj'), modes.GCM(b'legoroojlegorooj'), default_backend()).encryptor()
    aes.authenticate_additional_data(b'')
    infile.seek(0, 2)
    length = infile.tell()
    chunks = ((length - (length % 256)) // 256) + 1
    infile.seek(0, 0)
    
    with open('out_example.txt', 'wb+') as outfile:
        for i in range(1, chunks+1):
            data = aes.update(infile.read(256))
            outfile.write(data)
        data = aes.finalize()
        outfile.write(data)
        outfile.seek(0, 0)
        outfile.write(b'legoroojlegorooj')
        outfile.write(aes.tag)
    f = open('out_example.txt', 'rb')
    f.seek(32)
    print(sha256(f.read()).hexdigest())
with open('out_example.txt', 'rb+') as infile:
    infile.seek(0, 2)
    length = infile.tell() - 32
    chunks = ((length - (length % 256)) // 256) + 1
    infile.seek(0, 0)
    nonce = infile.read(16)
    gcm_tag = infile.read(16)
    
    aes = Cipher(
        algorithms.AES(b'legoroojlegorooj'),
        modes.GCM(b'legoroojlegorooj', tag=gcm_tag),
        default_backend()
    ).decryptor()
    
    aes.authenticate_additional_data(b'')
    hf = sha256()
    
    with open('outfile.txt', 'wb+') as outfile:
        for i in range(1, chunks+1):
            data = infile.read(256)
            hf.update(data)
            outfile.write(aes.update(data))
        print(hf.hexdigest())
        try:
            outfile.write(aes.finalize())
        except Exception as e:
            raise eThe contents of test.txt is available here. https://gist.github.com/Legorooj/dcb73bfead1663d901e95bbe15d97b2c
Metadata
Metadata
Assignees
Labels
No labels