Guest User

Untitled

a guest
Jan 30th, 2017
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.23 KB | None | 0 0
  1. import os
  2.  
  3. def rand_int(nbytes):
  4. return int.from_bytes(os.urandom(nbytes), byteorder='little')
  5.  
  6. def rand_less_than(upper_bound):
  7. while True:
  8. r = rand_int(((upper_bound).bit_length() + 7) // 8)
  9. if r < upper_bound:
  10. return r
  11.  
  12. def is_prime(p):
  13. for _ in range(5):
  14. a = rand_less_than(p)
  15. if not pow(a, p - 1, p) == 1:
  16. return False
  17. return True
  18.  
  19. def choose_parameters():
  20. while True:
  21. modulus = rand_int(1024 // 8)
  22. if is_prime(modulus):
  23. break
  24. base = rand_less_than(modulus)
  25. return base, modulus
  26.  
  27. class Peep:
  28. def __init__(self, base, modulus):
  29. self.base = base
  30. self.modulus = modulus
  31. self.private = rand_less_than(modulus)
  32. self.public = pow(base, self.private, modulus)
  33.  
  34. def send(self):
  35. return self.public
  36.  
  37. def receive(self, B):
  38. self.shared_secret = pow(B, self.private, self.modulus)
  39.  
  40. if __name__ == '__main__':
  41. base, modulus = choose_parameters()
  42. alice = Peep(base, modulus)
  43. bob = Peep(base, modulus)
  44.  
  45. A = alice.send()
  46. B = bob.send()
  47.  
  48. alice.receive(B)
  49. bob.receive(A)
  50.  
  51. assert alice.shared_secret == bob.shared_secret
Advertisement
Add Comment
Please, Sign In to add comment