I've recently started looking into encryption in python and I came across with pycryptodome library. I made this simple program that encrypt/decrypt a file using AES-GCM. Could someone take a look if I implemented the encryption and authentication correctly? For sake of simplicity, I'm posting only the encryption and makeKey functions.
import os
import struct
import secrets
import hahslib
from Cryptodome.Cipher import AES
def makeKey(password, salt):
key = hashlib.pbkdf2_hmac('sha512',password.encode('ascii'), salt, 1000000)
return key[:32]
def encrypt(password, inputFileName):
#creates the needed variables for encryption
salt = secrets.token_bytes(16)
key = makeKey(password, salt)
nonce = secrets.token_bytes(AES.block_size)
cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
#put the file size, salt and nonce in outputfile
fileSize = os.path.getsize(inputFileName)
with open("output", "wb") as outputFile:
outputFile.write(struct.pack('<Q', fileSize))
outputFile.write(salt)
outputFile.write(nonce)
#beginning of encryption itself
chunkSize = 64 * 1024
with open(inputFileName, "rb") as inputFile:
while True:
chunk = inputFile.read(chunkSize)
if len(chunk) == 0:
outputFile.write(cipher.digest())
break
outputFile.write(cipher.encrypt(chunk))