PKCS1_v1_5.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Signature/PKCS1-v1_5.py : PKCS#1 v1.5
  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. """
  23. RSA digital signature protocol according to PKCS#1 v1.5
  24. See RFC3447__ or the `original RSA Labs specification`__.
  25. This scheme is more properly called ``RSASSA-PKCS1-v1_5``.
  26. For example, a sender may authenticate a message using SHA-1 like
  27. this:
  28. >>> from Crypto.Signature import PKCS1_v1_5
  29. >>> from Crypto.Hash import SHA
  30. >>> from Crypto.PublicKey import RSA
  31. >>>
  32. >>> message = 'To be signed'
  33. >>> key = RSA.importKey(open('privkey.der').read())
  34. >>> h = SHA.new(message)
  35. >>> signer = PKCS1_v1_5.new(key)
  36. >>> signature = signer.sign(h)
  37. At the receiver side, verification can be done using the public part of
  38. the RSA key:
  39. >>> key = RSA.importKey(open('pubkey.der').read())
  40. >>> h = SHA.new(message)
  41. >>> verifier = PKCS1_v1_5.new(key)
  42. >>> if verifier.verify(h, signature):
  43. >>> print "The signature is authentic."
  44. >>> else:
  45. >>> print "The signature is not authentic."
  46. :undocumented: __revision__, __package__
  47. .. __: http://www.ietf.org/rfc/rfc3447.txt
  48. .. __: http://www.rsa.com/rsalabs/node.asp?id=2125
  49. """
  50. __revision__ = "$Id$"
  51. __all__ = [ 'new', 'PKCS115_SigScheme' ]
  52. import Crypto.Util.number
  53. from Crypto.Util.number import ceil_div
  54. from Crypto.Util.asn1 import DerSequence, DerNull, DerOctetString
  55. from Crypto.Util.py3compat import *
  56. class PKCS115_SigScheme:
  57. """This signature scheme can perform PKCS#1 v1.5 RSA signature or verification."""
  58. def __init__(self, key):
  59. """Initialize this PKCS#1 v1.5 signature scheme object.
  60. :Parameters:
  61. key : an RSA key object
  62. If a private half is given, both signature and verification are possible.
  63. If a public half is given, only verification is possible.
  64. """
  65. self._key = key
  66. def can_sign(self):
  67. """Return True if this cipher object can be used for signing messages."""
  68. return self._key.has_private()
  69. def sign(self, mhash):
  70. """Produce the PKCS#1 v1.5 signature of a message.
  71. This function is named ``RSASSA-PKCS1-V1_5-SIGN``, and is specified in
  72. section 8.2.1 of RFC3447.
  73. :Parameters:
  74. mhash : hash object
  75. The hash that was carried out over the message. This is an object
  76. belonging to the `Crypto.Hash` module.
  77. :Return: The signature encoded as a string.
  78. :Raise ValueError:
  79. If the RSA key length is not sufficiently long to deal with the given
  80. hash algorithm.
  81. :Raise TypeError:
  82. If the RSA key has no private half.
  83. """
  84. # TODO: Verify the key is RSA
  85. # See 8.2.1 in RFC3447
  86. modBits = Crypto.Util.number.size(self._key.n)
  87. k = ceil_div(modBits,8) # Convert from bits to bytes
  88. # Step 1
  89. em = EMSA_PKCS1_V1_5_ENCODE(mhash, k)
  90. # Step 2a (OS2IP) and 2b (RSASP1)
  91. m = self._key.decrypt(em)
  92. # Step 2c (I2OSP)
  93. S = bchr(0x00)*(k-len(m)) + m
  94. return S
  95. def verify(self, mhash, S):
  96. """Verify that a certain PKCS#1 v1.5 signature is authentic.
  97. This function checks if the party holding the private half of the key
  98. really signed the message.
  99. This function is named ``RSASSA-PKCS1-V1_5-VERIFY``, and is specified in
  100. section 8.2.2 of RFC3447.
  101. :Parameters:
  102. mhash : hash object
  103. The hash that was carried out over the message. This is an object
  104. belonging to the `Crypto.Hash` module.
  105. S : string
  106. The signature that needs to be validated.
  107. :Return: True if verification is correct. False otherwise.
  108. """
  109. # TODO: Verify the key is RSA
  110. # See 8.2.2 in RFC3447
  111. modBits = Crypto.Util.number.size(self._key.n)
  112. k = ceil_div(modBits,8) # Convert from bits to bytes
  113. # Step 1
  114. if len(S) != k:
  115. return 0
  116. # Step 2a (O2SIP) and 2b (RSAVP1)
  117. # Note that signature must be smaller than the module
  118. # but RSA.py won't complain about it.
  119. # TODO: Fix RSA object; don't do it here.
  120. m = self._key.encrypt(S, 0)[0]
  121. # Step 2c (I2OSP)
  122. em1 = bchr(0x00)*(k-len(m)) + m
  123. # Step 3
  124. try:
  125. em2 = EMSA_PKCS1_V1_5_ENCODE(mhash, k)
  126. except ValueError:
  127. return 0
  128. # Step 4
  129. # By comparing the full encodings (as opposed to checking each
  130. # of its components one at a time) we avoid attacks to the padding
  131. # scheme like Bleichenbacher's (see http://www.mail-archive.com/cryptography@metzdowd.com/msg06537).
  132. #
  133. return em1==em2
  134. def EMSA_PKCS1_V1_5_ENCODE(hash, emLen):
  135. """
  136. Implement the ``EMSA-PKCS1-V1_5-ENCODE`` function, as defined
  137. in PKCS#1 v2.1 (RFC3447, 9.2).
  138. ``EMSA-PKCS1-V1_5-ENCODE`` actually accepts the message ``M`` as input,
  139. and hash it internally. Here, we expect that the message has already
  140. been hashed instead.
  141. :Parameters:
  142. hash : hash object
  143. The hash object that holds the digest of the message being signed.
  144. emLen : int
  145. The length the final encoding must have, in bytes.
  146. :attention: the early standard (RFC2313) stated that ``DigestInfo``
  147. had to be BER-encoded. This means that old signatures
  148. might have length tags in indefinite form, which
  149. is not supported in DER. Such encoding cannot be
  150. reproduced by this function.
  151. :attention: the same standard defined ``DigestAlgorithm`` to be
  152. of ``AlgorithmIdentifier`` type, where the PARAMETERS
  153. item is optional. Encodings for ``MD2/4/5`` without
  154. ``PARAMETERS`` cannot be reproduced by this function.
  155. :Return: An ``emLen`` byte long string that encodes the hash.
  156. """
  157. # First, build the ASN.1 DER object DigestInfo:
  158. #
  159. # DigestInfo ::= SEQUENCE {
  160. # digestAlgorithm AlgorithmIdentifier,
  161. # digest OCTET STRING
  162. # }
  163. #
  164. # where digestAlgorithm identifies the hash function and shall be an
  165. # algorithm ID with an OID in the set PKCS1-v1-5DigestAlgorithms.
  166. #
  167. # PKCS1-v1-5DigestAlgorithms ALGORITHM-IDENTIFIER ::= {
  168. # { OID id-md2 PARAMETERS NULL }|
  169. # { OID id-md5 PARAMETERS NULL }|
  170. # { OID id-sha1 PARAMETERS NULL }|
  171. # { OID id-sha256 PARAMETERS NULL }|
  172. # { OID id-sha384 PARAMETERS NULL }|
  173. # { OID id-sha512 PARAMETERS NULL }
  174. # }
  175. #
  176. digestAlgo = DerSequence([hash.oid, DerNull().encode()])
  177. digest = DerOctetString(hash.digest())
  178. digestInfo = DerSequence([
  179. digestAlgo.encode(),
  180. digest.encode()
  181. ]).encode()
  182. # We need at least 11 bytes for the remaining data: 3 fixed bytes and
  183. # at least 8 bytes of padding).
  184. if emLen<len(digestInfo)+11:
  185. raise ValueError("Selected hash algorith has a too long digest (%d bytes)." % len(digest))
  186. PS = bchr(0xFF) * (emLen - len(digestInfo) - 3)
  187. return b("\x00\x01") + PS + bchr(0x00) + digestInfo
  188. def new(key):
  189. """Return a signature scheme object `PKCS115_SigScheme` that
  190. can be used to perform PKCS#1 v1.5 signature or verification.
  191. :Parameters:
  192. key : RSA key object
  193. The key to use to sign or verify the message. This is a `Crypto.PublicKey.RSA` object.
  194. Signing is only possible if *key* is a private RSA key.
  195. """
  196. return PKCS115_SigScheme(key)