DSA.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. # -*- coding: utf-8 -*-
  2. #
  3. # PublicKey/DSA.py : DSA signature primitive
  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. """DSA public-key signature algorithm.
  25. DSA_ is a widespread public-key signature algorithm. Its security is
  26. based on the discrete logarithm problem (DLP_). Given a cyclic
  27. group, a generator *g*, and an element *h*, it is hard
  28. to find an integer *x* such that *g^x = h*. The problem is believed
  29. to be difficult, and it has been proved such (and therefore secure) for
  30. more than 30 years.
  31. The group is actually a sub-group over the integers modulo *p*, with *p* prime.
  32. The sub-group order is *q*, which is prime too; it always holds that *(p-1)* is a multiple of *q*.
  33. The cryptographic strength is linked to the magnitude of *p* and *q*.
  34. The signer holds a value *x* (*0<x<q-1*) as private key, and its public
  35. key (*y* where *y=g^x mod p*) is distributed.
  36. In 2012, a sufficient size is deemed to be 2048 bits for *p* and 256 bits for *q*.
  37. For more information, see the most recent ECRYPT_ report.
  38. DSA is reasonably secure for new designs.
  39. The algorithm can only be used for authentication (digital signature).
  40. DSA cannot be used for confidentiality (encryption).
  41. The values *(p,q,g)* are called *domain parameters*;
  42. they are not sensitive but must be shared by both parties (the signer and the verifier).
  43. Different signers can share the same domain parameters with no security
  44. concerns.
  45. The DSA signature is twice as big as the size of *q* (64 bytes if *q* is 256 bit
  46. long).
  47. This module provides facilities for generating new DSA keys and for constructing
  48. them from known components. DSA keys allows you to perform basic signing and
  49. verification.
  50. >>> from Crypto.Random import random
  51. >>> from Crypto.PublicKey import DSA
  52. >>> from Crypto.Hash import SHA
  53. >>>
  54. >>> message = "Hello"
  55. >>> key = DSA.generate(1024)
  56. >>> h = SHA.new(message).digest()
  57. >>> k = random.StrongRandom().randint(1,key.q-1)
  58. >>> sig = key.sign(h,k)
  59. >>> ...
  60. >>> if key.verify(h,sig):
  61. >>> print "OK"
  62. >>> else:
  63. >>> print "Incorrect signature"
  64. .. _DSA: http://en.wikipedia.org/wiki/Digital_Signature_Algorithm
  65. .. _DLP: http://www.cosic.esat.kuleuven.be/publications/talk-78.pdf
  66. .. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf
  67. """
  68. __revision__ = "$Id$"
  69. __all__ = ['generate', 'construct', 'error', 'DSAImplementation', '_DSAobj']
  70. import sys
  71. if sys.version_info[0] == 2 and sys.version_info[1] == 1:
  72. from Crypto.Util.py21compat import *
  73. from Crypto.PublicKey import _DSA, _slowmath, pubkey
  74. from Crypto import Random
  75. try:
  76. from Crypto.PublicKey import _fastmath
  77. except ImportError:
  78. _fastmath = None
  79. class _DSAobj(pubkey.pubkey):
  80. """Class defining an actual DSA key.
  81. :undocumented: __getstate__, __setstate__, __repr__, __getattr__
  82. """
  83. #: Dictionary of DSA parameters.
  84. #:
  85. #: A public key will only have the following entries:
  86. #:
  87. #: - **y**, the public key.
  88. #: - **g**, the generator.
  89. #: - **p**, the modulus.
  90. #: - **q**, the order of the sub-group.
  91. #:
  92. #: A private key will also have:
  93. #:
  94. #: - **x**, the private key.
  95. keydata = ['y', 'g', 'p', 'q', 'x']
  96. def __init__(self, implementation, key):
  97. self.implementation = implementation
  98. self.key = key
  99. def __getattr__(self, attrname):
  100. if attrname in self.keydata:
  101. # For backward compatibility, allow the user to get (not set) the
  102. # DSA key parameters directly from this object.
  103. return getattr(self.key, attrname)
  104. else:
  105. raise AttributeError("%s object has no %r attribute" % (self.__class__.__name__, attrname,))
  106. def sign(self, M, K):
  107. """Sign a piece of data with DSA.
  108. :Parameter M: The piece of data to sign with DSA. It may
  109. not be longer in bit size than the sub-group order (*q*).
  110. :Type M: byte string or long
  111. :Parameter K: A secret number, chosen randomly in the closed
  112. range *[1,q-1]*.
  113. :Type K: long (recommended) or byte string (not recommended)
  114. :attention: selection of *K* is crucial for security. Generating a
  115. random number larger than *q* and taking the modulus by *q* is
  116. **not** secure, since smaller values will occur more frequently.
  117. Generating a random number systematically smaller than *q-1*
  118. (e.g. *floor((q-1)/8)* random bytes) is also **not** secure. In general,
  119. it shall not be possible for an attacker to know the value of `any
  120. bit of K`__.
  121. :attention: The number *K* shall not be reused for any other
  122. operation and shall be discarded immediately.
  123. :attention: M must be a digest cryptographic hash, otherwise
  124. an attacker may mount an existential forgery attack.
  125. :Return: A tuple with 2 longs.
  126. .. __: http://www.di.ens.fr/~pnguyen/pub_NgSh00.htm
  127. """
  128. return pubkey.pubkey.sign(self, M, K)
  129. def verify(self, M, signature):
  130. """Verify the validity of a DSA signature.
  131. :Parameter M: The expected message.
  132. :Type M: byte string or long
  133. :Parameter signature: The DSA signature to verify.
  134. :Type signature: A tuple with 2 longs as return by `sign`
  135. :Return: True if the signature is correct, False otherwise.
  136. """
  137. return pubkey.pubkey.verify(self, M, signature)
  138. def _encrypt(self, c, K):
  139. raise TypeError("DSA cannot encrypt")
  140. def _decrypt(self, c):
  141. raise TypeError("DSA cannot decrypt")
  142. def _blind(self, m, r):
  143. raise TypeError("DSA cannot blind")
  144. def _unblind(self, m, r):
  145. raise TypeError("DSA cannot unblind")
  146. def _sign(self, m, k):
  147. return self.key._sign(m, k)
  148. def _verify(self, m, sig):
  149. (r, s) = sig
  150. return self.key._verify(m, r, s)
  151. def has_private(self):
  152. return self.key.has_private()
  153. def size(self):
  154. return self.key.size()
  155. def can_blind(self):
  156. return False
  157. def can_encrypt(self):
  158. return False
  159. def can_sign(self):
  160. return True
  161. def publickey(self):
  162. return self.implementation.construct((self.key.y, self.key.g, self.key.p, self.key.q))
  163. def __getstate__(self):
  164. d = {}
  165. for k in self.keydata:
  166. try:
  167. d[k] = getattr(self.key, k)
  168. except AttributeError:
  169. pass
  170. return d
  171. def __setstate__(self, d):
  172. if not hasattr(self, 'implementation'):
  173. self.implementation = DSAImplementation()
  174. t = []
  175. for k in self.keydata:
  176. if not d.has_key(k):
  177. break
  178. t.append(d[k])
  179. self.key = self.implementation._math.dsa_construct(*tuple(t))
  180. def __repr__(self):
  181. attrs = []
  182. for k in self.keydata:
  183. if k == 'p':
  184. attrs.append("p(%d)" % (self.size()+1,))
  185. elif hasattr(self.key, k):
  186. attrs.append(k)
  187. if self.has_private():
  188. attrs.append("private")
  189. # PY3K: This is meant to be text, do not change to bytes (data)
  190. return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs))
  191. class DSAImplementation(object):
  192. """
  193. A DSA key factory.
  194. This class is only internally used to implement the methods of the
  195. `Crypto.PublicKey.DSA` module.
  196. """
  197. def __init__(self, **kwargs):
  198. """Create a new DSA key factory.
  199. :Keywords:
  200. use_fast_math : bool
  201. Specify which mathematic library to use:
  202. - *None* (default). Use fastest math available.
  203. - *True* . Use fast math.
  204. - *False* . Use slow math.
  205. default_randfunc : callable
  206. Specify how to collect random data:
  207. - *None* (default). Use Random.new().read().
  208. - not *None* . Use the specified function directly.
  209. :Raise RuntimeError:
  210. When **use_fast_math** =True but fast math is not available.
  211. """
  212. use_fast_math = kwargs.get('use_fast_math', None)
  213. if use_fast_math is None: # Automatic
  214. if _fastmath is not None:
  215. self._math = _fastmath
  216. else:
  217. self._math = _slowmath
  218. elif use_fast_math: # Explicitly select fast math
  219. if _fastmath is not None:
  220. self._math = _fastmath
  221. else:
  222. raise RuntimeError("fast math module not available")
  223. else: # Explicitly select slow math
  224. self._math = _slowmath
  225. self.error = self._math.error
  226. # 'default_randfunc' parameter:
  227. # None (default) - use Random.new().read
  228. # not None - use the specified function
  229. self._default_randfunc = kwargs.get('default_randfunc', None)
  230. self._current_randfunc = None
  231. def _get_randfunc(self, randfunc):
  232. if randfunc is not None:
  233. return randfunc
  234. elif self._current_randfunc is None:
  235. self._current_randfunc = Random.new().read
  236. return self._current_randfunc
  237. def generate(self, bits, randfunc=None, progress_func=None):
  238. """Randomly generate a fresh, new DSA key.
  239. :Parameters:
  240. bits : int
  241. Key length, or size (in bits) of the DSA modulus
  242. *p*.
  243. It must be a multiple of 64, in the closed
  244. interval [512,1024].
  245. randfunc : callable
  246. Random number generation function; it should accept
  247. a single integer N and return a string of random data
  248. N bytes long.
  249. If not specified, a new one will be instantiated
  250. from ``Crypto.Random``.
  251. progress_func : callable
  252. Optional function that will be called with a short string
  253. containing the key parameter currently being generated;
  254. it's useful for interactive applications where a user is
  255. waiting for a key to be generated.
  256. :attention: You should always use a cryptographically secure random number generator,
  257. such as the one defined in the ``Crypto.Random`` module; **don't** just use the
  258. current time and the ``random`` module.
  259. :Return: A DSA key object (`_DSAobj`).
  260. :Raise ValueError:
  261. When **bits** is too little, too big, or not a multiple of 64.
  262. """
  263. # Check against FIPS 186-2, which says that the size of the prime p
  264. # must be a multiple of 64 bits between 512 and 1024
  265. for i in (0, 1, 2, 3, 4, 5, 6, 7, 8):
  266. if bits == 512 + 64*i:
  267. return self._generate(bits, randfunc, progress_func)
  268. # The March 2006 draft of FIPS 186-3 also allows 2048 and 3072-bit
  269. # primes, but only with longer q values. Since the current DSA
  270. # implementation only supports a 160-bit q, we don't support larger
  271. # values.
  272. raise ValueError("Number of bits in p must be a multiple of 64 between 512 and 1024, not %d bits" % (bits,))
  273. def _generate(self, bits, randfunc=None, progress_func=None):
  274. rf = self._get_randfunc(randfunc)
  275. obj = _DSA.generate_py(bits, rf, progress_func) # TODO: Don't use legacy _DSA module
  276. key = self._math.dsa_construct(obj.y, obj.g, obj.p, obj.q, obj.x)
  277. return _DSAobj(self, key)
  278. def construct(self, tup):
  279. """Construct a DSA key from a tuple of valid DSA components.
  280. The modulus *p* must be a prime.
  281. The following equations must apply:
  282. - p-1 = 0 mod q
  283. - g^x = y mod p
  284. - 0 < x < q
  285. - 1 < g < p
  286. :Parameters:
  287. tup : tuple
  288. A tuple of long integers, with 4 or 5 items
  289. in the following order:
  290. 1. Public key (*y*).
  291. 2. Sub-group generator (*g*).
  292. 3. Modulus, finite field order (*p*).
  293. 4. Sub-group order (*q*).
  294. 5. Private key (*x*). Optional.
  295. :Return: A DSA key object (`_DSAobj`).
  296. """
  297. key = self._math.dsa_construct(*tup)
  298. return _DSAobj(self, key)
  299. _impl = DSAImplementation()
  300. generate = _impl.generate
  301. construct = _impl.construct
  302. error = _impl.error
  303. # vim:set ts=4 sw=4 sts=4 expandtab: