Task5.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Created on Mon Oct 1 06:31:45 2018
  5. @author: varshath
  6. """
  7. from Crypto.Cipher import PKCS1_OAEP
  8. from Crypto.PublicKey import RSA
  9. from timeit import default_timer as timer
  10. def generateFiles():
  11. with open('kbfile.txt', 'w+') as f:
  12. num_chars = 256
  13. f.write("abcd" * num_chars)
  14. with open('mbfile.txt', 'w+') as f:
  15. num_chars = 256 * 1024
  16. f.write("abcd" * num_chars)
  17. def getData(fileName):
  18. x=""
  19. with open(fileName,'r') as file:
  20. x=file.read()
  21. return x
  22. def rsa(message,size):
  23. start = timer()
  24. key = RSA.generate(size)
  25. key_gen_time= timer() - start
  26. cipher = PKCS1_OAEP.new(key.publickey())
  27. buffer=""
  28. chunks=[]
  29. size=214
  30. parts=int(len(message)/size)
  31. x=0
  32. for i in range(parts):
  33. chunks.append(message[size*i:size*(i+1)])
  34. x=i
  35. chunks.append(message[(x+1)*size:])
  36. ciphers=[]
  37. start = timer()
  38. for chunk in chunks:
  39. chunk_bytes=chunk.encode("utf-8")
  40. ciphertext = cipher.encrypt(chunk_bytes)
  41. ciphers.append(ciphertext)
  42. encrypt_time=timer() - start
  43. #decryption
  44. cipher = PKCS1_OAEP.new(key)
  45. start = timer()
  46. for ciphertext in ciphers:
  47. pt = cipher.decrypt(ciphertext)
  48. buffer+=pt.decode("utf-8")
  49. decrypt_time = timer() - start
  50. if buffer==message:
  51. print("successfull encryption and decryption")
  52. else:
  53. print("Incorrect encryption/decryption")
  54. print("time taken for key gen ",(key_gen_time))
  55. print("time taken to encrypt ",(encrypt_time))
  56. print("Time Taken to Encrypt per byte is ",((encrypt_time)/len(message)))
  57. print("time taken to Decrypt ",(decrypt_time))
  58. print("Time Taken to Decrypt per byte is ",((decrypt_time)/len(message)))
  59. generateFiles()
  60. kbData=getData("kbfile.txt")
  61. mbData=getData("mbfile.txt")
  62. rsa(kbData,2048)
  63. rsa(mbData,2048)