RSA


SUBMITTED BY: Guest

DATE: May 19, 2013, 4:01 a.m.

FORMAT: Python

SIZE: 3.2 kB

HITS: 2025

  1. #
  2. # implementing RSA algorithm(Python Version)
  3. #
  4. #
  5. #
  6. def gcd (a, b):
  7. "Compute GCD of two numbers"
  8. if b == 0: return a
  9. else: return gcd(b, a % b)
  10. def multiplicative_inverse(a, b):
  11. """ Find multiplicative inverse of a modulo b (a > b)
  12. using Extended Euclidean Algorithm """
  13. origA = a
  14. X = 0
  15. prevX = 1
  16. Y = 1
  17. prevY = 0
  18. while b != 0:
  19. temp = b
  20. quotient = a/b
  21. b = a % b
  22. a = temp
  23. temp = X
  24. a = prevX - quotient * X
  25. prevX = temp
  26. temp = Y
  27. Y = prevY - quotient * Y
  28. prevY = temp
  29. return origA + prevY
  30. def generateRSAKeys(p, q):
  31. "Generate RSA Public and Private Keys from prime numbers p & q"
  32. n = p * q
  33. m = (p - 1) * (q - 1)
  34. # Generate a number e so that gcd(n, e) = 1, start with e = 3
  35. e = 3
  36. while 1:
  37. if gcd(m, e) == 1: break
  38. else: e = e + 2
  39. # start with a number d = m/e will be atleast 1
  40. d = multiplicative_inverse(m, e)
  41. # Return a tuple of public and private keys
  42. return ((n,e), (n,d))
  43. if __name__ == "__main__":
  44. print "RSA Encryption algorithm...."
  45. p = long(raw_input("Enter the value of p (prime number):"))
  46. q = long(raw_input("Enter the value of q (prime number):"))
  47. print "Generating public and private keys...."
  48. (publickey, privatekey) = generateRSAKeys(p, q)
  49. print "Public Key (n, e) =", publickey
  50. print "Private Key (n, d) =", privatekey
  51. n, e = publickey
  52. n, d = privatekey
  53. input_num = long(raw_input("Enter a number to be encrypted:"))
  54. encrypted_num = (input_num ** e) % n
  55. print "Encrypted number using public key =", encrypted_num
  56. decrypted_num = encrypted_num ** d % n
  57. print "Decrypted (Original) number using private key =", decrypted_num

comments powered by Disqus