pkcs1_15.py 8.8 KB

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