EncryptionDecryption.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. #!/usr/bin/python3
  2. """
  3. Created on Wed Aug 03 15:34:06 2016
  4. @author: RAVI TEJA AINAMPUDI
  5. """
  6. from Crypto.Hash import MD5
  7. from Crypto.Cipher import AES
  8. from Crypto import Random
  9. import os
  10. import sys
  11. class DynamicEncryptionAndDecryption(object):
  12. def __init__(self, filename=None):
  13. self.filename = filename
  14. def encrypt(self, key, filename):
  15. chunksize = 128 * 1024
  16. outFile = os.path.join(os.path.dirname(filename), "(Secured)" + os.path.basename(filename))
  17. filesize = str(os.path.getsize(filename)).zfill(16)
  18. IV = Random.new().read(AES.block_size)
  19. print(IV, len(IV))
  20. encryptor = AES.new(key, AES.MODE_CBC, IV)
  21. with open(filename, "rb") as infile:
  22. with open(outFile, "wb") as outfile:
  23. outfile.write(filesize.encode('utf-8'))
  24. outfile.write(IV)
  25. while True:
  26. chunk = infile.read(chunksize)
  27. if len(chunk) == 0:
  28. break
  29. elif len(chunk) % 16 != 0:
  30. chunk += b' ' * (16 - (len(chunk) % 16))
  31. outfile.write(encryptor.encrypt(chunk))
  32. return outFile
  33. def decrypt(self, key, filename):
  34. outFile = os.path.join(os.path.dirname(filename),
  35. os.path.basename(filename).replace("(Secured)", ""))
  36. print(outFile)
  37. chunksize = 128 * 1024
  38. with open(filename, "rb") as infile:
  39. filesize = infile.read(16)
  40. IV = infile.read(16)
  41. decryptor = AES.new(key, AES.MODE_CBC, IV)
  42. with open(outFile, "wb") as outfile:
  43. while True:
  44. chunk = infile.read(chunksize)
  45. if len(chunk) == 0:
  46. break
  47. outfile.write(decryptor.decrypt(chunk))
  48. outfile.truncate(int(filesize))
  49. return outFile
  50. @staticmethod
  51. def allfiles(path=os.getcwd()):
  52. allFiles = []
  53. for root, subfiles, files in os.walk(path):
  54. for dir_name in subfiles:
  55. allFiles.append(os.path.join(root, dir_name))
  56. for file_name in files:
  57. allFiles.append(os.path.join(root, file_name))
  58. return allFiles
  59. def choices():
  60. ed_object = DynamicEncryptionAndDecryption()
  61. choice = input("Do you want to L - List the Files, E - Encrypt or D - Decrypt? ==")
  62. print("\n")
  63. perform_multiple_encryption = input(f"Do you want to perform multi-layered encryption? Y-Yes or N-No: ")
  64. if perform_multiple_encryption.lower() not in ("yes", "y"):
  65. perform_multiple_encryption = False
  66. password = input("Please enter the `Password/Key` to be used: ")
  67. else:
  68. encFiles = ed_object.allfiles()
  69. if choice == "E":
  70. print("")
  71. subchoice = input("Want to encrypt all the Files ? Y- Yes or N - No ? :")
  72. if subchoice == "Y":
  73. for Tfiles in encFiles:
  74. if os.path.basename(Tfiles).startswith("(Secured)"):
  75. print(f"{Tfiles} is already encrypted")
  76. pass
  77. elif Tfiles == os.path.join(os.getcwd(), sys.argv[0]):
  78. pass
  79. else:
  80. ed_object.encrypt(MD5.new(password).digest(), str(Tfiles))
  81. print(f"Done Encryption for {Tfiles}")
  82. os.remove(Tfiles)
  83. elif subchoice == "N":
  84. print("")
  85. filename = input("Enter the Filename to Encrypt: ")
  86. if not os.path.exists(filename):
  87. print(f"Given file {filename} does not exist")
  88. sys.exit(0)
  89. elif filename.startswith("(Secured)"):
  90. print(f"File {filename} was already encrypted")
  91. sys.exit()
  92. else:
  93. ed_object.encrypt(MD5.new(password).digest(), filename)
  94. print(f"Done Encryption of {filename}")
  95. os.remove(filename)
  96. else:
  97. print("\n Enter either Y or N")
  98. elif choice == "D":
  99. print("")
  100. filename = input("Enter the filename to decrypt: ")
  101. if not os.path.exists(filename):
  102. print(f"Given file {filename} does not exist")
  103. sys.exit(0)
  104. elif not filename.startswith("(Secured)"):
  105. print("{filename} file was never encrypted")
  106. sys.exit()
  107. else:
  108. ed_object.decrypt(MD5.new(password).digest(), filename)
  109. print(f"Done Decryption for {filename}")
  110. os.remove(filename)
  111. elif choice == "L":
  112. print(" \n The files present in the current directory are: ")
  113. file_list = []
  114. for content in os.listdir(".."):
  115. file_list.append(content)
  116. print(file_list)
  117. else:
  118. print("\n Please choose a valid command. Either E or D")
  119. sys.exit()
  120. if __name__ == "__main__":
  121. # choices()
  122. pass