Debian Codegraph @

lib/Crypto/Cipher/PKCS1_OAEP.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # Cipher/PKCS1_OAEP.py : PKCS#1 OAEP
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 from Crypto.Signature.pss import MGF1
24 import Crypto.Hash.SHA1
25
26 from Crypto.Util.py3compat import _copy_bytes
27 import Crypto.Util.number
28 from Crypto.Util.number import ceil_div, bytes_to_long, long_to_bytes
29 from Crypto.Util.strxor import strxor
30 from Crypto import Random
31 from ._pkcs1_oaep_decode import oaep_decode
32
33
34 class PKCS1OAEP_Cipher:
35 """Cipher object for PKCS#1 v1.5 OAEP.
36 Do not create directly: use :func:`new` instead."""
37
38 def __init__(self, key, hashAlgo, mgfunc, label, randfunc):
39 """Initialize this PKCS#1 OAEP cipher object.
40
41 :Parameters:
42 key : an RSA key object
43 If a private half is given, both encryption and decryption are possible.
44 If a public half is given, only encryption is possible.
45 hashAlgo : hash object
46 The hash function to use. This can be a module under `Crypto.Hash`
47 or an existing hash object created from any of such modules. If not specified,
48 `Crypto.Hash.SHA1` is used.
49 mgfunc : callable
50 A mask generation function that accepts two parameters: a string to
51 use as seed, and the lenth of the mask to generate, in bytes.
52 If not specified, the standard MGF1 consistent with ``hashAlgo`` is used (a safe choice).
53 label : bytes/bytearray/memoryview
54 A label to apply to this particular encryption. If not specified,
55 an empty string is used. Specifying a label does not improve
56 security.
57 randfunc : callable
58 A function that returns random bytes.
59
60 :attention: Modify the mask generation function only if you know what you are doing.
61 Sender and receiver must use the same one.
62 """
63 self._key = key
64
65 if hashAlgo:
66 self._hashObj = hashAlgo
67 else:
68 self._hashObj = Crypto.Hash.SHA1
69
70 if mgfunc:
71 self._mgf = mgfunc
72 else:
73 self._mgf = lambda x, y: MGF1(x, y, self._hashObj)
74
75 self._label = _copy_bytes(None, None, label)
76 self._randfunc = randfunc
77
78 def can_encrypt(self):
79 """Legacy function to check if you can call :meth:`encrypt`.
80
81 .. deprecated:: 3.0"""
82 return self._key.can_encrypt()
83
84 def can_decrypt(self):
85 """Legacy function to check if you can call :meth:`decrypt`.
86
87 .. deprecated:: 3.0"""
88 return self._key.can_decrypt()
89
90 def encrypt(self, message):
91 """Encrypt a message with PKCS#1 OAEP.
92
93 :param message:
94 The message to encrypt, also known as plaintext. It can be of
95 variable length, but not longer than the RSA modulus (in bytes)
96 minus 2, minus twice the hash output size.
97 For instance, if you use RSA 2048 and SHA-256, the longest message
98 you can encrypt is 190 byte long.
99 :type message: bytes/bytearray/memoryview
100
101 :returns: The ciphertext, as large as the RSA modulus.
102 :rtype: bytes
103
104 :raises ValueError:
105 if the message is too long.
106 """
107
108 # See 7.1.1 in RFC3447
109 modBits = Crypto.Util.number.size(self._key.n)
110 k = ceil_div(modBits, 8) # Convert from bits to bytes
111 hLen = self._hashObj.digest_size
112 mLen = len(message)
113
114 # Step 1b
115 ps_len = k - mLen - 2 * hLen - 2
116 if ps_len < 0:
117 raise ValueError("Plaintext is too long.")
118 # Step 2a
119 lHash = self._hashObj.new(self._label).digest()
120 # Step 2b
121 ps = b'\x00' * ps_len
122 # Step 2c
123 db = lHash + ps + b'\x01' + _copy_bytes(None, None, message)
124 # Step 2d
125 ros = self._randfunc(hLen)
126 # Step 2e
127 dbMask = self._mgf(ros, k-hLen-1)
128 # Step 2f
129 maskedDB = strxor(db, dbMask)
130 # Step 2g
131 seedMask = self._mgf(maskedDB, hLen)
132 # Step 2h
133 maskedSeed = strxor(ros, seedMask)
134 # Step 2i
135 em = b'\x00' + maskedSeed + maskedDB
136 # Step 3a (OS2IP)
137 em_int = bytes_to_long(em)
138 # Step 3b (RSAEP)
139 m_int = self._key._encrypt(em_int)
140 # Step 3c (I2OSP)
141 c = long_to_bytes(m_int, k)
142 return c
143
144 def decrypt(self, ciphertext):
145 """Decrypt a message with PKCS#1 OAEP.
146
147 :param ciphertext: The encrypted message.
148 :type ciphertext: bytes/bytearray/memoryview
149
150 :returns: The original message (plaintext).
151 :rtype: bytes
152
153 :raises ValueError:
154 if the ciphertext has the wrong length, or if decryption
155 fails the integrity check (in which case, the decryption
156 key is probably wrong).
157 :raises TypeError:
158 if the RSA key has no private half (i.e. you are trying
159 to decrypt using a public key).
160 """
161
162 # See 7.1.2 in RFC3447
163 modBits = Crypto.Util.number.size(self._key.n)
164 k = ceil_div(modBits, 8) # Convert from bits to bytes
165 hLen = self._hashObj.digest_size
166
167 # Step 1b and 1c
168 if len(ciphertext) != k or k < hLen+2:
169 raise ValueError("Ciphertext with incorrect length.")
170 # Step 2a (O2SIP)
171 ct_int = bytes_to_long(ciphertext)
172 # Step 2b (RSADP) and step 2c (I2OSP)
173 em = self._key._decrypt_to_bytes(ct_int)
174 # Step 3a
175 lHash = self._hashObj.new(self._label).digest()
176 # y must be 0, but we MUST NOT check it here in order not to
177 # allow attacks like Manger's (http://dl.acm.org/citation.cfm?id=704143)
178 maskedSeed = em[1:hLen+1]
179 maskedDB = em[hLen+1:]
180 # Step 3c
181 seedMask = self._mgf(maskedDB, hLen)
182 # Step 3d
183 seed = strxor(maskedSeed, seedMask)
184 # Step 3e
185 dbMask = self._mgf(seed, k-hLen-1)
186 # Step 3f
187 db = strxor(maskedDB, dbMask)
188 # Step 3b + 3g
189 res = oaep_decode(em, lHash, db)
190 if res <= 0:
191 raise ValueError("Incorrect decryption.")
192 # Step 4
193 return db[res:]
194
195
196 def new(key, hashAlgo=None, mgfunc=None, label=b'', randfunc=None):
197 """Return a cipher object :class:`PKCS1OAEP_Cipher`
198 that can be used to perform PKCS#1 OAEP encryption or decryption.
199
200 :param key:
201 The key object to use to encrypt or decrypt the message.
202 Decryption is only possible with a private RSA key.
203 :type key: RSA key object
204
205 :param hashAlgo:
206 The hash function to use. This can be a module under `Crypto.Hash`
207 or an existing hash object created from any of such modules.
208 If not specified, `Crypto.Hash.SHA1` is used.
209 :type hashAlgo: hash object
210
211 :param mgfunc:
212 A mask generation function that accepts two parameters: a string to
213 use as seed, and the lenth of the mask to generate, in bytes.
214 If not specified, the standard MGF1 consistent with ``hashAlgo`` is used (a safe choice).
215 :type mgfunc: callable
216
217 :param label:
218 A label to apply to this particular encryption. If not specified,
219 an empty string is used. Specifying a label does not improve
220 security.
221 :type label: bytes/bytearray/memoryview
222
223 :param randfunc:
224 A function that returns random bytes.
225 The default is `Random.get_random_bytes`.
226 :type randfunc: callable
227 """
228
229 if randfunc is None:
230 randfunc = Random.get_random_bytes
231 return PKCS1OAEP_Cipher(key, hashAlgo, mgfunc, label, randfunc)