DSS.py 15 KB

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