DSS.py 15 KB

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