rsa.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. from __future__ import absolute_import, division, print_function
  5. import abc
  6. try:
  7. # Only available in math in 3.5+
  8. from math import gcd
  9. except ImportError:
  10. from fractions import gcd
  11. import six
  12. from cryptography import utils
  13. from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
  14. from cryptography.hazmat.backends import _get_backend
  15. from cryptography.hazmat.backends.interfaces import RSABackend
  16. @six.add_metaclass(abc.ABCMeta)
  17. class RSAPrivateKey(object):
  18. @abc.abstractmethod
  19. def signer(self, padding, algorithm):
  20. """
  21. Returns an AsymmetricSignatureContext used for signing data.
  22. """
  23. @abc.abstractmethod
  24. def decrypt(self, ciphertext, padding):
  25. """
  26. Decrypts the provided ciphertext.
  27. """
  28. @abc.abstractproperty
  29. def key_size(self):
  30. """
  31. The bit length of the public modulus.
  32. """
  33. @abc.abstractmethod
  34. def public_key(self):
  35. """
  36. The RSAPublicKey associated with this private key.
  37. """
  38. @abc.abstractmethod
  39. def sign(self, data, padding, algorithm):
  40. """
  41. Signs the data.
  42. """
  43. @six.add_metaclass(abc.ABCMeta)
  44. class RSAPrivateKeyWithSerialization(RSAPrivateKey):
  45. @abc.abstractmethod
  46. def private_numbers(self):
  47. """
  48. Returns an RSAPrivateNumbers.
  49. """
  50. @abc.abstractmethod
  51. def private_bytes(self, encoding, format, encryption_algorithm):
  52. """
  53. Returns the key serialized as bytes.
  54. """
  55. @six.add_metaclass(abc.ABCMeta)
  56. class RSAPublicKey(object):
  57. @abc.abstractmethod
  58. def verifier(self, signature, padding, algorithm):
  59. """
  60. Returns an AsymmetricVerificationContext used for verifying signatures.
  61. """
  62. @abc.abstractmethod
  63. def encrypt(self, plaintext, padding):
  64. """
  65. Encrypts the given plaintext.
  66. """
  67. @abc.abstractproperty
  68. def key_size(self):
  69. """
  70. The bit length of the public modulus.
  71. """
  72. @abc.abstractmethod
  73. def public_numbers(self):
  74. """
  75. Returns an RSAPublicNumbers
  76. """
  77. @abc.abstractmethod
  78. def public_bytes(self, encoding, format):
  79. """
  80. Returns the key serialized as bytes.
  81. """
  82. @abc.abstractmethod
  83. def verify(self, signature, data, padding, algorithm):
  84. """
  85. Verifies the signature of the data.
  86. """
  87. RSAPublicKeyWithSerialization = RSAPublicKey
  88. def generate_private_key(public_exponent, key_size, backend=None):
  89. backend = _get_backend(backend)
  90. if not isinstance(backend, RSABackend):
  91. raise UnsupportedAlgorithm(
  92. "Backend object does not implement RSABackend.",
  93. _Reasons.BACKEND_MISSING_INTERFACE,
  94. )
  95. _verify_rsa_parameters(public_exponent, key_size)
  96. return backend.generate_rsa_private_key(public_exponent, key_size)
  97. def _verify_rsa_parameters(public_exponent, key_size):
  98. if public_exponent not in (3, 65537):
  99. raise ValueError(
  100. "public_exponent must be either 3 (for legacy compatibility) or "
  101. "65537. Almost everyone should choose 65537 here!"
  102. )
  103. if key_size < 512:
  104. raise ValueError("key_size must be at least 512-bits.")
  105. def _check_private_key_components(
  106. p, q, private_exponent, dmp1, dmq1, iqmp, public_exponent, modulus
  107. ):
  108. if modulus < 3:
  109. raise ValueError("modulus must be >= 3.")
  110. if p >= modulus:
  111. raise ValueError("p must be < modulus.")
  112. if q >= modulus:
  113. raise ValueError("q must be < modulus.")
  114. if dmp1 >= modulus:
  115. raise ValueError("dmp1 must be < modulus.")
  116. if dmq1 >= modulus:
  117. raise ValueError("dmq1 must be < modulus.")
  118. if iqmp >= modulus:
  119. raise ValueError("iqmp must be < modulus.")
  120. if private_exponent >= modulus:
  121. raise ValueError("private_exponent must be < modulus.")
  122. if public_exponent < 3 or public_exponent >= modulus:
  123. raise ValueError("public_exponent must be >= 3 and < modulus.")
  124. if public_exponent & 1 == 0:
  125. raise ValueError("public_exponent must be odd.")
  126. if dmp1 & 1 == 0:
  127. raise ValueError("dmp1 must be odd.")
  128. if dmq1 & 1 == 0:
  129. raise ValueError("dmq1 must be odd.")
  130. if p * q != modulus:
  131. raise ValueError("p*q must equal modulus.")
  132. def _check_public_key_components(e, n):
  133. if n < 3:
  134. raise ValueError("n must be >= 3.")
  135. if e < 3 or e >= n:
  136. raise ValueError("e must be >= 3 and < n.")
  137. if e & 1 == 0:
  138. raise ValueError("e must be odd.")
  139. def _modinv(e, m):
  140. """
  141. Modular Multiplicative Inverse. Returns x such that: (x*e) mod m == 1
  142. """
  143. x1, x2 = 1, 0
  144. a, b = e, m
  145. while b > 0:
  146. q, r = divmod(a, b)
  147. xn = x1 - q * x2
  148. a, b, x1, x2 = b, r, x2, xn
  149. return x1 % m
  150. def rsa_crt_iqmp(p, q):
  151. """
  152. Compute the CRT (q ** -1) % p value from RSA primes p and q.
  153. """
  154. return _modinv(q, p)
  155. def rsa_crt_dmp1(private_exponent, p):
  156. """
  157. Compute the CRT private_exponent % (p - 1) value from the RSA
  158. private_exponent (d) and p.
  159. """
  160. return private_exponent % (p - 1)
  161. def rsa_crt_dmq1(private_exponent, q):
  162. """
  163. Compute the CRT private_exponent % (q - 1) value from the RSA
  164. private_exponent (d) and q.
  165. """
  166. return private_exponent % (q - 1)
  167. # Controls the number of iterations rsa_recover_prime_factors will perform
  168. # to obtain the prime factors. Each iteration increments by 2 so the actual
  169. # maximum attempts is half this number.
  170. _MAX_RECOVERY_ATTEMPTS = 1000
  171. def rsa_recover_prime_factors(n, e, d):
  172. """
  173. Compute factors p and q from the private exponent d. We assume that n has
  174. no more than two factors. This function is adapted from code in PyCrypto.
  175. """
  176. # See 8.2.2(i) in Handbook of Applied Cryptography.
  177. ktot = d * e - 1
  178. # The quantity d*e-1 is a multiple of phi(n), even,
  179. # and can be represented as t*2^s.
  180. t = ktot
  181. while t % 2 == 0:
  182. t = t // 2
  183. # Cycle through all multiplicative inverses in Zn.
  184. # The algorithm is non-deterministic, but there is a 50% chance
  185. # any candidate a leads to successful factoring.
  186. # See "Digitalized Signatures and Public Key Functions as Intractable
  187. # as Factorization", M. Rabin, 1979
  188. spotted = False
  189. a = 2
  190. while not spotted and a < _MAX_RECOVERY_ATTEMPTS:
  191. k = t
  192. # Cycle through all values a^{t*2^i}=a^k
  193. while k < ktot:
  194. cand = pow(a, k, n)
  195. # Check if a^k is a non-trivial root of unity (mod n)
  196. if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
  197. # We have found a number such that (cand-1)(cand+1)=0 (mod n).
  198. # Either of the terms divides n.
  199. p = gcd(cand + 1, n)
  200. spotted = True
  201. break
  202. k *= 2
  203. # This value was not any good... let's try another!
  204. a += 2
  205. if not spotted:
  206. raise ValueError("Unable to compute factors p and q from exponent d.")
  207. # Found !
  208. q, r = divmod(n, p)
  209. assert r == 0
  210. p, q = sorted((p, q), reverse=True)
  211. return (p, q)
  212. class RSAPrivateNumbers(object):
  213. def __init__(self, p, q, d, dmp1, dmq1, iqmp, public_numbers):
  214. if (
  215. not isinstance(p, six.integer_types)
  216. or not isinstance(q, six.integer_types)
  217. or not isinstance(d, six.integer_types)
  218. or not isinstance(dmp1, six.integer_types)
  219. or not isinstance(dmq1, six.integer_types)
  220. or not isinstance(iqmp, six.integer_types)
  221. ):
  222. raise TypeError(
  223. "RSAPrivateNumbers p, q, d, dmp1, dmq1, iqmp arguments must"
  224. " all be an integers."
  225. )
  226. if not isinstance(public_numbers, RSAPublicNumbers):
  227. raise TypeError(
  228. "RSAPrivateNumbers public_numbers must be an RSAPublicNumbers"
  229. " instance."
  230. )
  231. self._p = p
  232. self._q = q
  233. self._d = d
  234. self._dmp1 = dmp1
  235. self._dmq1 = dmq1
  236. self._iqmp = iqmp
  237. self._public_numbers = public_numbers
  238. p = utils.read_only_property("_p")
  239. q = utils.read_only_property("_q")
  240. d = utils.read_only_property("_d")
  241. dmp1 = utils.read_only_property("_dmp1")
  242. dmq1 = utils.read_only_property("_dmq1")
  243. iqmp = utils.read_only_property("_iqmp")
  244. public_numbers = utils.read_only_property("_public_numbers")
  245. def private_key(self, backend=None):
  246. backend = _get_backend(backend)
  247. return backend.load_rsa_private_numbers(self)
  248. def __eq__(self, other):
  249. if not isinstance(other, RSAPrivateNumbers):
  250. return NotImplemented
  251. return (
  252. self.p == other.p
  253. and self.q == other.q
  254. and self.d == other.d
  255. and self.dmp1 == other.dmp1
  256. and self.dmq1 == other.dmq1
  257. and self.iqmp == other.iqmp
  258. and self.public_numbers == other.public_numbers
  259. )
  260. def __ne__(self, other):
  261. return not self == other
  262. def __hash__(self):
  263. return hash(
  264. (
  265. self.p,
  266. self.q,
  267. self.d,
  268. self.dmp1,
  269. self.dmq1,
  270. self.iqmp,
  271. self.public_numbers,
  272. )
  273. )
  274. class RSAPublicNumbers(object):
  275. def __init__(self, e, n):
  276. if not isinstance(e, six.integer_types) or not isinstance(
  277. n, six.integer_types
  278. ):
  279. raise TypeError("RSAPublicNumbers arguments must be integers.")
  280. self._e = e
  281. self._n = n
  282. e = utils.read_only_property("_e")
  283. n = utils.read_only_property("_n")
  284. def public_key(self, backend=None):
  285. backend = _get_backend(backend)
  286. return backend.load_rsa_public_numbers(self)
  287. def __repr__(self):
  288. return "<RSAPublicNumbers(e={0.e}, n={0.n})>".format(self)
  289. def __eq__(self, other):
  290. if not isinstance(other, RSAPublicNumbers):
  291. return NotImplemented
  292. return self.e == other.e and self.n == other.n
  293. def __ne__(self, other):
  294. return not self == other
  295. def __hash__(self):
  296. return hash((self.e, self.n))