pkcs1_15.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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
  31. import Crypto.Util.number
  32. from Crypto.Util.number import ceil_div, bytes_to_long, long_to_bytes
  33. from Crypto.Util.asn1 import DerSequence, DerNull, DerOctetString, DerObjectId
  34. class PKCS115_SigScheme:
  35. """A signature object for ``RSASSA-PKCS1-v1_5``.
  36. Do not instantiate directly.
  37. Use :func:`Crypto.Signature.pkcs1_15.new`.
  38. """
  39. def __init__(self, rsa_key):
  40. """Initialize this PKCS#1 v1.5 signature scheme object.
  41. :Parameters:
  42. rsa_key : an RSA key object
  43. Creation of signatures is only possible if this is a *private*
  44. RSA key. Verification of signatures is always possible.
  45. """
  46. self._key = rsa_key
  47. def can_sign(self):
  48. """Return ``True`` if this object can be used to sign messages."""
  49. return self._key.has_private()
  50. def sign(self, msg_hash):
  51. """Create the PKCS#1 v1.5 signature of a message.
  52. This function is also called ``RSASSA-PKCS1-V1_5-SIGN`` and
  53. it is specified in
  54. `section 8.2.1 of RFC8017 <https://tools.ietf.org/html/rfc8017#page-36>`_.
  55. :parameter msg_hash:
  56. This is an object from the :mod:`Crypto.Hash` package.
  57. It has been used to digest the message to sign.
  58. :type msg_hash: hash object
  59. :return: the signature encoded as a *byte string*.
  60. :raise ValueError: if the RSA key is not long enough for the given hash algorithm.
  61. :raise TypeError: if the RSA key has no private half.
  62. """
  63. # See 8.2.1 in RFC3447
  64. modBits = Crypto.Util.number.size(self._key.n)
  65. k = ceil_div(modBits,8) # Convert from bits to bytes
  66. # Step 1
  67. em = _EMSA_PKCS1_V1_5_ENCODE(msg_hash, k)
  68. # Step 2a (OS2IP)
  69. em_int = bytes_to_long(em)
  70. # Step 2b (RSASP1)
  71. m_int = self._key._decrypt(em_int)
  72. # Step 2c (I2OSP)
  73. signature = long_to_bytes(m_int, k)
  74. return signature
  75. def verify(self, msg_hash, signature):
  76. """Check if the PKCS#1 v1.5 signature over a message is valid.
  77. This function is also called ``RSASSA-PKCS1-V1_5-VERIFY`` and
  78. it is specified in
  79. `section 8.2.2 of RFC8037 <https://tools.ietf.org/html/rfc8017#page-37>`_.
  80. :parameter msg_hash:
  81. The hash that was carried out over the message. This is an object
  82. belonging to the :mod:`Crypto.Hash` module.
  83. :type parameter: hash object
  84. :parameter signature:
  85. The signature that needs to be validated.
  86. :type signature: byte string
  87. :raise ValueError: if the signature is not valid.
  88. """
  89. # See 8.2.2 in RFC3447
  90. modBits = Crypto.Util.number.size(self._key.n)
  91. k = ceil_div(modBits, 8) # Convert from bits to bytes
  92. # Step 1
  93. if len(signature) != k:
  94. raise ValueError("Invalid signature")
  95. # Step 2a (O2SIP)
  96. signature_int = bytes_to_long(signature)
  97. # Step 2b (RSAVP1)
  98. em_int = self._key._encrypt(signature_int)
  99. # Step 2c (I2OSP)
  100. em1 = long_to_bytes(em_int, k)
  101. # Step 3
  102. try:
  103. possible_em1 = [ _EMSA_PKCS1_V1_5_ENCODE(msg_hash, k, True) ]
  104. # MD2/4/5 hashes always require NULL params in AlgorithmIdentifier.
  105. # For all others, it is optional.
  106. try:
  107. algorithm_is_md = msg_hash.oid.startswith('1.2.840.113549.2.')
  108. except AttributeError:
  109. algorithm_is_md = False
  110. if not algorithm_is_md: # MD2/MD4/MD5
  111. possible_em1.append(_EMSA_PKCS1_V1_5_ENCODE(msg_hash, k, False))
  112. except ValueError:
  113. raise ValueError("Invalid signature")
  114. # Step 4
  115. # By comparing the full encodings (as opposed to checking each
  116. # of its components one at a time) we avoid attacks to the padding
  117. # scheme like Bleichenbacher's (see http://www.mail-archive.com/cryptography@metzdowd.com/msg06537).
  118. #
  119. if em1 not in possible_em1:
  120. raise ValueError("Invalid signature")
  121. pass
  122. def _EMSA_PKCS1_V1_5_ENCODE(msg_hash, emLen, with_hash_parameters=True):
  123. """
  124. Implement the ``EMSA-PKCS1-V1_5-ENCODE`` function, as defined
  125. in PKCS#1 v2.1 (RFC3447, 9.2).
  126. ``_EMSA-PKCS1-V1_5-ENCODE`` actually accepts the message ``M`` as input,
  127. and hash it internally. Here, we expect that the message has already
  128. been hashed instead.
  129. :Parameters:
  130. msg_hash : hash object
  131. The hash object that holds the digest of the message being signed.
  132. emLen : int
  133. The length the final encoding must have, in bytes.
  134. with_hash_parameters : bool
  135. If True (default), include NULL parameters for the hash
  136. algorithm in the ``digestAlgorithm`` SEQUENCE.
  137. :attention: the early standard (RFC2313) stated that ``DigestInfo``
  138. had to be BER-encoded. This means that old signatures
  139. might have length tags in indefinite form, which
  140. is not supported in DER. Such encoding cannot be
  141. reproduced by this function.
  142. :Return: An ``emLen`` byte long string that encodes the hash.
  143. """
  144. # First, build the ASN.1 DER object DigestInfo:
  145. #
  146. # DigestInfo ::= SEQUENCE {
  147. # digestAlgorithm AlgorithmIdentifier,
  148. # digest OCTET STRING
  149. # }
  150. #
  151. # where digestAlgorithm identifies the hash function and shall be an
  152. # algorithm ID with an OID in the set PKCS1-v1-5DigestAlgorithms.
  153. #
  154. # PKCS1-v1-5DigestAlgorithms ALGORITHM-IDENTIFIER ::= {
  155. # { OID id-md2 PARAMETERS NULL }|
  156. # { OID id-md5 PARAMETERS NULL }|
  157. # { OID id-sha1 PARAMETERS NULL }|
  158. # { OID id-sha256 PARAMETERS NULL }|
  159. # { OID id-sha384 PARAMETERS NULL }|
  160. # { OID id-sha512 PARAMETERS NULL }
  161. # }
  162. #
  163. # Appendix B.1 also says that for SHA-1/-2 algorithms, the parameters
  164. # should be omitted. They may be present, but when they are, they shall
  165. # have NULL value.
  166. digestAlgo = DerSequence([ DerObjectId(msg_hash.oid).encode() ])
  167. if with_hash_parameters:
  168. digestAlgo.append(DerNull().encode())
  169. digest = DerOctetString(msg_hash.digest())
  170. digestInfo = DerSequence([
  171. digestAlgo.encode(),
  172. digest.encode()
  173. ]).encode()
  174. # We need at least 11 bytes for the remaining data: 3 fixed bytes and
  175. # at least 8 bytes of padding).
  176. if emLen<len(digestInfo)+11:
  177. raise TypeError("Selected hash algorith has a too long digest (%d bytes)." % len(digest))
  178. PS = bchr(0xFF) * (emLen - len(digestInfo) - 3)
  179. return b("\x00\x01") + PS + bchr(0x00) + digestInfo
  180. def new(rsa_key):
  181. """Create a signature object for creating
  182. or verifying PKCS#1 v1.5 signatures.
  183. :parameter rsa_key:
  184. The RSA key to use for signing or verifying the message.
  185. This is a :class:`Crypto.PublicKey.RSA` object.
  186. Signing is only possible when ``rsa_key`` is a **private** RSA key.
  187. :type rsa_key: RSA object
  188. :return: a :class:`PKCS115_SigScheme` signature object
  189. """
  190. return PKCS115_SigScheme(rsa_key)