Debian Codegraph @

lib/Crypto/Signature/pkcs1_15.py

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