Advertisement
makispaiktis

RSA

Apr 24th, 2022 (edited)
387
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. import sympy
  2.  
  3. # 1. Find Co-prime
  4. def find_coprime(phi):
  5.     e = 2
  6.     flag = False
  7.     while e < phi:
  8.         if phi % e != 0:
  9.             break
  10.         else:
  11.             e = e + 1
  12.             flag = True
  13.     if not flag:
  14.         print("There is no co-prime with phi = " + str(phi))
  15.         return -1000
  16.     else:
  17.         return e
  18.  
  19. # 2. Find 'd' having initial 'k'
  20. def find_d(e, phi):
  21.     d = 2
  22.     while (d * e) % phi != 1:
  23.         d = d + 1
  24.     return d
  25.  
  26.  
  27. # MAIN FUNCTION
  28. # Public key (n, e)
  29. # Private key (n, d)
  30. LIM1 = 10**2
  31. LIM2 = 10**3
  32. x = sympy.randprime(LIM1, LIM2)
  33. y = sympy.randprime(LIM1, LIM2)
  34. while x == y:
  35.     y = sympy.randprime(LIM1, LIM2)
  36. n = x * y
  37. phi = (x-1) * (y-1)
  38. e = find_coprime(phi)
  39. d = find_d(e, phi)
  40. print("Public key  = (n, e) = (" + str(n) + ", " + str(e) + ")")
  41. print("Private key = (n, d) = (" + str(n) + ", " + str(d) + ")")
  42. message = 20
  43. E = (message ** e) % n          # Encoded
  44. D = (E ** d) % n                # Decoded
  45. print()
  46. print("message = " + str(message))
  47. print("Encoded = " + str(E))
  48. print("Decoded = " + str(D))
  49. answer = input("Would you like to see the 2 random primes? ")
  50. yes_list = ["yes", "yeah", "yep", "of course"]
  51. if answer.lower() in yes_list:
  52.     print("x = " + str(x) + ", y = " + str(y))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement