@@ -183,3 +183,36 @@ def test_apppend_zeroes(self):
183
183
signature = signature + bytes .fromhex ('0000' )
184
184
with self .assertRaises (rsa .VerificationError ):
185
185
pkcs1 .verify (message , signature , self .pub )
186
+
187
+
188
+ class PaddingSizeTest (unittest .TestCase ):
189
+ def test_too_little_padding (self ):
190
+ """Padding less than 8 bytes should be rejected."""
191
+
192
+ # Construct key that will be small enough to need only 7 bytes of padding.
193
+ # This key is 168 bit long, and was generated with rsa.newkeys(nbits=168).
194
+ self .private_key = rsa .PrivateKey .load_pkcs1 (b'''
195
+ -----BEGIN RSA PRIVATE KEY-----
196
+ MHkCAQACFgCIGbbNSkIRLtprxka9NgOf5UxgxCMCAwEAAQIVQqymO0gHubdEVS68
197
+ CdCiWmOJxVfRAgwBQM+e1JJwMKmxSF0CCmya6CFxO8Evdn8CDACMM3AlVC4FhlN8
198
+ 3QIKC9cjoam/swMirwIMAR7Br9tdouoH7jAE
199
+ -----END RSA PRIVATE KEY-----
200
+ ''' )
201
+ self .public_key = rsa .PublicKey (n = self .private_key .n , e = self .private_key .e )
202
+
203
+ cyphertext = self .encrypt_with_short_padding (b'op je hoofd' )
204
+ with self .assertRaises (rsa .DecryptionError ):
205
+ rsa .decrypt (cyphertext , self .private_key )
206
+
207
+ def encrypt_with_short_padding (self , message : bytes ) -> bytes :
208
+ # This is a copy of rsa.pkcs1.encrypt() adjusted to use the wrong padding length.
209
+ keylength = rsa .common .byte_size (self .public_key .n )
210
+
211
+ # The word 'padding' has 7 letters, so is one byte short of a valid padding length.
212
+ padded = b'\x00 \x02 padding\x00 ' + message
213
+
214
+ payload = rsa .transform .bytes2int (padded )
215
+ encrypted_value = rsa .core .encrypt_int (payload , self .public_key .e , self .public_key .n )
216
+ cyphertext = rsa .transform .int2bytes (encrypted_value , keylength )
217
+
218
+ return cyphertext
0 commit comments