SourceCode.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. import boto3
  2. import tqdm
  3. import mysql.connector
  4. import sys
  5. from cryptography.fernet import Fernet
  6. from PIL import Image
  7. import os
  8. global s3
  9. s3 = boto3.client('s3', aws_access_key_id='<<your access key>>',
  10. aws_secret_access_key='<<your secret access key>>')
  11. def percent(part, total):
  12. return 100 * float(part) / float(total)
  13. def WriteDataToFilePrompt(data, newline):
  14. filename = input("Filename: ")
  15. file = open(filename, 'w')
  16. location = 0
  17. while location < len(data):
  18. if newline == True:
  19. file.writelines(data[location] + "\n")
  20. else:
  21. file.writelines(data[location])
  22. location += 1
  23. file.close()
  24. class Fibonacci():
  25. def _init_(self):
  26. pass
  27. def Single(self, n): # Returns a single Fibonacci number
  28. if n == 0:
  29. return 0
  30. elif n == 1:
  31. return 1
  32. else:
  33. return self.Single(n - 1) + self.Single(n - 2)
  34. def SetOfFibonacci(self, start, end): # Returns a set of Fibonacci numbers from start to end.
  35. returnData = []
  36. location = start
  37. while location < end:
  38. returnData.append(str(self.Single(location)))
  39. location += 1
  40. return returnData
  41. fib = Fibonacci()
  42. encryptionList = fib.SetOfFibonacci(1, 11)
  43. class FibonacciEncryption():
  44. def _init_(self):
  45. pass
  46. def Encrypt(self, textToEncrypt):
  47. location = 0
  48. encryptedText = []
  49. offsetIndex = 0
  50. while location < len(textToEncrypt):
  51. if offsetIndex < 9: # Let's make sure we keep it in-bounds.
  52. offsetIndex += 1
  53. elif offsetIndex == 9:
  54. offsetIndex = 0
  55. charValue = ord(textToEncrypt[location])
  56. offsetValue = encryptionList[offsetIndex]
  57. finalValue = int(charValue) + int(offsetValue)
  58. encryptedText.append(str(finalValue))
  59. location += 1
  60. location = 0
  61. finalString = ""
  62. while location < len(encryptedText):
  63. finalString += str(encryptedText[location])
  64. if location != len(encryptedText):
  65. finalString += " "
  66. location += 1
  67. return finalString
  68. def Decrypt(self, textToDecrypt): # Anything other than a string input will break this
  69. location = 0
  70. decryptedText = ""
  71. offsetIndex = 0
  72. nextwhitespace = 0
  73. while location < len(textToDecrypt):
  74. if offsetIndex < 9:
  75. offsetIndex += 1
  76. elif offsetIndex == 9:
  77. offsetIndex = 0
  78. nextwhitespace = textToDecrypt.find(" ", location)
  79. if nextwhitespace != -1:
  80. tempTextToDecrypt = textToDecrypt[location:nextwhitespace]
  81. offsetValue = encryptionList[offsetIndex]
  82. finalText = chr(int(tempTextToDecrypt) - int(offsetValue))
  83. decryptedText += finalText
  84. if nextwhitespace < location:
  85. return decryptedText
  86. else:
  87. location = nextwhitespace + 1
  88. fibe = FibonacciEncryption()
  89. class AESEncryption:
  90. def __init__(self, filename): # Constructor
  91. self.filename = filename
  92. def encryption(self): # Allows us to perform file operation
  93. try:
  94. original_information = open(self.filename, 'rb')
  95. except (IOError, FileNotFoundError):
  96. print('File with name {} is not found.'.format(self.filename))
  97. sys.exit(0)
  98. try:
  99. encrypted_file_name = 'cipher_' + self.filename
  100. encrypted_file_object = open(encrypted_file_name, 'wb')
  101. content = original_information.read()
  102. content = bytearray(content)
  103. key1 = 192
  104. print('Encryption Process is in progress...!')
  105. for i, val in tqdm(enumerate(content)):
  106. content[i] = val ^ key1
  107. encrypted_file_object.write(content)
  108. except Exception:
  109. print('Something went wrong with {}'.format(self.filename))
  110. finally:
  111. encrypted_file_object.close()
  112. original_information.close()
  113. class AESDecryption:
  114. def __init__(self, filename):
  115. self.filename = filename
  116. def decryption(self): # produces the original result
  117. try:
  118. encrypted_file_object = open(self.filename, 'rb')
  119. except (FileNotFoundError, IOError):
  120. print('File with name {} is not found'.format(self.filename))
  121. sys.exit(0)
  122. try:
  123. decrypted_file = input(
  124. 'Enter the filename for the Decryption file with extension:') # Decrypted file as output
  125. decrypted_file_object = open(decrypted_file, 'wb')
  126. cipher_text = encrypted_file_object.read()
  127. key1 = 192
  128. cipher_text = bytearray(cipher_text)
  129. print('Decryption Process is in progress...!')
  130. for i, val in tqdm(enumerate(cipher_text)):
  131. cipher_text[i] = val ^ key1
  132. decrypted_file_object.write(cipher_text)
  133. except Exception:
  134. print('Some problem with Ciphertext unable to handle.')
  135. finally:
  136. encrypted_file_object.close()
  137. decrypted_file_object.close()
  138. def genData(data):
  139. # list of binary codes
  140. # of given data
  141. newd = []
  142. for i in data:
  143. newd.append(format(ord(i), '08b'))
  144. return newd
  145. # Pixels are modified according to the
  146. # 8-bit binary data and finally returned
  147. def modPix(pix, data):
  148. datalist = genData(data)
  149. lendata = len(datalist)
  150. imdata = iter(pix)
  151. for i in range(lendata):
  152. # Extracting 3 pixels at a time
  153. pix = [value for value in imdata.__next__()[:3] +
  154. imdata.__next__()[:3] +
  155. imdata.__next__()[:3]]
  156. # Pixel value should be made
  157. # odd for 1 and even for 0
  158. for j in range(0, 8):
  159. if (datalist[i][j] == '0' and pix[j] % 2 != 0):
  160. pix[j] -= 1
  161. elif (datalist[i][j] == '1' and pix[j] % 2 == 0):
  162. if (pix[j] != 0):
  163. pix[j] -= 1
  164. else:
  165. pix[j] += 1
  166. # pix[j] -= 1
  167. # Eighth pixel of every set tells
  168. # whether to stop or read further.
  169. # 0 means keep reading; 1 means thec
  170. # message is over.
  171. if (i == lendata - 1):
  172. if (pix[-1] % 2 == 0):
  173. if (pix[-1] != 0):
  174. pix[-1] -= 1
  175. else:
  176. pix[-1] += 1
  177. else:
  178. if pix[-1] % 2 != 0:
  179. pix[-1] -= 1
  180. pix = tuple(pix)
  181. yield pix[0:3]
  182. yield pix[3:6]
  183. yield pix[6:9]
  184. def encode_enc(newimg, data):
  185. w = newimg.size[0]
  186. (x, y) = (0, 0)
  187. for pixel in modPix(newimg.getdata(), data):
  188. # Putting modified pixels in the new image
  189. newimg.putpixel((x, y), pixel)
  190. if (x == w - 1):
  191. x = 0
  192. y += 1
  193. else:
  194. x += 1
  195. def merge_file(f, ff, fff):
  196. data = data2 = data3 = ""
  197. # Reading data from file1
  198. with open(f) as fp:
  199. data = fp.read()
  200. # Reading data from file2
  201. with open(ff) as fp:
  202. data2 = fp.read()
  203. with open(fff) as fp:
  204. data3 = fp.read()
  205. # Merging 3 files
  206. # To add the data of file2
  207. # from next line
  208. #data += "\n"
  209. data += data2
  210. #data += "\n"
  211. data += data3
  212. with open('final_project.txt', 'w') as fp:
  213. fp.write(data)
  214. def decrypt_new(fileq, filea):
  215. with open(fileq) as f:
  216. with open(filea, "w") as f1:
  217. for line in f:
  218. f1.write(line)
  219. # Encode data into image
  220. def encode():
  221. global new_img_name
  222. img = input("Enter image name(with extension) : ")
  223. image = Image.open(img, 'r')
  224. data = input("Enter data to be encoded : ")
  225. if (len(data) == 0):
  226. raise ValueError('Data is empty')
  227. newimg = image.copy()
  228. encode_enc(newimg, data)
  229. new_img_name = input("Enter the name of new image(with extension) : ")
  230. newimg.save(new_img_name)
  231. # Decode the data in the image
  232. def decode():
  233. imgg = input("Enter image name(with extension) : ")
  234. image = Image.open(imgg, 'r')
  235. data = ''
  236. imgdata = iter(image.getdata())
  237. while (True):
  238. pixels = [value for value in imgdata.__next__()[:3] +
  239. imgdata.__next__()[:3] +
  240. imgdata.__next__()[:3]]
  241. # string of binary data
  242. binstr = ''
  243. for i in pixels[:8]:
  244. if (i % 2 == 0):
  245. binstr += '0'
  246. else:
  247. binstr += '1'
  248. data += chr(int(binstr, 2))
  249. if (pixels[-1] % 2 != 0):
  250. return data
  251. def write_key():
  252. global key
  253. #key = Fernet.generate_key()
  254. key=""
  255. # def load_key():
  256. def encrypt(filename, key):
  257. f = Fernet(key)
  258. with open(filename, "rb") as file:
  259. file_data = file.read()
  260. encrypted_data = f.encrypt(file_data)
  261. with open(str(filename.split(".")[0]) + 'FE.' + str(filename.split(".")[1]), "wb") as file1:
  262. file1.write(encrypted_data)
  263. print("")
  264. def fernet_cipher_and_save_file(filename, fkey):
  265. f = Fernet(fkey)
  266. # fkey = Fernet.generate_key()
  267. with open(filename, "rb") as file:
  268. file_data = file.read()
  269. encrypted_data = f.encrypt(file_data)
  270. with open(str(filename.split(".")[0]) + 'FE.' + str(filename.split(".")[1]), "wb") as file1:
  271. file1.write(encrypted_data)
  272. def decrypt(filename, key):
  273. f = Fernet(key)
  274. with open(filename, "rb") as file:
  275. # read the encrypted data
  276. encrypted_data = file.read()
  277. # decrypt data
  278. decrypted_data = f.decrypt(encrypted_data)
  279. # write the original file
  280. with open(str("decrypt_" + filename.split(".")[0]) + '.' + str(filename.split(".")[1]), "wb") as file7:
  281. file7.write(decrypted_data)
  282. def fernet_decipher_and_save_file(filename, fkey):
  283. f = Fernet(fkey)
  284. with open(filename, "rb") as file:
  285. # read the encrypted data
  286. encrypted_data = file.read()
  287. # decrypt data
  288. decrypted_data = f.decrypt(encrypted_data)
  289. # write the original file
  290. with open(str("decrypt_" + filename.split(".")[0]) + '.' + str(filename.split(".")[1]), "wb") as file7:
  291. file7.write(decrypted_data)
  292. """
  293. def check_key():
  294. my_db = mysql.connector.connect(host="localhost", user="root", passwd="Bruhan@123", database="os_project",
  295. autocommit=True)
  296. cur = my_db.cursor()
  297. cur.execute("select key_code from file_sec where name = '" + uname + "';")
  298. for i in cur:
  299. res1 = i[0]
  300. if len(res1) > 0:
  301. return res1
  302. """
  303. def get_symmetric_cipher_key(user_id):
  304. my_db = mysql.connector.connect(host="localhost", user="root", passwd="Bruhan@123", database="os_project",
  305. autocommit=True)
  306. cur = my_db.cursor()
  307. cur.execute("select key_code from file_sec where name = '" + user_id + "';")
  308. key = ''
  309. for i in cur:
  310. key = i[0]
  311. if len(key) < 1:
  312. key = Fernet.generate_key()
  313. # st = "INSERT INTO file_sec (name,password,key_code) VALUES(%s,%s,%s);"
  314. # key_string = (key, 'utf-8')
  315. st = "UPDATE file_sec SET key_code = '" + key.decode() + "' WHERE name = '" + user_id + "';"
  316. cur.execute(st)
  317. my_db.commit()
  318. else:
  319. return key.encode()
  320. print("HELLO!! WELCOME TO 3 STEP SECURITY FILE STORAGE IN AWS")
  321. print("1. LOGIN")
  322. print("2. SIGN UP")
  323. a = int(input("ENTER YOUR CHOICE: "))
  324. os.system("cls")
  325. global name
  326. global res1
  327. if a == 2:
  328. name = input("ENTER YOUR NAME: ")
  329. passwd = input("ENTER YOUR PASSWORD: ")
  330. write_key()
  331. st = "INSERT INTO file_sec (name,password,key_code) VALUES(%s,%s,%s);"
  332. record = (name, passwd, key)
  333. my_db = mysql.connector.connect(host="localhost", user="root", passwd="Bruhan@123", database="os_project",
  334. autocommit=True)
  335. # my_db = mysql.connector.connect("localhost", "root", "Bruhan@123", "os_project", True)
  336. cur = my_db.cursor()
  337. cur.execute(st, record)
  338. print("YOUR ACCOUNT IS ALL SET!! PLEASE COPY THE KEY BELOW")
  339. print(key)
  340. print("PLEASE PRESS 3 TO PROCEED FURTHER...")
  341. b = int(input())
  342. os.system("cls")
  343. if b == 3:
  344. #print(
  345. # "WELCOME TO FINAL STEP OF SIGN UP PROCEDURE. KINDLY SELECT AN IMAGE AND PASTE UR KEY AS HIDDEN MESSAGE AND ENCODE IT.")
  346. #encode()
  347. #ss = "update file_sec set steg_file_name = %s where name = %s"
  348. #rec = (new_img_name, name)
  349. #cur.execute(ss, rec)
  350. print("YOU ARE ALL SET!!KINDLY EXIT AND RERUN FOR LOGIN")
  351. q = int(input())
  352. if q == 4:
  353. os.system("exit")
  354. else:
  355. print("INVALID CHOICE")
  356. else:
  357. uname = input("ENTER USERNAME : ")
  358. pas = input("ENTER PASSWORD : ")
  359. os.system("cls")
  360. print("IF U WANT TO SELECT A FILE FROM UR PC AND UPLOAD IT TO AWS S3 THEN PRESS 1")
  361. print("IF U WANT TO DOWNLOAD ENCRYPTED FILES FROM AWS S3 AND DECRYPT IT FOR VIEWING - THEN PRESS 2")
  362. fg = int(input())
  363. os.system("cls")
  364. if fg == 1:
  365. res = ''
  366. # call res= getSymmetricCipherKey(userName)
  367. """
  368. my_db = mysql.connector.connect(host="localhost", user="root", passwd="Bruhan@123", database="os_project",
  369. autocommit=True)
  370. cur = my_db.cursor()
  371. cur.execute("select key_code from file_sec where name = '"+uname+"';")
  372. for i in cur:
  373. res = i[0]
  374. """
  375. res= get_symmetric_cipher_key(uname)
  376. print("WELCOME TO THE MAIN PAGE")
  377. print("PLEASE GIVE THE FILE NAME(WITH EXTENSION) WHICH YOU WANT TO STORE IN CLOUD: ")
  378. fname = input()
  379. nf1 = open(str(fname.split(".")[0]) + '1.' + str(fname.split(".")[1]), "wb")
  380. nf2 = open(str(fname.split(".")[0]) + '2.' + str(fname.split(".")[1]), "wb")
  381. nf3 = open(str(fname.split(".")[0]) + '3.' + str(fname.split(".")[1]), "wb")
  382. with open(fname, "r", encoding="utf8") as file:
  383. data = file.readlines()
  384. si = len(data)
  385. for i in range(si // 3):
  386. nf1.write(data[i].encode())
  387. # nf1.write('Why no work!.\n')
  388. for j in range(si // 3, 2 * si // 3):
  389. nf2.write(data[j].encode())
  390. for k in range(2 * si // 3, si):
  391. nf3.write(data[k].encode())
  392. nf1.close()
  393. nf2.close()
  394. nf3.close()
  395. # check_key()
  396. fernet_cipher_and_save_file(str(fname.split(".")[0]) + '1.' + str(fname.split(".")[1]), res)
  397. print("FILE 1st SUBPART HAS BEEN SUCCESSFULLY ENCRYPTED")
  398. fernet_cipher_and_save_file(str(fname.split(".")[0]) + '2.' + str(fname.split(".")[1]), res)
  399. print("FILE 2nd SUBPART HAS BEEN SUCCESSFULLY ENCRYPTED")
  400. fernet_cipher_and_save_file(str(fname.split(".")[0]) + '3.' + str(fname.split(".")[1]), res)
  401. print("FILE 3rd SUBPART HAS BEEN SUCCESSFULLY ENCRYPTED")
  402. s3.upload_file(str(fname.split(".")[0]) + '1FE.' + str(fname.split(".")[1]), 'os-project',
  403. str(fname.split(".")[0]) + '1FE.' + str(fname.split(".")[1]))
  404. print("FILE 1 UPLOADED SUCCESSFULLY")
  405. s3.upload_file(str(fname.split(".")[0]) + '2FE.' + str(fname.split(".")[1]), 'os-project',
  406. str(fname.split(".")[0]) + '2FE.' + str(fname.split(".")[1]))
  407. print("FILE 2 UPLOADED SUCCESSFULLY")
  408. s3.upload_file(str(fname.split(".")[0]) + '3FE.' + str(fname.split(".")[1]), 'os-project',
  409. str(fname.split(".")[0]) + '3FE.' + str(fname.split(".")[1]))
  410. print("FILE 3 UPLOADED SUCCESSFULLY")
  411. print("FILE HAS BEEN UPLOADED SECURELY USING 3SES. PLEASE PRESS 4 TO EXIT THE SYSTEM")
  412. h = int(input())
  413. if h == 4:
  414. os.system("exit")
  415. else:
  416. print("INVALID COMMAND")
  417. else:
  418. bname = input("ENTER THE NAME OF THE FILE THAT YOU ENCRYPTED : ")
  419. df1=s3.download_file('os-project', str(bname.split(".")[0]) + '1FE.' + str(bname.split(".")[1]),
  420. str(bname.split(".")[0]) + '1DE.' + str(bname.split(".")[1]))
  421. print("FILE 1 HAS BEEN SUCCESSFULLY DOWNLOADED FROM AWS")
  422. df2=s3.download_file('os-project', str(bname.split(".")[0]) + '2FE.' + str(bname.split(".")[1]),
  423. str(bname.split(".")[0]) + '2DE.' + str(bname.split(".")[1]))
  424. print("FILE 2 HAS BEEN SUCCESSFULLY DOWNLOADED FROM AWS")
  425. df3=s3.download_file('os-project', str(bname.split(".")[0]) + '3FE.' + str(bname.split(".")[1]),
  426. str(bname.split(".")[0]) + '3DE.' + str(bname.split(".")[1]))
  427. print("FILE 3 HAS BEEN SUCCESSFULLY DOWNLOADED FROM AWS")
  428. """
  429. my_db = mysql.connector.connect(host="localhost", user="root", passwd="Bruhan@123", database="os_project",
  430. autocommit=True)
  431. cur = my_db.cursor()
  432. cur.execute("select key_code from file_sec where name = '" + uname + "';")
  433. res1 = ""
  434. for i in cur:
  435. res1 = i[0]
  436. """
  437. res1 = get_symmetric_cipher_key(uname)
  438. fernet_decipher_and_save_file(str(bname.split(".")[0]) + '1DE.' + str(bname.split(".")[1]),res1)
  439. #str("decrypt_" + bname.split(".")[0]) + '1.' + str(bname.split(".")[1]),res1)
  440. print("SUCCESSFULLY DECRYPTED FILE No 1!!!")
  441. # decrypt(str(bname.split(".")[0])+'2DE.'+str(bname.split(".")[1]),
  442. # str("decrypt_"+bname.split(".")[0])+'2.'+str(bname.split(".")[1]))
  443. fernet_decipher_and_save_file(str(bname.split(".")[0]) + '2DE.' + str(bname.split(".")[1]), res1)
  444. print("SUCCESSFULLY DECRYPTED FILE No 2!!!")
  445. fernet_decipher_and_save_file(str(bname.split(".")[0]) + '3DE.' + str(bname.split(".")[1]), res1)
  446. #str("decrypt_" + bname.split(".")[0]) + '3.' + str(bname.split(".")[1]), res1)
  447. print("SUCCESSFULLY DECRYPTED FILE No 3!!!")
  448. merge_file(str("decrypt_" + bname.split(".")[0]) + '1DE.' + str(bname.split(".")[1]),
  449. str("decrypt_" + bname.split(".")[0]) + '2DE.' + str(bname.split(".")[1]),
  450. str("decrypt_" + bname.split(".")[0]) + '3DE.' + str(bname.split(".")[1]))
  451. print("FILE HAS BEEN SAVED IN UR SPECIFIED DIRECTORY.")