diff options
Diffstat (limited to 'filecrypt.py')
-rw-r--r-- | filecrypt.py | 35 |
1 files changed, 19 insertions, 16 deletions
diff --git a/filecrypt.py b/filecrypt.py index da0db9b..755e857 100644 --- a/filecrypt.py +++ b/filecrypt.py @@ -5,12 +5,13 @@ import struct import subprocess import binascii import os +from contextlib import contextmanager FILE_ID_LENGTH = 22 TOKEN_LENGTH = 22 HEADER_LENGTH = 56 -def encrypt_file(filename_in, download_filename, chunk_size=1000000//16): +def generate_keys(download_filename, chunk_size=1000000//16): file_id = secrets.token_urlsafe(16) auth_secret = secrets.token_bytes(16) key = secrets.token_bytes(16) @@ -19,25 +20,27 @@ def encrypt_file(filename_in, download_filename, chunk_size=1000000//16): token_cipher = AES.new(auth_secret, AES.MODE_GCM) token_cipher.update(download_filename.encode()) ciphertext, token_tag = token_cipher.encrypt_and_digest(key) - token = base64.b64encode(ciphertext).rstrip(b'=').decode() + token = base64.b64encode(ciphertext, b'+-').rstrip(b'=').decode() - with open(f'{file_id}.enc', 'wb') as fout, open(filename_in, 'rb') as fin: - fout.write(token_cipher.nonce) # 16 bytes - fout.write(token_tag) # 16 bytes - fout.write(auth_secret) # 16 bytes - fout.write(data_nonce) # 8 bytes - assert fout.tell() == HEADER_LENGTH + def encrypt(filename_in): + with open(f'{file_id}.enc', 'wb') as fout, open(filename_in, 'rb') as fin: + fout.write(token_cipher.nonce) # 16 bytes + fout.write(token_tag) # 16 bytes + fout.write(auth_secret) # 16 bytes + fout.write(data_nonce) # 8 bytes + assert fout.tell() == HEADER_LENGTH - cipher = AES.new(key, AES.MODE_CTR, - initial_value=struct.pack('<Q', 0), nonce=data_nonce) + cipher = AES.new(key, AES.MODE_CTR, + initial_value=struct.pack('<Q', 0), nonce=data_nonce) - block = fin.read(cipher.block_size*chunk_size) - while block: - data = cipher.encrypt(block) - fout.write(data) block = fin.read(cipher.block_size*chunk_size) + while block: + data = cipher.encrypt(block) + fout.write(data) + yield len(data) + block = fin.read(cipher.block_size*chunk_size) - return file_id, token + return file_id, token, encrypt def payload_size(path): return os.stat(path).st_size - HEADER_LENGTH @@ -50,7 +53,7 @@ def decrypt_generator(filename, download_filename, token, seek=0, end=None, chun data_nonce = fin.read(8) assert fin.tell() == HEADER_LENGTH - ciphertext = base64.b64decode(token + '='*((3-len(token)%3)%3)) + ciphertext = base64.b64decode(token + '='*((3-len(token)%3)%3), b'+-') token_cipher = AES.new(auth_secret, AES.MODE_GCM, nonce=token_nonce) token_cipher.update(download_filename.encode()) key = token_cipher.decrypt_and_verify(ciphertext, token_tag) |