_slowmath.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # -*- coding: utf-8 -*-
  2. #
  3. # PubKey/RSA/_slowmath.py : Pure Python implementation of the RSA portions of _fastmath
  4. #
  5. # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
  6. #
  7. # ===================================================================
  8. # The contents of this file are dedicated to the public domain. To
  9. # the extent that dedication to the public domain is not available,
  10. # everyone is granted a worldwide, perpetual, royalty-free,
  11. # non-exclusive license to exercise all rights associated with the
  12. # contents of this file for any purpose whatsoever.
  13. # No rights are reserved.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  19. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  20. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. # ===================================================================
  24. """Pure Python implementation of the RSA-related portions of Crypto.PublicKey._fastmath."""
  25. __revision__ = "$Id$"
  26. __all__ = ['rsa_construct']
  27. import sys
  28. if sys.version_info[0] == 2 and sys.version_info[1] == 1:
  29. from Crypto.Util.py21compat import *
  30. from Crypto.Util.number import size, inverse, GCD
  31. class error(Exception):
  32. pass
  33. class _RSAKey(object):
  34. def _blind(self, m, r):
  35. # compute r**e * m (mod n)
  36. return m * pow(r, self.e, self.n)
  37. def _unblind(self, m, r):
  38. # compute m / r (mod n)
  39. return inverse(r, self.n) * m % self.n
  40. def _decrypt(self, c):
  41. # compute c**d (mod n)
  42. if not self.has_private():
  43. raise TypeError("No private key")
  44. if (hasattr(self,'p') and hasattr(self,'q') and hasattr(self,'u')):
  45. m1 = pow(c, self.d % (self.p-1), self.p)
  46. m2 = pow(c, self.d % (self.q-1), self.q)
  47. h = m2 - m1
  48. if (h<0):
  49. h = h + self.q
  50. h = h*self.u % self.q
  51. return h*self.p+m1
  52. return pow(c, self.d, self.n)
  53. def _encrypt(self, m):
  54. # compute m**d (mod n)
  55. return pow(m, self.e, self.n)
  56. def _sign(self, m): # alias for _decrypt
  57. if not self.has_private():
  58. raise TypeError("No private key")
  59. return self._decrypt(m)
  60. def _verify(self, m, sig):
  61. return self._encrypt(sig) == m
  62. def has_private(self):
  63. return hasattr(self, 'd')
  64. def size(self):
  65. """Return the maximum number of bits that can be encrypted"""
  66. return size(self.n) - 1
  67. def rsa_construct(n, e, d=None, p=None, q=None, u=None):
  68. """Construct an RSAKey object"""
  69. assert isinstance(n, long)
  70. assert isinstance(e, long)
  71. assert isinstance(d, (long, type(None)))
  72. assert isinstance(p, (long, type(None)))
  73. assert isinstance(q, (long, type(None)))
  74. assert isinstance(u, (long, type(None)))
  75. obj = _RSAKey()
  76. obj.n = n
  77. obj.e = e
  78. if d is None:
  79. return obj
  80. obj.d = d
  81. if p is not None and q is not None:
  82. obj.p = p
  83. obj.q = q
  84. else:
  85. # Compute factors p and q from the private exponent d.
  86. # We assume that n has no more than two factors.
  87. # See 8.2.2(i) in Handbook of Applied Cryptography.
  88. ktot = d*e-1
  89. # The quantity d*e-1 is a multiple of phi(n), even,
  90. # and can be represented as t*2^s.
  91. t = ktot
  92. while t%2==0:
  93. t=divmod(t,2)[0]
  94. # Cycle through all multiplicative inverses in Zn.
  95. # The algorithm is non-deterministic, but there is a 50% chance
  96. # any candidate a leads to successful factoring.
  97. # See "Digitalized Signatures and Public Key Functions as Intractable
  98. # as Factorization", M. Rabin, 1979
  99. spotted = 0
  100. a = 2
  101. while not spotted and a<100:
  102. k = t
  103. # Cycle through all values a^{t*2^i}=a^k
  104. while k<ktot:
  105. cand = pow(a,k,n)
  106. # Check if a^k is a non-trivial root of unity (mod n)
  107. if cand!=1 and cand!=(n-1) and pow(cand,2,n)==1:
  108. # We have found a number such that (cand-1)(cand+1)=0 (mod n).
  109. # Either of the terms divides n.
  110. obj.p = GCD(cand+1,n)
  111. spotted = 1
  112. break
  113. k = k*2
  114. # This value was not any good... let's try another!
  115. a = a+2
  116. if not spotted:
  117. raise ValueError("Unable to compute factors p and q from exponent d.")
  118. # Found !
  119. assert ((n % obj.p)==0)
  120. obj.q = divmod(n,obj.p)[0]
  121. if u is not None:
  122. obj.u = u
  123. else:
  124. obj.u = inverse(obj.p, obj.q)
  125. return obj
  126. class _DSAKey(object):
  127. def size(self):
  128. """Return the maximum number of bits that can be encrypted"""
  129. return size(self.p) - 1
  130. def has_private(self):
  131. return hasattr(self, 'x')
  132. def _sign(self, m, k): # alias for _decrypt
  133. # SECURITY TODO - We _should_ be computing SHA1(m), but we don't because that's the API.
  134. if not self.has_private():
  135. raise TypeError("No private key")
  136. if not (1L < k < self.q):
  137. raise ValueError("k is not between 2 and q-1")
  138. inv_k = inverse(k, self.q) # Compute k**-1 mod q
  139. r = pow(self.g, k, self.p) % self.q # r = (g**k mod p) mod q
  140. s = (inv_k * (m + self.x * r)) % self.q
  141. return (r, s)
  142. def _verify(self, m, r, s):
  143. # SECURITY TODO - We _should_ be computing SHA1(m), but we don't because that's the API.
  144. if not (0 < r < self.q) or not (0 < s < self.q):
  145. return False
  146. w = inverse(s, self.q)
  147. u1 = (m*w) % self.q
  148. u2 = (r*w) % self.q
  149. v = (pow(self.g, u1, self.p) * pow(self.y, u2, self.p) % self.p) % self.q
  150. return v == r
  151. def dsa_construct(y, g, p, q, x=None):
  152. assert isinstance(y, long)
  153. assert isinstance(g, long)
  154. assert isinstance(p, long)
  155. assert isinstance(q, long)
  156. assert isinstance(x, (long, type(None)))
  157. obj = _DSAKey()
  158. obj.y = y
  159. obj.g = g
  160. obj.p = p
  161. obj.q = q
  162. if x is not None: obj.x = x
  163. return obj
  164. # vim:set ts=4 sw=4 sts=4 expandtab: