Advertisement
Guest User

Untitled

a guest
Nov 16th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. from Crypto.Util import number
  2. import random
  3. from fractions import gcd
  4. import time
  5. import matplotlib.pyplot as plt
  6.  
  7. n_length = 512
  8.  
  9. def egcd(a, b):
  10. if a == 0:
  11. return (b, 0, 1)
  12. else:
  13. g, y, x = egcd(b % a, a)
  14. return (g, x - (b // a) * y, y)
  15.  
  16.  
  17. def modinv(a, m):
  18. g, x, y = egcd(a, m)
  19. if g != 1:
  20. raise Exception('modular inverse does not exist')
  21. else:
  22. return x % m
  23.  
  24. def get_keys():
  25. p = number.getPrime(n_length)
  26. q = number.getPrime(n_length)
  27.  
  28. n = p * q
  29. phi = (p - 1) * (q - 1)
  30.  
  31. e = random.randrange(1, phi)
  32.  
  33. g = gcd(e, phi)
  34. while g != 1:
  35. e = random.randrange(1, phi)
  36. g = gcd(e, phi)
  37.  
  38. d = modinv(e, phi)
  39.  
  40. return ((e, n), (d, n))
  41.  
  42. def encrypt(pk, plaintext):
  43. key, n = pk
  44. cipher = [pow(ord(char), key, n) for char in plaintext]
  45. return cipher
  46.  
  47. def decrypt(pk, ciphertext):
  48. key, n = pk
  49. plain = [chr(pow(char, key, n)) for char in ciphertext]
  50. print plain
  51. return ''.join(plain)
  52.  
  53. public, private = get_keys()
  54. print public, private
  55.  
  56. timing = []
  57. message_len = []
  58. for i in xrange(100):
  59. base_message = "A random message for Foundations of Cybersecurity"
  60. message = base_message + 'i'*i
  61. start = time.time()
  62. cipher = encrypt(public, message)
  63. time_taken = time.time() - start
  64. timing.append(time_taken)
  65. message_len.append(len(message))
  66. print time_taken
  67.  
  68. plt.xlabel("Message Lenght")
  69. plt.ylabel("Time")
  70. plt.plot(message_len, timing)
  71. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement