pss.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  4. # All rights reserved.
  5. #
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions
  8. # are met:
  9. #
  10. # 1. Redistributions of source code must retain the above copyright
  11. # notice, this list of conditions and the following disclaimer.
  12. # 2. Redistributions in binary form must reproduce the above copyright
  13. # notice, this list of conditions and the following disclaimer in
  14. # the documentation and/or other materials provided with the
  15. # distribution.
  16. #
  17. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  20. # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  21. # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  22. # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  23. # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  25. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  26. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  27. # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28. # POSSIBILITY OF SUCH DAMAGE.
  29. # ===================================================================
  30. from Crypto.Util.py3compat import bchr, bord, iter_range
  31. import Crypto.Util.number
  32. from Crypto.Util.number import (ceil_div,
  33. long_to_bytes,
  34. bytes_to_long
  35. )
  36. from Crypto.Util.strxor import strxor
  37. from Crypto import Random
  38. class PSS_SigScheme:
  39. """A signature object for ``RSASSA-PSS``.
  40. Do not instantiate directly.
  41. Use :func:`Crypto.Signature.pss.new`.
  42. """
  43. def __init__(self, key, mgfunc, saltLen, randfunc):
  44. """Initialize this PKCS#1 PSS signature scheme object.
  45. :Parameters:
  46. key : an RSA key object
  47. If a private half is given, both signature and
  48. verification are possible.
  49. If a public half is given, only verification is possible.
  50. mgfunc : callable
  51. A mask generation function that accepts two parameters:
  52. a string to use as seed, and the lenth of the mask to
  53. generate, in bytes.
  54. saltLen : integer
  55. Length of the salt, in bytes.
  56. randfunc : callable
  57. A function that returns random bytes.
  58. """
  59. self._key = key
  60. self._saltLen = saltLen
  61. self._mgfunc = mgfunc
  62. self._randfunc = randfunc
  63. def can_sign(self):
  64. """Return ``True`` if this object can be used to sign messages."""
  65. return self._key.has_private()
  66. def sign(self, msg_hash):
  67. """Create the PKCS#1 PSS signature of a message.
  68. This function is also called ``RSASSA-PSS-SIGN`` and
  69. it is specified in
  70. `section 8.1.1 of RFC8017 <https://tools.ietf.org/html/rfc8017#section-8.1.1>`_.
  71. :parameter msg_hash:
  72. This is an object from the :mod:`Crypto.Hash` package.
  73. It has been used to digest the message to sign.
  74. :type msg_hash: hash object
  75. :return: the signature encoded as a *byte string*.
  76. :raise ValueError: if the RSA key is not long enough for the given hash algorithm.
  77. :raise TypeError: if the RSA key has no private half.
  78. """
  79. # Set defaults for salt length and mask generation function
  80. if self._saltLen is None:
  81. sLen = msg_hash.digest_size
  82. else:
  83. sLen = self._saltLen
  84. if self._mgfunc is None:
  85. mgf = lambda x, y: MGF1(x, y, msg_hash)
  86. else:
  87. mgf = self._mgfunc
  88. modBits = Crypto.Util.number.size(self._key.n)
  89. # See 8.1.1 in RFC3447
  90. k = ceil_div(modBits, 8) # k is length in bytes of the modulus
  91. # Step 1
  92. em = _EMSA_PSS_ENCODE(msg_hash, modBits-1, self._randfunc, mgf, sLen)
  93. # Step 2a (OS2IP)
  94. em_int = bytes_to_long(em)
  95. # Step 2b (RSASP1) and Step 2c (I2OSP)
  96. signature = self._key._decrypt_to_bytes(em_int)
  97. # Verify no faults occurred
  98. if em_int != pow(bytes_to_long(signature), self._key.e, self._key.n):
  99. raise ValueError("Fault detected in RSA private key operation")
  100. return signature
  101. def verify(self, msg_hash, signature):
  102. """Check if the PKCS#1 PSS signature over a message is valid.
  103. This function is also called ``RSASSA-PSS-VERIFY`` and
  104. it is specified in
  105. `section 8.1.2 of RFC8037 <https://tools.ietf.org/html/rfc8017#section-8.1.2>`_.
  106. :parameter msg_hash:
  107. The hash that was carried out over the message. This is an object
  108. belonging to the :mod:`Crypto.Hash` module.
  109. :type parameter: hash object
  110. :parameter signature:
  111. The signature that needs to be validated.
  112. :type signature: bytes
  113. :raise ValueError: if the signature is not valid.
  114. """
  115. # Set defaults for salt length and mask generation function
  116. if self._saltLen is None:
  117. sLen = msg_hash.digest_size
  118. else:
  119. sLen = self._saltLen
  120. if self._mgfunc:
  121. mgf = self._mgfunc
  122. else:
  123. mgf = lambda x, y: MGF1(x, y, msg_hash)
  124. modBits = Crypto.Util.number.size(self._key.n)
  125. # See 8.1.2 in RFC3447
  126. k = ceil_div(modBits, 8) # Convert from bits to bytes
  127. # Step 1
  128. if len(signature) != k:
  129. raise ValueError("Incorrect signature")
  130. # Step 2a (O2SIP)
  131. signature_int = bytes_to_long(signature)
  132. # Step 2b (RSAVP1)
  133. em_int = self._key._encrypt(signature_int)
  134. # Step 2c (I2OSP)
  135. emLen = ceil_div(modBits - 1, 8)
  136. em = long_to_bytes(em_int, emLen)
  137. # Step 3/4
  138. _EMSA_PSS_VERIFY(msg_hash, em, modBits-1, mgf, sLen)
  139. def MGF1(mgfSeed, maskLen, hash_gen):
  140. """Mask Generation Function, described in `B.2.1 of RFC8017
  141. <https://tools.ietf.org/html/rfc8017>`_.
  142. :param mfgSeed:
  143. seed from which the mask is generated
  144. :type mfgSeed: byte string
  145. :param maskLen:
  146. intended length in bytes of the mask
  147. :type maskLen: integer
  148. :param hash_gen:
  149. A module or a hash object from :mod:`Crypto.Hash`
  150. :type hash_object:
  151. :return: the mask, as a *byte string*
  152. """
  153. T = b""
  154. for counter in iter_range(ceil_div(maskLen, hash_gen.digest_size)):
  155. c = long_to_bytes(counter, 4)
  156. hobj = hash_gen.new()
  157. hobj.update(mgfSeed + c)
  158. T = T + hobj.digest()
  159. assert(len(T) >= maskLen)
  160. return T[:maskLen]
  161. def _EMSA_PSS_ENCODE(mhash, emBits, randFunc, mgf, sLen):
  162. r"""
  163. Implement the ``EMSA-PSS-ENCODE`` function, as defined
  164. in PKCS#1 v2.1 (RFC3447, 9.1.1).
  165. The original ``EMSA-PSS-ENCODE`` actually accepts the message ``M``
  166. as input, and hash it internally. Here, we expect that the message
  167. has already been hashed instead.
  168. :Parameters:
  169. mhash : hash object
  170. The hash object that holds the digest of the message being signed.
  171. emBits : int
  172. Maximum length of the final encoding, in bits.
  173. randFunc : callable
  174. An RNG function that accepts as only parameter an int, and returns
  175. a string of random bytes, to be used as salt.
  176. mgf : callable
  177. A mask generation function that accepts two parameters: a string to
  178. use as seed, and the lenth of the mask to generate, in bytes.
  179. sLen : int
  180. Length of the salt, in bytes.
  181. :Return: An ``emLen`` byte long string that encodes the hash
  182. (with ``emLen = \ceil(emBits/8)``).
  183. :Raise ValueError:
  184. When digest or salt length are too big.
  185. """
  186. emLen = ceil_div(emBits, 8)
  187. # Bitmask of digits that fill up
  188. lmask = 0
  189. for i in iter_range(8*emLen-emBits):
  190. lmask = lmask >> 1 | 0x80
  191. # Step 1 and 2 have been already done
  192. # Step 3
  193. if emLen < mhash.digest_size+sLen+2:
  194. raise ValueError("Digest or salt length are too long"
  195. " for given key size.")
  196. # Step 4
  197. salt = randFunc(sLen)
  198. # Step 5
  199. m_prime = bchr(0)*8 + mhash.digest() + salt
  200. # Step 6
  201. h = mhash.new()
  202. h.update(m_prime)
  203. # Step 7
  204. ps = bchr(0)*(emLen-sLen-mhash.digest_size-2)
  205. # Step 8
  206. db = ps + bchr(1) + salt
  207. # Step 9
  208. dbMask = mgf(h.digest(), emLen-mhash.digest_size-1)
  209. # Step 10
  210. maskedDB = strxor(db, dbMask)
  211. # Step 11
  212. maskedDB = bchr(bord(maskedDB[0]) & ~lmask) + maskedDB[1:]
  213. # Step 12
  214. em = maskedDB + h.digest() + bchr(0xBC)
  215. return em
  216. def _EMSA_PSS_VERIFY(mhash, em, emBits, mgf, sLen):
  217. """
  218. Implement the ``EMSA-PSS-VERIFY`` function, as defined
  219. in PKCS#1 v2.1 (RFC3447, 9.1.2).
  220. ``EMSA-PSS-VERIFY`` actually accepts the message ``M`` as input,
  221. and hash it internally. Here, we expect that the message has already
  222. been hashed instead.
  223. :Parameters:
  224. mhash : hash object
  225. The hash object that holds the digest of the message to be verified.
  226. em : string
  227. The signature to verify, therefore proving that the sender really
  228. signed the message that was received.
  229. emBits : int
  230. Length of the final encoding (em), in bits.
  231. mgf : callable
  232. A mask generation function that accepts two parameters: a string to
  233. use as seed, and the lenth of the mask to generate, in bytes.
  234. sLen : int
  235. Length of the salt, in bytes.
  236. :Raise ValueError:
  237. When the encoding is inconsistent, or the digest or salt lengths
  238. are too big.
  239. """
  240. emLen = ceil_div(emBits, 8)
  241. # Bitmask of digits that fill up
  242. lmask = 0
  243. for i in iter_range(8*emLen-emBits):
  244. lmask = lmask >> 1 | 0x80
  245. # Step 1 and 2 have been already done
  246. # Step 3
  247. if emLen < mhash.digest_size+sLen+2:
  248. raise ValueError("Incorrect signature")
  249. # Step 4
  250. if ord(em[-1:]) != 0xBC:
  251. raise ValueError("Incorrect signature")
  252. # Step 5
  253. maskedDB = em[:emLen-mhash.digest_size-1]
  254. h = em[emLen-mhash.digest_size-1:-1]
  255. # Step 6
  256. if lmask & bord(em[0]):
  257. raise ValueError("Incorrect signature")
  258. # Step 7
  259. dbMask = mgf(h, emLen-mhash.digest_size-1)
  260. # Step 8
  261. db = strxor(maskedDB, dbMask)
  262. # Step 9
  263. db = bchr(bord(db[0]) & ~lmask) + db[1:]
  264. # Step 10
  265. if not db.startswith(bchr(0)*(emLen-mhash.digest_size-sLen-2) + bchr(1)):
  266. raise ValueError("Incorrect signature")
  267. # Step 11
  268. if sLen > 0:
  269. salt = db[-sLen:]
  270. else:
  271. salt = b""
  272. # Step 12
  273. m_prime = bchr(0)*8 + mhash.digest() + salt
  274. # Step 13
  275. hobj = mhash.new()
  276. hobj.update(m_prime)
  277. hp = hobj.digest()
  278. # Step 14
  279. if h != hp:
  280. raise ValueError("Incorrect signature")
  281. def new(rsa_key, **kwargs):
  282. """Create an object for making or verifying PKCS#1 PSS signatures.
  283. :parameter rsa_key:
  284. The RSA key to use for signing or verifying the message.
  285. This is a :class:`Crypto.PublicKey.RSA` object.
  286. Signing is only possible when ``rsa_key`` is a **private** RSA key.
  287. :type rsa_key: RSA object
  288. :Keyword Arguments:
  289. * *mask_func* (``callable``) --
  290. A function that returns the mask (as `bytes`).
  291. It must accept two parameters: a seed (as `bytes`)
  292. and the length of the data to return.
  293. If not specified, it will be the function :func:`MGF1` defined in
  294. `RFC8017 <https://tools.ietf.org/html/rfc8017#page-67>`_ and
  295. combined with the same hash algorithm applied to the
  296. message to sign or verify.
  297. If you want to use a different function, for instance still :func:`MGF1`
  298. but together with another hash, you can do::
  299. from Crypto.Hash import SHA256
  300. from Crypto.Signature.pss import MGF1
  301. mgf = lambda x, y: MGF1(x, y, SHA256)
  302. * *salt_bytes* (``integer``) --
  303. Length of the salt, in bytes.
  304. It is a value between 0 and ``emLen - hLen - 2``, where ``emLen``
  305. is the size of the RSA modulus and ``hLen`` is the size of the digest
  306. applied to the message to sign or verify.
  307. The salt is generated internally, you don't need to provide it.
  308. If not specified, the salt length will be ``hLen``.
  309. If it is zero, the signature scheme becomes deterministic.
  310. Note that in some implementations such as OpenSSL the default
  311. salt length is ``emLen - hLen - 2`` (even though it is not more
  312. secure than ``hLen``).
  313. * *rand_func* (``callable``) --
  314. A function that returns random ``bytes``, of the desired length.
  315. The default is :func:`Crypto.Random.get_random_bytes`.
  316. :return: a :class:`PSS_SigScheme` signature object
  317. """
  318. mask_func = kwargs.pop("mask_func", None)
  319. salt_len = kwargs.pop("salt_bytes", None)
  320. rand_func = kwargs.pop("rand_func", None)
  321. if rand_func is None:
  322. rand_func = Random.get_random_bytes
  323. if kwargs:
  324. raise ValueError("Unknown keywords: " + str(kwargs.keys()))
  325. return PSS_SigScheme(rsa_key, mask_func, salt_len, rand_func)