pss.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 b, bchr, bord
  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)
  96. m_int = self._key._decrypt(em_int)
  97. # Step 2c (I2OSP)
  98. signature = long_to_bytes(m_int, k)
  99. return signature
  100. def verify(self, msg_hash, signature):
  101. """Check if the PKCS#1 PSS signature over a message is valid.
  102. This function is also called ``RSASSA-PSS-VERIFY`` and
  103. it is specified in
  104. `section 8.1.2 of RFC8037 <https://tools.ietf.org/html/rfc8017#section-8.1.2>`_.
  105. :parameter msg_hash:
  106. The hash that was carried out over the message. This is an object
  107. belonging to the :mod:`Crypto.Hash` module.
  108. :type parameter: hash object
  109. :parameter signature:
  110. The signature that needs to be validated.
  111. :type signature: byte string
  112. :raise ValueError: if the signature is not valid.
  113. """
  114. # Set defaults for salt length and mask generation function
  115. if self._saltLen is None:
  116. sLen = msg_hash.digest_size
  117. else:
  118. sLen = self._saltLen
  119. if self._mgfunc:
  120. mgf = self._mgfunc
  121. else:
  122. mgf = lambda x, y: MGF1(x, y, msg_hash)
  123. modBits = Crypto.Util.number.size(self._key.n)
  124. # See 8.1.2 in RFC3447
  125. k = ceil_div(modBits, 8) # Convert from bits to bytes
  126. # Step 1
  127. if len(signature) != k:
  128. raise ValueError("Incorrect signature")
  129. # Step 2a (O2SIP)
  130. signature_int = bytes_to_long(signature)
  131. # Step 2b (RSAVP1)
  132. em_int = self._key._encrypt(signature_int)
  133. # Step 2c (I2OSP)
  134. emLen = ceil_div(modBits - 1, 8)
  135. em = long_to_bytes(em_int, emLen)
  136. # Step 3/4
  137. _EMSA_PSS_VERIFY(msg_hash, em, modBits-1, mgf, sLen)
  138. def MGF1(mgfSeed, maskLen, hash_gen):
  139. """Mask Generation Function, described in `B.2.1 of RFC8017
  140. <https://tools.ietf.org/html/rfc8017>`_.
  141. :param mfgSeed:
  142. seed from which the mask is generated
  143. :type mfgSeed: byte string
  144. :param maskLen:
  145. intended length in bytes of the mask
  146. :type maskLen: integer
  147. :param hash_gen:
  148. A module or a hash object from :mod:`Crypto.Hash`
  149. :type hash_object:
  150. :return: the mask, as a *byte string*
  151. """
  152. T = b("")
  153. for counter in xrange(ceil_div(maskLen, hash_gen.digest_size)):
  154. c = long_to_bytes(counter, 4)
  155. hobj = hash_gen.new()
  156. hobj.update(mgfSeed + c)
  157. T = T + hobj.digest()
  158. assert(len(T) >= maskLen)
  159. return T[:maskLen]
  160. def _EMSA_PSS_ENCODE(mhash, emBits, randFunc, mgf, sLen):
  161. """
  162. Implement the ``EMSA-PSS-ENCODE`` function, as defined
  163. in PKCS#1 v2.1 (RFC3447, 9.1.1).
  164. The original ``EMSA-PSS-ENCODE`` actually accepts the message ``M``
  165. as input, and hash it internally. Here, we expect that the message
  166. has already been hashed instead.
  167. :Parameters:
  168. mhash : hash object
  169. The hash object that holds the digest of the message being signed.
  170. emBits : int
  171. Maximum length of the final encoding, in bits.
  172. randFunc : callable
  173. An RNG function that accepts as only parameter an int, and returns
  174. a string of random bytes, to be used as salt.
  175. mgf : callable
  176. A mask generation function that accepts two parameters: a string to
  177. use as seed, and the lenth of the mask to generate, in bytes.
  178. sLen : int
  179. Length of the salt, in bytes.
  180. :Return: An ``emLen`` byte long string that encodes the hash
  181. (with ``emLen = \ceil(emBits/8)``).
  182. :Raise ValueError:
  183. When digest or salt length are too big.
  184. """
  185. emLen = ceil_div(emBits, 8)
  186. # Bitmask of digits that fill up
  187. lmask = 0
  188. for i in xrange(8*emLen-emBits):
  189. lmask = lmask >> 1 | 0x80
  190. # Step 1 and 2 have been already done
  191. # Step 3
  192. if emLen < mhash.digest_size+sLen+2:
  193. raise ValueError("Digest or salt length are too long"
  194. " for given key size.")
  195. # Step 4
  196. salt = randFunc(sLen)
  197. # Step 5
  198. m_prime = bchr(0)*8 + mhash.digest() + salt
  199. # Step 6
  200. h = mhash.new()
  201. h.update(m_prime)
  202. # Step 7
  203. ps = bchr(0)*(emLen-sLen-mhash.digest_size-2)
  204. # Step 8
  205. db = ps + bchr(1) + salt
  206. # Step 9
  207. dbMask = mgf(h.digest(), emLen-mhash.digest_size-1)
  208. # Step 10
  209. maskedDB = strxor(db, dbMask)
  210. # Step 11
  211. maskedDB = bchr(bord(maskedDB[0]) & ~lmask) + maskedDB[1:]
  212. # Step 12
  213. em = maskedDB + h.digest() + bchr(0xBC)
  214. return em
  215. def _EMSA_PSS_VERIFY(mhash, em, emBits, mgf, sLen):
  216. """
  217. Implement the ``EMSA-PSS-VERIFY`` function, as defined
  218. in PKCS#1 v2.1 (RFC3447, 9.1.2).
  219. ``EMSA-PSS-VERIFY`` actually accepts the message ``M`` as input,
  220. and hash it internally. Here, we expect that the message has already
  221. been hashed instead.
  222. :Parameters:
  223. mhash : hash object
  224. The hash object that holds the digest of the message to be verified.
  225. em : string
  226. The signature to verify, therefore proving that the sender really
  227. signed the message that was received.
  228. emBits : int
  229. Length of the final encoding (em), in bits.
  230. mgf : callable
  231. A mask generation function that accepts two parameters: a string to
  232. use as seed, and the lenth of the mask to generate, in bytes.
  233. sLen : int
  234. Length of the salt, in bytes.
  235. :Raise ValueError:
  236. When the encoding is inconsistent, or the digest or salt lengths
  237. are too big.
  238. """
  239. emLen = ceil_div(emBits, 8)
  240. # Bitmask of digits that fill up
  241. lmask = 0
  242. for i in xrange(8*emLen-emBits):
  243. lmask = lmask >> 1 | 0x80
  244. # Step 1 and 2 have been already done
  245. # Step 3
  246. if emLen < mhash.digest_size+sLen+2:
  247. return False
  248. # Step 4
  249. if ord(em[-1:]) != 0xBC:
  250. raise ValueError("Incorrect signature")
  251. # Step 5
  252. maskedDB = em[:emLen-mhash.digest_size-1]
  253. h = em[emLen-mhash.digest_size-1:-1]
  254. # Step 6
  255. if lmask & bord(em[0]):
  256. raise ValueError("Incorrect signature")
  257. # Step 7
  258. dbMask = mgf(h, emLen-mhash.digest_size-1)
  259. # Step 8
  260. db = strxor(maskedDB, dbMask)
  261. # Step 9
  262. db = bchr(bord(db[0]) & ~lmask) + db[1:]
  263. # Step 10
  264. if not db.startswith(bchr(0)*(emLen-mhash.digest_size-sLen-2) + bchr(1)):
  265. raise ValueError("Incorrect signature")
  266. # Step 11
  267. if sLen > 0:
  268. salt = db[-sLen:]
  269. else:
  270. salt = b("")
  271. # Step 12
  272. m_prime = bchr(0)*8 + mhash.digest() + salt
  273. # Step 13
  274. hobj = mhash.new()
  275. hobj.update(m_prime)
  276. hp = hobj.digest()
  277. # Step 14
  278. if h != hp:
  279. raise ValueError("Incorrect signature")
  280. def new(rsa_key, **kwargs):
  281. """Create a signature object for creating
  282. 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 mask generation function that accepts two parameters: a string to
  291. use as seed, and the length of the mask in bytes to generate.
  292. If not specified, the standard :func:`MGF1` is used.
  293. * *salt_bytes* (``integer``) --
  294. Length of the salt, in bytes.
  295. If not specified, it matches the output size of the hash function.
  296. If zero, the signature scheme becomes deterministic.
  297. * *rand_func* (``callable``) --
  298. A function that returns random *byte string*, given the desired
  299. length.
  300. The default is :func:`Crypto.Random.get_random_bytes`.
  301. :return: a :class:`PSS_SigScheme` signature object
  302. """
  303. mask_func = kwargs.pop("mask_func", None)
  304. salt_len = kwargs.pop("salt_bytes", None)
  305. rand_func = kwargs.pop("rand_func", None)
  306. if rand_func is None:
  307. rand_func = Random.get_random_bytes
  308. if kwargs:
  309. raise ValueError("Unknown keywords: " + str(kwargs.keys()))
  310. return PSS_SigScheme(rsa_key, mask_func, salt_len, rand_func)