Add compress.py
This commit is contained in:
parent
124dd6c831
commit
7e2a7046a5
42
compress.py
Normal file
42
compress.py
Normal file
@ -0,0 +1,42 @@
|
||||
import os
|
||||
import re
|
||||
import gzip
|
||||
|
||||
|
||||
def recurse(path, maxsize="50M"):
|
||||
max = parse_size(maxsize)
|
||||
for f in os.listdir(path):
|
||||
uri = os.path.join(path, f)
|
||||
if os.path.isfile(uri):
|
||||
size = os.path.getsize(uri)
|
||||
Hsize = str(human_readable_size(size, 0))
|
||||
print(f + " : " + Hsize)
|
||||
if size > max:
|
||||
compress(uri)
|
||||
elif os.path.isdir(uri):
|
||||
recurse(uri)
|
||||
|
||||
|
||||
def compress(file):
|
||||
with open(file, 'rb') as infile:
|
||||
with gzip.open(file + ".gz", 'wb') as zipfile:
|
||||
while chunk := infile.read(64 * 1024):
|
||||
zipfile.write(chunk)
|
||||
print(file + " compressed")
|
||||
pass
|
||||
|
||||
|
||||
def human_readable_size(size, decimal_places=2):
|
||||
for unit in ['B', 'K', 'M', 'G', 'T']:
|
||||
if size < 1024.0:
|
||||
break
|
||||
size /= 1024.0
|
||||
return f"{size:.{decimal_places}f}{unit}"
|
||||
|
||||
|
||||
def parse_size(size):
|
||||
units = {"B": 1, "K": 2**10, "M": 2**20, "G": 2**30, "T": 2**40}
|
||||
if size[-1].isdigit():
|
||||
size = size + 'K'
|
||||
number, unit = re.match(r"([0-9]+)([BKMGT])", size, re.I).groups()
|
||||
return int(float(number)*units[unit])
|
12
crypt.py
12
crypt.py
@ -33,11 +33,8 @@ def encrypt_file(key, in_file, out_file=None, chunksize=64 * 1024):
|
||||
outfile.write(struct.pack('<Q', filesize))
|
||||
outfile.write(cipher.iv)
|
||||
|
||||
while True:
|
||||
chunk = infile.read(chunksize)
|
||||
if len(chunk) == 0:
|
||||
break
|
||||
elif len(chunk) % 16 != 0:
|
||||
while chunk := infile.read(chunksize):
|
||||
if len(chunk) % 16 != 0:
|
||||
chunk += b' ' * (16 - len(chunk) % 16)
|
||||
|
||||
outfile.write(cipher.encrypt(chunk))
|
||||
@ -61,10 +58,7 @@ def decrypt_file(key, in_file, out_file=None, chunksize=24 * 1024):
|
||||
decryptor = AES.new(key, AES.MODE_CBC, iv)
|
||||
|
||||
with open(out_file, 'wb') as outfile:
|
||||
while True:
|
||||
chunk = infile.read(chunksize)
|
||||
if len(chunk) == 0:
|
||||
break
|
||||
while chunk := infile.read(chunksize):
|
||||
outfile.write(decryptor.decrypt(chunk))
|
||||
|
||||
outfile.truncate(origsize)
|
12
main.py
12
main.py
@ -1,9 +1,17 @@
|
||||
from crypt import *
|
||||
from Crypto.Random import get_random_bytes
|
||||
|
||||
from compress import *
|
||||
|
||||
key = get_random_bytes(32) # 32 bytes * 8 = 256 bits (1 byte = 8 bits)
|
||||
print(key)
|
||||
|
||||
encrypt_file(key, 'original_file.txt')
|
||||
file = "original_file.txt"
|
||||
cfile = file+'.enc'
|
||||
|
||||
decrypt_file(key, 'original_file.txt.enc')
|
||||
encrypt_file(key, file, cfile)
|
||||
|
||||
decrypt_file(key, cfile)
|
||||
|
||||
rootdir="test"
|
||||
recurse(rootdir)
|
||||
|
Loading…
x
Reference in New Issue
Block a user