You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

94 lines
2.1 KiB

5 years ago
  1. '''
  2. Created on Dec 14, 2011
  3. @author: pablocelayes
  4. '''
  5. #!/usr/bin/python
  6. # -*- coding: utf-8 -*-
  7. """\
  8. This module generates RSA-keys which are vulnerable to
  9. the Wiener continued fraction attack
  10. (see RSAfracCont.pdf)
  11. The RSA keys are obtained as follows:
  12. 1. Choose two prime numbers p and q
  13. 2. Compute n=pq
  14. 3. Compute phi(n)=(p-1)(q-1)
  15. 4. Choose e coprime to phi(n) such that gcd(e,n)=1
  16. 5. Compute d = e^(-1) mod (phi(n))
  17. 6. e is the publickey; n is also made public (determines the block size); d is the privatekey
  18. Encryption is as follows:
  19. 1. Size of data to be encrypted must be less than n
  20. 2. ciphertext=pow(plaintext,publickey,n)
  21. Decryption is as follows:
  22. 1. Size of data to be decrypted must be less than n
  23. 2. plaintext=pow(ciphertext,privatekey,n)
  24. -------------------------------
  25. RSA-keys are Wiener-vulnerable if d < (n^(1/4))/sqrt(6)
  26. """
  27. import random, MillerRabin, Arithmetic
  28. def getPrimePair(bits=512):
  29. '''
  30. genera un par de primos p , q con
  31. p de nbits y
  32. p < q < 2p
  33. '''
  34. assert bits%4==0
  35. p = MillerRabin.gen_prime(bits)
  36. q = MillerRabin.gen_prime_range(p+1, 2*p)
  37. return p,q
  38. def generateKeys(nbits=1024):
  39. '''
  40. Generates a key pair
  41. public = (e,n)
  42. private = d
  43. such that
  44. n is nbits long
  45. (e,n) is vulnerable to the Wiener Continued Fraction Attack
  46. '''
  47. # nbits >= 1024 is recommended
  48. assert nbits%4==0
  49. p,q = getPrimePair(nbits//2)
  50. n = p*q
  51. phi = Arithmetic.totient(p, q)
  52. # generate a d such that:
  53. # (d,n) = 1
  54. # 36d^4 < n
  55. good_d = False
  56. while not good_d:
  57. d = random.getrandbits(nbits//4)
  58. if (Arithmetic.gcd(d,phi) == 1 and 36*pow(d,4) < n):
  59. good_d = True
  60. e = Arithmetic.modInverse(d,phi)
  61. return e,n,d
  62. if __name__ == "__main__":
  63. print("hey")
  64. for i in range(5):
  65. e,n,d = generateKeys()
  66. print ("Clave Publica:")
  67. print("e =")
  68. print(e)
  69. print("n =")
  70. print(n)
  71. print ("Clave Privada:")
  72. print("d =")
  73. print(d)
  74. print("-----------------------")