PKCS1_PSS.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Signature/PKCS1_PSS.py : PKCS#1 PPS
  4. #
  5. # ===================================================================
  6. # The contents of this file are dedicated to the public domain. To
  7. # the extent that dedication to the public domain is not available,
  8. # everyone is granted a worldwide, perpetual, royalty-free,
  9. # non-exclusive license to exercise all rights associated with the
  10. # contents of this file for any purpose whatsoever.
  11. # No rights are reserved.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  17. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  18. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  19. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. # ===================================================================
  22. """RSA digital signature protocol with appendix according to PKCS#1 PSS.
  23. See RFC3447__ or the `original RSA Labs specification`__.
  24. This scheme is more properly called ``RSASSA-PSS``.
  25. For example, a sender may authenticate a message using SHA-1 and PSS like
  26. this:
  27. >>> from Crypto.Signature import PKCS1_PSS
  28. >>> from Crypto.Hash import SHA
  29. >>> from Crypto.PublicKey import RSA
  30. >>> from Crypto import Random
  31. >>>
  32. >>> message = 'To be signed'
  33. >>> key = RSA.importKey(open('privkey.der').read())
  34. >>> h = SHA.new()
  35. >>> h.update(message)
  36. >>> signer = PKCS1_PSS.new(key)
  37. >>> signature = PKCS1_PSS.sign(key)
  38. At the receiver side, verification can be done like using the public part of
  39. the RSA key:
  40. >>> key = RSA.importKey(open('pubkey.der').read())
  41. >>> h = SHA.new()
  42. >>> h.update(message)
  43. >>> verifier = PKCS1_PSS.new(key)
  44. >>> if verifier.verify(h, signature):
  45. >>> print "The signature is authentic."
  46. >>> else:
  47. >>> print "The signature is not authentic."
  48. :undocumented: __revision__, __package__
  49. .. __: http://www.ietf.org/rfc/rfc3447.txt
  50. .. __: http://www.rsa.com/rsalabs/node.asp?id=2125
  51. """
  52. # Allow nested scopes in Python 2.1
  53. # See http://oreilly.com/pub/a/python/2001/04/19/pythonnews.html
  54. from __future__ import nested_scopes
  55. __revision__ = "$Id$"
  56. __all__ = [ 'new', 'PSS_SigScheme' ]
  57. from Crypto.Util.py3compat import *
  58. if sys.version_info[0] == 2 and sys.version_info[1] == 1:
  59. from Crypto.Util.py21compat import *
  60. import Crypto.Util.number
  61. from Crypto.Util.number import ceil_shift, ceil_div, long_to_bytes
  62. from Crypto.Util.strxor import strxor
  63. class PSS_SigScheme:
  64. """This signature scheme can perform PKCS#1 PSS RSA signature or verification."""
  65. def __init__(self, key, mgfunc, saltLen):
  66. """Initialize this PKCS#1 PSS signature scheme object.
  67. :Parameters:
  68. key : an RSA key object
  69. If a private half is given, both signature and verification are possible.
  70. If a public half is given, only verification is possible.
  71. mgfunc : callable
  72. A mask generation function that accepts two parameters: a string to
  73. use as seed, and the lenth of the mask to generate, in bytes.
  74. saltLen : int
  75. Length of the salt, in bytes.
  76. """
  77. self._key = key
  78. self._saltLen = saltLen
  79. self._mgfunc = mgfunc
  80. def can_sign(self):
  81. """Return True if this cipher object can be used for signing messages."""
  82. return self._key.has_private()
  83. def sign(self, mhash):
  84. """Produce the PKCS#1 PSS signature of a message.
  85. This function is named ``RSASSA-PSS-SIGN``, and is specified in
  86. section 8.1.1 of RFC3447.
  87. :Parameters:
  88. mhash : hash object
  89. The hash that was carried out over the message. This is an object
  90. belonging to the `Crypto.Hash` module.
  91. :Return: The PSS signature encoded as a string.
  92. :Raise ValueError:
  93. If the RSA key length is not sufficiently long to deal with the given
  94. hash algorithm.
  95. :Raise TypeError:
  96. If the RSA key has no private half.
  97. :attention: Modify the salt length and the mask generation function only
  98. if you know what you are doing.
  99. The receiver must use the same parameters too.
  100. """
  101. # TODO: Verify the key is RSA
  102. randfunc = self._key._randfunc
  103. # Set defaults for salt length and mask generation function
  104. if self._saltLen == None:
  105. sLen = mhash.digest_size
  106. else:
  107. sLen = self._saltLen
  108. if self._mgfunc:
  109. mgf = self._mgfunc
  110. else:
  111. mgf = lambda x,y: MGF1(x,y,mhash)
  112. modBits = Crypto.Util.number.size(self._key.n)
  113. # See 8.1.1 in RFC3447
  114. k = ceil_div(modBits,8) # Convert from bits to bytes
  115. # Step 1
  116. em = EMSA_PSS_ENCODE(mhash, modBits-1, randfunc, mgf, sLen)
  117. # Step 2a (OS2IP) and 2b (RSASP1)
  118. m = self._key.decrypt(em)
  119. # Step 2c (I2OSP)
  120. S = bchr(0x00)*(k-len(m)) + m
  121. return S
  122. def verify(self, mhash, S):
  123. """Verify that a certain PKCS#1 PSS signature is authentic.
  124. This function checks if the party holding the private half of the given
  125. RSA key has really signed the message.
  126. This function is called ``RSASSA-PSS-VERIFY``, and is specified in section
  127. 8.1.2 of RFC3447.
  128. :Parameters:
  129. mhash : hash object
  130. The hash that was carried out over the message. This is an object
  131. belonging to the `Crypto.Hash` module.
  132. S : string
  133. The signature that needs to be validated.
  134. :Return: True if verification is correct. False otherwise.
  135. """
  136. # TODO: Verify the key is RSA
  137. # Set defaults for salt length and mask generation function
  138. if self._saltLen == None:
  139. sLen = mhash.digest_size
  140. else:
  141. sLen = self._saltLen
  142. if self._mgfunc:
  143. mgf = self._mgfunc
  144. else:
  145. mgf = lambda x,y: MGF1(x,y,mhash)
  146. modBits = Crypto.Util.number.size(self._key.n)
  147. # See 8.1.2 in RFC3447
  148. k = ceil_div(modBits,8) # Convert from bits to bytes
  149. # Step 1
  150. if len(S) != k:
  151. return False
  152. # Step 2a (O2SIP), 2b (RSAVP1), and partially 2c (I2OSP)
  153. # Note that signature must be smaller than the module
  154. # but RSA.py won't complain about it.
  155. # TODO: Fix RSA object; don't do it here.
  156. em = self._key.encrypt(S, 0)[0]
  157. # Step 2c
  158. emLen = ceil_div(modBits-1,8)
  159. em = bchr(0x00)*(emLen-len(em)) + em
  160. # Step 3
  161. try:
  162. result = EMSA_PSS_VERIFY(mhash, em, modBits-1, mgf, sLen)
  163. except ValueError:
  164. return False
  165. # Step 4
  166. return result
  167. def MGF1(mgfSeed, maskLen, hash):
  168. """Mask Generation Function, described in B.2.1"""
  169. T = b("")
  170. for counter in xrange(ceil_div(maskLen, hash.digest_size)):
  171. c = long_to_bytes(counter, 4)
  172. T = T + hash.new(mgfSeed + c).digest()
  173. assert(len(T)>=maskLen)
  174. return T[:maskLen]
  175. def EMSA_PSS_ENCODE(mhash, emBits, randFunc, mgf, sLen):
  176. """
  177. Implement the ``EMSA-PSS-ENCODE`` function, as defined
  178. in PKCS#1 v2.1 (RFC3447, 9.1.1).
  179. The original ``EMSA-PSS-ENCODE`` actually accepts the message ``M`` as input,
  180. and hash it internally. Here, we expect that the message has already
  181. been hashed instead.
  182. :Parameters:
  183. mhash : hash object
  184. The hash object that holds the digest of the message being signed.
  185. emBits : int
  186. Maximum length of the final encoding, in bits.
  187. randFunc : callable
  188. An RNG function that accepts as only parameter an int, and returns
  189. a string of random bytes, to be used as salt.
  190. mgf : callable
  191. A mask generation function that accepts two parameters: a string to
  192. use as seed, and the lenth of the mask to generate, in bytes.
  193. sLen : int
  194. Length of the salt, in bytes.
  195. :Return: An ``emLen`` byte long string that encodes the hash
  196. (with ``emLen = \ceil(emBits/8)``).
  197. :Raise ValueError:
  198. When digest or salt length are too big.
  199. """
  200. emLen = ceil_div(emBits,8)
  201. # Bitmask of digits that fill up
  202. lmask = 0
  203. for i in xrange(8*emLen-emBits):
  204. lmask = lmask>>1 | 0x80
  205. # Step 1 and 2 have been already done
  206. # Step 3
  207. if emLen < mhash.digest_size+sLen+2:
  208. raise ValueError("Digest or salt length are too long for given key size.")
  209. # Step 4
  210. salt = b("")
  211. if randFunc and sLen>0:
  212. salt = randFunc(sLen)
  213. # Step 5 and 6
  214. h = mhash.new(bchr(0x00)*8 + mhash.digest() + salt)
  215. # Step 7 and 8
  216. db = bchr(0x00)*(emLen-sLen-mhash.digest_size-2) + bchr(0x01) + salt
  217. # Step 9
  218. dbMask = mgf(h.digest(), emLen-mhash.digest_size-1)
  219. # Step 10
  220. maskedDB = strxor(db,dbMask)
  221. # Step 11
  222. maskedDB = bchr(bord(maskedDB[0]) & ~lmask) + maskedDB[1:]
  223. # Step 12
  224. em = maskedDB + h.digest() + bchr(0xBC)
  225. return em
  226. def EMSA_PSS_VERIFY(mhash, em, emBits, mgf, sLen):
  227. """
  228. Implement the ``EMSA-PSS-VERIFY`` function, as defined
  229. in PKCS#1 v2.1 (RFC3447, 9.1.2).
  230. ``EMSA-PSS-VERIFY`` actually accepts the message ``M`` as input,
  231. and hash it internally. Here, we expect that the message has already
  232. been hashed instead.
  233. :Parameters:
  234. mhash : hash object
  235. The hash object that holds the digest of the message to be verified.
  236. em : string
  237. The signature to verify, therefore proving that the sender really signed
  238. the message that was received.
  239. emBits : int
  240. Length of the final encoding (em), in bits.
  241. mgf : callable
  242. A mask generation function that accepts two parameters: a string to
  243. use as seed, and the lenth of the mask to generate, in bytes.
  244. sLen : int
  245. Length of the salt, in bytes.
  246. :Return: 0 if the encoding is consistent, 1 if it is inconsistent.
  247. :Raise ValueError:
  248. When digest or salt length are too big.
  249. """
  250. emLen = ceil_div(emBits,8)
  251. # Bitmask of digits that fill up
  252. lmask = 0
  253. for i in xrange(8*emLen-emBits):
  254. lmask = lmask>>1 | 0x80
  255. # Step 1 and 2 have been already done
  256. # Step 3
  257. if emLen < mhash.digest_size+sLen+2:
  258. return False
  259. # Step 4
  260. if ord(em[-1:])!=0xBC:
  261. return False
  262. # Step 5
  263. maskedDB = em[:emLen-mhash.digest_size-1]
  264. h = em[emLen-mhash.digest_size-1:-1]
  265. # Step 6
  266. if lmask & bord(em[0]):
  267. return False
  268. # Step 7
  269. dbMask = mgf(h, emLen-mhash.digest_size-1)
  270. # Step 8
  271. db = strxor(maskedDB, dbMask)
  272. # Step 9
  273. db = bchr(bord(db[0]) & ~lmask) + db[1:]
  274. # Step 10
  275. if not db.startswith(bchr(0x00)*(emLen-mhash.digest_size-sLen-2) + bchr(0x01)):
  276. return False
  277. # Step 11
  278. salt = b("")
  279. if sLen: salt = db[-sLen:]
  280. # Step 12 and 13
  281. hp = mhash.new(bchr(0x00)*8 + mhash.digest() + salt).digest()
  282. # Step 14
  283. if h!=hp:
  284. return False
  285. return True
  286. def new(key, mgfunc=None, saltLen=None):
  287. """Return a signature scheme object `PSS_SigScheme` that
  288. can be used to perform PKCS#1 PSS signature or verification.
  289. :Parameters:
  290. key : RSA key object
  291. The key to use to sign or verify the message. This is a `Crypto.PublicKey.RSA` object.
  292. Signing is only possible if *key* is a private RSA key.
  293. mgfunc : callable
  294. A mask generation function that accepts two parameters: a string to
  295. use as seed, and the lenth of the mask to generate, in bytes.
  296. If not specified, the standard MGF1 is used.
  297. saltLen : int
  298. Length of the salt, in bytes. If not specified, it matches the output
  299. size of the hash function.
  300. """
  301. return PSS_SigScheme(key, mgfunc, saltLen)