EncryptionDecryption_2.py 878 B

1234567891011121314151617181920
  1. def encrypt(self, key, filename):
  2. chunksize = 128 * 1024
  3. outFile = os.path.join(os.path.dirname(filename), "(Secured)" + os.path.basename(filename))
  4. filesize = str(os.path.getsize(filename)).zfill(16)
  5. IV = Random.new().read(AES.block_size)
  6. print(IV, len(IV))
  7. encryptor = AES.new(key, AES.MODE_CBC, IV)
  8. with open(filename, "rb") as infile:
  9. with open(outFile, "wb") as outfile:
  10. outfile.write(filesize.encode('utf-8'))
  11. outfile.write(IV)
  12. while True:
  13. chunk = infile.read(chunksize)
  14. if len(chunk) == 0:
  15. break
  16. elif len(chunk) % 16 != 0:
  17. chunk += b' ' * (16 - (len(chunk) % 16))
  18. outfile.write(encryptor.encrypt(chunk))
  19. return outFile