Debian Codegraph @

lib/Crypto/Cipher/PKCS1_v1_5.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # Cipher/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 __all__ = ['new', 'PKCS115_Cipher']
24
25 from Crypto import Random
26 from Crypto.Util.number import bytes_to_long, long_to_bytes
27 from Crypto.Util.py3compat import bord, is_bytes, _copy_bytes
28 from ._pkcs1_oaep_decode import pkcs1_decode
29
30
31 class PKCS115_Cipher:
32 """This cipher can perform PKCS#1 v1.5 RSA encryption or decryption.
33 Do not instantiate directly. Use :func:`Crypto.Cipher.PKCS1_v1_5.new` instead."""
34
35 def __init__(self, key, randfunc):
36 """Initialize this PKCS#1 v1.5 cipher object.
37
38 :Parameters:
39 key : an RSA key object
40 If a private half is given, both encryption and decryption are possible.
41 If a public half is given, only encryption is possible.
42 randfunc : callable
43 Function that returns random bytes.
44 """
45
46 self._key = key
47 self._randfunc = randfunc
48
49 def can_encrypt(self):
50 """Return True if this cipher object can be used for encryption."""
51 return self._key.can_encrypt()
52
53 def can_decrypt(self):
54 """Return True if this cipher object can be used for decryption."""
55 return self._key.can_decrypt()
56
57 def encrypt(self, message):
58 """Produce the PKCS#1 v1.5 encryption of a message.
59
60 This function is named ``RSAES-PKCS1-V1_5-ENCRYPT``, and it is specified in
61 `section 7.2.1 of RFC8017
62 <https://tools.ietf.org/html/rfc8017#page-28>`_.
63
64 :param message:
65 The message to encrypt, also known as plaintext. It can be of
66 variable length, but not longer than the RSA modulus (in bytes) minus 11.
67 :type message: bytes/bytearray/memoryview
68
69 :Returns: A byte string, the ciphertext in which the message is encrypted.
70 It is as long as the RSA modulus (in bytes).
71
72 :Raises ValueError:
73 If the RSA key length is not sufficiently long to deal with the given
74 message.
75 """
76
77 # See 7.2.1 in RFC8017
78 k = self._key.size_in_bytes()
79 mLen = len(message)
80
81 # Step 1
82 if mLen > k - 11:
83 raise ValueError("Plaintext is too long.")
84 # Step 2a
85 ps = []
86 while len(ps) != k - mLen - 3:
87 new_byte = self._randfunc(1)
88 if bord(new_byte[0]) == 0x00:
89 continue
90 ps.append(new_byte)
91 ps = b"".join(ps)
92 # Step 2b
93 em = b'\x00\x02' + ps + b'\x00' + _copy_bytes(None, None, message)
94 # Step 3a (OS2IP)
95 em_int = bytes_to_long(em)
96 # Step 3b (RSAEP)
97 m_int = self._key._encrypt(em_int)
98 # Step 3c (I2OSP)
99 c = long_to_bytes(m_int, k)
100 return c
101
102 def decrypt(self, ciphertext, sentinel, expected_pt_len=0):
103 r"""Decrypt a PKCS#1 v1.5 ciphertext.
104
105 This is the function ``RSAES-PKCS1-V1_5-DECRYPT`` specified in
106 `section 7.2.2 of RFC8017
107 <https://tools.ietf.org/html/rfc8017#page-29>`_.
108
109 Args:
110 ciphertext (bytes/bytearray/memoryview):
111 The ciphertext that contains the message to recover.
112 sentinel (any type):
113 The object to return whenever an error is detected.
114 expected_pt_len (integer):
115 The length the plaintext is known to have, or 0 if unknown.
116
117 Returns (byte string):
118 It is either the original message or the ``sentinel`` (in case of an error).
119
120 .. warning::
121 PKCS#1 v1.5 decryption is intrinsically vulnerable to timing
122 attacks (see `Bleichenbacher's`__ attack).
123 **Use PKCS#1 OAEP instead**.
124
125 This implementation attempts to mitigate the risk
126 with some constant-time constructs.
127 However, they are not sufficient by themselves: the type of protocol you
128 implement and the way you handle errors make a big difference.
129
130 Specifically, you should make it very hard for the (malicious)
131 party that submitted the ciphertext to quickly understand if decryption
132 succeeded or not.
133
134 To this end, it is recommended that your protocol only encrypts
135 plaintexts of fixed length (``expected_pt_len``),
136 that ``sentinel`` is a random byte string of the same length,
137 and that processing continues for as long
138 as possible even if ``sentinel`` is returned (i.e. in case of
139 incorrect decryption).
140
141 .. __: https://dx.doi.org/10.1007/BFb0055716
142 """
143
144 # See 7.2.2 in RFC8017
145 k = self._key.size_in_bytes()
146
147 # Step 1
148 if len(ciphertext) != k:
149 raise ValueError("Ciphertext with incorrect length (not %d bytes)" % k)
150
151 # Step 2a (O2SIP)
152 ct_int = bytes_to_long(ciphertext)
153
154 # Step 2b (RSADP) and Step 2c (I2OSP)
155 em = self._key._decrypt_to_bytes(ct_int)
156
157 # Step 3 (not constant time when the sentinel is not a byte string)
158 output = bytes(bytearray(k))
159 if not is_bytes(sentinel) or len(sentinel) > k:
160 size = pkcs1_decode(em, b'', expected_pt_len, output)
161 if size < 0:
162 return sentinel
163 else:
164 return output[size:]
165
166 # Step 3 (somewhat constant time)
167 size = pkcs1_decode(em, sentinel, expected_pt_len, output)
168 return output[size:]
169
170
171 def new(key, randfunc=None):
172 """Create a cipher for performing PKCS#1 v1.5 encryption or decryption.
173
174 :param key:
175 The key to use to encrypt or decrypt the message. This is a `Crypto.PublicKey.RSA` object.
176 Decryption is only possible if *key* is a private RSA key.
177 :type key: RSA key object
178
179 :param randfunc:
180 Function that return random bytes.
181 The default is :func:`Crypto.Random.get_random_bytes`.
182 :type randfunc: callable
183
184 :returns: A cipher object `PKCS115_Cipher`.
185 """
186
187 if randfunc is None:
188 randfunc = Random.get_random_bytes
189 return PKCS115_Cipher(key, randfunc)