DSS.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. #
  2. # Signature/DSS.py : DSS.py
  3. #
  4. # ===================================================================
  5. #
  6. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  7. # All rights reserved.
  8. #
  9. # Redistribution and use in source and binary forms, with or without
  10. # modification, are permitted provided that the following conditions
  11. # are met:
  12. #
  13. # 1. Redistributions of source code must retain the above copyright
  14. # notice, this list of conditions and the following disclaimer.
  15. # 2. Redistributions in binary form must reproduce the above copyright
  16. # notice, this list of conditions and the following disclaimer in
  17. # the documentation and/or other materials provided with the
  18. # distribution.
  19. #
  20. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  23. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  24. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  25. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  26. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  27. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  28. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  29. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  30. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  31. # POSSIBILITY OF SUCH DAMAGE.
  32. # ===================================================================
  33. __all__ = ['new', 'DssSigScheme']
  34. from Crypto.Util.py3compat import bchr, b
  35. from Crypto.Util.asn1 import DerSequence
  36. from Crypto.Util.number import long_to_bytes
  37. from Crypto.Math.Numbers import Integer
  38. from Crypto.Hash import HMAC
  39. from Crypto.PublicKey.ECC import _curve, EccKey
  40. class DssSigScheme(object):
  41. """A (EC)DSA signature object.
  42. Do not instantiate directly.
  43. Use :func:`Crypto.Signature.DSS.new`.
  44. """
  45. def __init__(self, key, encoding, order):
  46. """Create a new Digital Signature Standard (DSS) object.
  47. Do not instantiate this object directly,
  48. use `Crypto.Signature.DSS.new` instead.
  49. """
  50. self._key = key
  51. self._encoding = encoding
  52. self._order = order
  53. self._order_bits = self._order.size_in_bits()
  54. self._order_bytes = (self._order_bits - 1) // 8 + 1
  55. def can_sign(self):
  56. """Return ``True`` if this signature object can be used
  57. for signing messages."""
  58. return self._key.has_private()
  59. def _compute_nonce(self, msg_hash):
  60. raise NotImplementedError("To be provided by subclasses")
  61. def _valid_hash(self, msg_hash):
  62. raise NotImplementedError("To be provided by subclasses")
  63. def sign(self, msg_hash):
  64. """Produce the DSA/ECDSA signature of a message.
  65. :parameter msg_hash:
  66. The hash that was carried out over the message.
  67. The object belongs to the :mod:`Crypto.Hash` package.
  68. Under mode *'fips-186-3'*, the hash must be a FIPS
  69. approved secure hash (SHA-1 or a member of the SHA-2 family),
  70. of cryptographic strength appropriate for the DSA key.
  71. For instance, a 3072/256 DSA key can only be used
  72. in combination with SHA-512.
  73. :type msg_hash: hash object
  74. :return: The signature as a *byte string*
  75. :raise ValueError: if the hash algorithm is incompatible to the (EC)DSA key
  76. :raise TypeError: if the (EC)DSA key has no private half
  77. """
  78. if not self._valid_hash(msg_hash):
  79. raise ValueError("Hash is not sufficiently strong")
  80. # Generate the nonce k (critical!)
  81. nonce = self._compute_nonce(msg_hash)
  82. # Perform signature using the raw API
  83. z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes])
  84. sig_pair = self._key._sign(z, nonce)
  85. # Encode the signature into a single byte string
  86. if self._encoding == 'binary':
  87. output = b("").join([long_to_bytes(x, self._order_bytes)
  88. for x in sig_pair])
  89. else:
  90. # Dss-sig ::= SEQUENCE {
  91. # r OCTET STRING,
  92. # s OCTET STRING
  93. # }
  94. output = DerSequence(sig_pair).encode()
  95. return output
  96. def verify(self, msg_hash, signature):
  97. """Check if a certain (EC)DSA signature is authentic.
  98. :parameter msg_hash:
  99. The hash that was carried out over the message.
  100. This is an object belonging to the :mod:`Crypto.Hash` module.
  101. Under mode *'fips-186-3'*, the hash must be a FIPS
  102. approved secure hash (SHA-1 or a member of the SHA-2 family),
  103. of cryptographic strength appropriate for the DSA key.
  104. For instance, a 3072/256 DSA key can only be used in
  105. combination with SHA-512.
  106. :type msg_hash: hash object
  107. :parameter signature:
  108. The signature that needs to be validated
  109. :type signature: byte string
  110. :raise ValueError: if the signature is not authentic
  111. """
  112. if not self._valid_hash(msg_hash):
  113. raise ValueError("Hash does not belong to SHS")
  114. if self._encoding == 'binary':
  115. if len(signature) != (2 * self._order_bytes):
  116. raise ValueError("The signature is not authentic (length)")
  117. r_prime, s_prime = [Integer.from_bytes(x)
  118. for x in (signature[:self._order_bytes],
  119. signature[self._order_bytes:])]
  120. else:
  121. try:
  122. der_seq = DerSequence().decode(signature)
  123. except (ValueError, IndexError):
  124. raise ValueError("The signature is not authentic (DER)")
  125. if len(der_seq) != 2 or not der_seq.hasOnlyInts():
  126. raise ValueError("The signature is not authentic (DER content)")
  127. r_prime, s_prime = der_seq[0], der_seq[1]
  128. if not (0 < r_prime < self._order) or not (0 < s_prime < self._order):
  129. raise ValueError("The signature is not authentic (d)")
  130. z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes])
  131. result = self._key._verify(z, (r_prime, s_prime))
  132. if not result:
  133. raise ValueError("The signature is not authentic")
  134. # Make PyCrypto code to fail
  135. return False
  136. class DeterministicDsaSigScheme(DssSigScheme):
  137. # Also applicable to ECDSA
  138. def __init__(self, key, encoding, order, private_key):
  139. super(DeterministicDsaSigScheme, self).__init__(key, encoding, order)
  140. self._private_key = private_key
  141. def _bits2int(self, bstr):
  142. """See 2.3.2 in RFC6979"""
  143. result = Integer.from_bytes(bstr)
  144. q_len = self._order.size_in_bits()
  145. b_len = len(bstr) * 8
  146. if b_len > q_len:
  147. result >>= (b_len - q_len)
  148. return result
  149. def _int2octets(self, int_mod_q):
  150. """See 2.3.3 in RFC6979"""
  151. assert 0 < int_mod_q < self._order
  152. return long_to_bytes(int_mod_q, self._order_bytes)
  153. def _bits2octets(self, bstr):
  154. """See 2.3.4 in RFC6979"""
  155. z1 = self._bits2int(bstr)
  156. if z1 < self._order:
  157. z2 = z1
  158. else:
  159. z2 = z1 - self._order
  160. return self._int2octets(z2)
  161. def _compute_nonce(self, mhash):
  162. """Generate k in a deterministic way"""
  163. # See section 3.2 in RFC6979.txt
  164. # Step a
  165. h1 = mhash.digest()
  166. # Step b
  167. mask_v = bchr(1) * mhash.digest_size
  168. # Step c
  169. nonce_k = bchr(0) * mhash.digest_size
  170. for int_oct in 0, 1:
  171. # Step d/f
  172. nonce_k = HMAC.new(nonce_k,
  173. mask_v + bchr(int_oct) +
  174. self._int2octets(self._private_key) +
  175. self._bits2octets(h1), mhash).digest()
  176. # Step e/g
  177. mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
  178. nonce = -1
  179. while not (0 < nonce < self._order):
  180. # Step h.C (second part)
  181. if nonce != -1:
  182. nonce_k = HMAC.new(nonce_k, mask_v + bchr(0),
  183. mhash).digest()
  184. mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
  185. # Step h.A
  186. mask_t = b("")
  187. # Step h.B
  188. while len(mask_t) < self._order_bytes:
  189. mask_v = HMAC.new(nonce_k, mask_v, mhash).digest()
  190. mask_t += mask_v
  191. # Step h.C (first part)
  192. nonce = self._bits2int(mask_t)
  193. return nonce
  194. def _valid_hash(self, msg_hash):
  195. return True
  196. class FipsDsaSigScheme(DssSigScheme):
  197. #: List of L (bit length of p) and N (bit length of q) combinations
  198. #: that are allowed by FIPS 186-3. The security level is provided in
  199. #: Table 2 of FIPS 800-57 (rev3).
  200. _fips_186_3_L_N = (
  201. (1024, 160), # 80 bits (SHA-1 or stronger)
  202. (2048, 224), # 112 bits (SHA-224 or stronger)
  203. (2048, 256), # 128 bits (SHA-256 or stronger)
  204. (3072, 256) # 256 bits (SHA-512)
  205. )
  206. def __init__(self, key, encoding, order, randfunc):
  207. super(FipsDsaSigScheme, self).__init__(key, encoding, order)
  208. self._randfunc = randfunc
  209. L = Integer(key.p).size_in_bits()
  210. if (L, self._order_bits) not in self._fips_186_3_L_N:
  211. error = ("L/N (%d, %d) is not compliant to FIPS 186-3"
  212. % (L, self._order_bits))
  213. raise ValueError(error)
  214. def _compute_nonce(self, msg_hash):
  215. # hash is not used
  216. return Integer.random_range(min_inclusive=1,
  217. max_exclusive=self._order,
  218. randfunc=self._randfunc)
  219. def _valid_hash(self, msg_hash):
  220. """Verify that SHA-1, SHA-2 or SHA-3 are used"""
  221. return (msg_hash.oid == "1.3.14.3.2.26" or
  222. msg_hash.oid.startswith("2.16.840.1.101.3.4.2."))
  223. class FipsEcDsaSigScheme(DssSigScheme):
  224. def __init__(self, key, encoding, order, randfunc):
  225. super(FipsEcDsaSigScheme, self).__init__(key, encoding, order)
  226. self._randfunc = randfunc
  227. def _compute_nonce(self, msg_hash):
  228. return Integer.random_range(min_inclusive=1,
  229. max_exclusive=_curve.order,
  230. randfunc=self._randfunc)
  231. def _valid_hash(self, msg_hash):
  232. """Verify that SHA-[23] (256|384|512) bits are used to
  233. match the 128-bit security of P-256"""
  234. approved = ("2.16.840.1.101.3.4.2.1",
  235. "2.16.840.1.101.3.4.2.2",
  236. "2.16.840.1.101.3.4.2.3",
  237. "2.16.840.1.101.3.4.2.8",
  238. "2.16.840.1.101.3.4.2.9",
  239. "2.16.840.1.101.3.4.2.10")
  240. return msg_hash.oid in approved
  241. def new(key, mode, encoding='binary', randfunc=None):
  242. """Create a signature object :class:`DSS_SigScheme` that
  243. can perform (EC)DSA signature or verification.
  244. .. note::
  245. Refer to `NIST SP 800 Part 1 Rev 4`_ (or newer release) for an
  246. overview of the recommended key lengths.
  247. :parameter key:
  248. The key to use for computing the signature (*private* keys only)
  249. or verifying one: it must be either
  250. :class:`Crypto.PublicKey.DSA` or :class:`Crypto.PublicKey.ECC`.
  251. For DSA keys, let ``L`` and ``N`` be the bit lengths of the modulus ``p``
  252. and of ``q``: the pair ``(L,N)`` must appear in the following list,
  253. in compliance to section 4.2 of `FIPS 186-4`_:
  254. - (1024, 160) *legacy only; do not create new signatures with this*
  255. - (2048, 224) *deprecated; do not create new signatures with this*
  256. - (2048, 256)
  257. - (3072, 256)
  258. For ECC, only keys over P-256 are accepted.
  259. :type key:
  260. a key object
  261. :parameter mode:
  262. The parameter can take these values:
  263. - *'fips-186-3'*. The signature generation is randomized and carried out
  264. according to `FIPS 186-3`_: the nonce ``k`` is taken from the RNG.
  265. - *'deterministic-rfc6979'*. The signature generation is not
  266. randomized. See RFC6979_.
  267. :type mode:
  268. string
  269. :parameter encoding:
  270. How the signature is encoded. This value determines the output of
  271. :meth:`sign` and the input to :meth:`verify`.
  272. The following values are accepted:
  273. - *'binary'* (default), the signature is the raw concatenation
  274. of ``r`` and ``s``.
  275. For DSA, the size in bytes of the signature is ``N/4``
  276. (e.g. 64 bytes for ``N=256``).
  277. For ECDSA (over P-256), the signature is always 64 bytes long.
  278. - *'der'*, the signature is an ASN.1 SEQUENCE with two
  279. INTEGERs (``r`` and ``s``) encoded with DER.
  280. The size of the signature is variable.
  281. :type encoding: string
  282. :parameter randfunc:
  283. A function that returns random *byte strings*, of a given length.
  284. If omitted, the internal RNG is used.
  285. Only applicable for the *'fips-186-3'* mode.
  286. :type randfunc: callable
  287. .. _FIPS 186-3: http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
  288. .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
  289. .. _NIST SP 800 Part 1 Rev 4: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r4.pdf
  290. .. _RFC6979: http://tools.ietf.org/html/rfc6979
  291. """
  292. # The goal of the 'mode' parameter is to avoid to
  293. # have the current version of the standard as default.
  294. #
  295. # Over time, such version will be superseded by (for instance)
  296. # FIPS 186-4 and it will be odd to have -3 as default.
  297. if encoding not in ('binary', 'der'):
  298. raise ValueError("Unknown encoding '%s'" % encoding)
  299. if isinstance(key, EccKey):
  300. order = _curve.order
  301. private_key_attr = 'd'
  302. else:
  303. order = Integer(key.q)
  304. private_key_attr = 'x'
  305. if key.has_private():
  306. private_key = getattr(key, private_key_attr)
  307. else:
  308. private_key = None
  309. if mode == 'deterministic-rfc6979':
  310. return DeterministicDsaSigScheme(key, encoding, order, private_key)
  311. elif mode == 'fips-186-3':
  312. if isinstance(key, EccKey):
  313. return FipsEcDsaSigScheme(key, encoding, order, randfunc)
  314. else:
  315. return FipsDsaSigScheme(key, encoding, order, randfunc)
  316. else:
  317. raise ValueError("Unknown DSS mode '%s'" % mode)