-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencrypt.py
48 lines (39 loc) · 1.58 KB
/
encrypt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from Crypto.Cipher import AES
import secrets
import binascii
import os
def pad(data):
padding_length = AES.block_size - len(data) % AES.block_size
padding = bytes([padding_length] * padding_length)
return data + padding
def unpad(data):
padding_length = data[-1]
return data[:-padding_length]
def encrypt_text(key, plaintext):
iv = secrets.token_bytes(AES.block_size)
cipher = AES.new(binascii.unhexlify(key), AES.MODE_CBC, iv)
padded_data = pad(plaintext.encode())
encrypted = iv + cipher.encrypt(padded_data)
result = binascii.hexlify(encrypted).decode()
# Securely clear sensitive data
del padded_data, plaintext, key
return result
def encrypt_file(key, filepath, progress_callback=None):
iv = secrets.token_bytes(AES.block_size)
cipher = AES.new(binascii.unhexlify(key), AES.MODE_CBC, iv)
encrypted_filepath = filepath + '.enc'
filesize = os.path.getsize(filepath)
total_chunks = (filesize // (1024 * AES.block_size)) + 1
with open(filepath, 'rb') as f_in, open(encrypted_filepath, 'wb') as f_out:
f_out.write(iv)
for i, chunk in enumerate(iter(lambda: f_in.read(1024 * AES.block_size), b'')):
if len(chunk) % AES.block_size != 0:
chunk = pad(chunk)
f_out.write(cipher.encrypt(chunk))
if progress_callback:
progress_callback((i + 1) / total_chunks * 100)
with open(filepath + "_key.txt", 'w') as key_file:
key_file.write(key)
# Securely clear sensitive data
del iv, key, cipher
return encrypted_filepath