Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import os
- import struct
- from Crypto.Cipher import AES
- import hashlib
- import getpass
- def encryption_file(in_filename, key, chunksize=64*1024):
- out_filename = in_filename + '.enc'
- TheHash = hashlib.sha256(key.encode('utf-8')).hexdigest()
- key = TheHash[0:32]
- IV = b'rp1\\\xe6@\x04\x13\x7f\x81\x1d<\x0b\x13\x1a@'
- encryptor = AES.new(key, AES.MODE_CBC, IV)
- file_size = os.path.getsize(in_filename)
- with open(in_filename, 'rb') as infile:
- with open(out_filename, 'wb') as outfile:
- outfile.write(struct.pack('<Q', file_size))
- outfile.write(IV)
- while True:
- chunk = infile.read(chunksize)
- if len(chunk) == 0:
- break
- elif len(chunk) % 16 != 0:
- chunk += ' '.encode('utf-8') * (16 - len(chunk) % 16)
- text = encryptor.encrypt(chunk)
- print('[DEBUG]: encrypted:', text)
- outfile.write(text)
- os.unlink(in_filename)
- def decrypt_file(in_filename, key, chunksize=64*1024):
- out_filename = os.path.splitext(filename)[0]
- TheHash2 = hashlib.sha256(key.encode('utf-8')).hexdigest()
- key = TheHash2[0:32]
- #IV = b'rp1\\\xe6@\x04\x13\x7f\x81\x1d<\x0b\x13\x1a@'
- #print(len(IV))
- with open(filename, 'rb') as infile:
- file_size = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
- IV = infile.read(16) # len(IV)
- decryptor = AES.new(key, AES.MODE_CBC, IV)
- with open(out_filename, 'wb') as outfile:
- while True:
- chunk = infile.read(chunksize)
- if len(chunk) == 0:
- break
- text = decryptor.decrypt(chunk)
- print('[DEBUG]: decrypted:', text)
- outfile.write(text)
- outfile.truncate(file_size)
- os.unlink(in_filename)
- #----------------------------------------------------------
- choice = input("(E)ncrypt or (D)ecrypt: ").lower()
- if choice == 'e':
- #filename = input("Enter filename: ")
- #key = getpass.getpass("Enter password: ")
- filename = 'test.txt'
- key = 'hello world'
- encryption_file(filename, key)
- elif choice == 'd':
- #filename = input("Enter filename: ")
- #key = getpass.getpass("Enter password: ")
- filename = 'test.txt.enc'
- key = 'hello world'
- decrypt_file(filename, key)
- else:
- print("Select E or D")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement