Skip to content

Commit d1739c6

Browse files
committed
Fix issue #198: AESNI breaks with messages shorter than 16 bytes
1 parent df80035 commit d1739c6

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

lib/Crypto/SelfTest/Cipher/test_AES.py

+23
Original file line numberDiff line numberDiff line change
@@ -1265,16 +1265,39 @@ def runTest(self):
12651265
self.assertEqual(SHA256.new(ct).hexdigest(), expected)
12661266

12671267

1268+
class TestIncompleteBlocks(unittest.TestCase):
1269+
1270+
def __init__(self, use_aesni):
1271+
unittest.TestCase.__init__(self)
1272+
self.use_aesni = use_aesni
1273+
1274+
def runTest(self):
1275+
# Encrypt data with length not multiple of 16 bytes
1276+
1277+
cipher = AES.new(b'4'*16, AES.MODE_ECB, use_aesni=self.use_aesni)
1278+
1279+
for msg_len in range(1, 16):
1280+
self.assertRaises(ValueError, cipher.encrypt, b'1' * msg_len)
1281+
self.assertRaises(ValueError, cipher.encrypt, b'1' * (msg_len+16))
1282+
self.assertRaises(ValueError, cipher.decrypt, b'1' * msg_len)
1283+
self.assertRaises(ValueError, cipher.decrypt, b'1' * (msg_len+16))
1284+
1285+
self.assertEqual(cipher.encrypt(b''), b'')
1286+
self.assertEqual(cipher.decrypt(b''), b'')
1287+
1288+
12681289
def get_tests(config={}):
12691290
from Crypto.Util import _cpu_features
12701291
from common import make_block_tests
12711292

12721293
tests = make_block_tests(AES, "AES", test_data, {'use_aesni': False})
12731294
tests += [ TestMultipleBlocks(False) ]
1295+
tests += [ TestIncompleteBlocks(False) ]
12741296
if _cpu_features.have_aes_ni():
12751297
# Run tests with AES-NI instructions if they are available.
12761298
tests += make_block_tests(AES, "AESNI", test_data, {'use_aesni': True})
12771299
tests += [ TestMultipleBlocks(True) ]
1300+
tests += [ TestIncompleteBlocks(True) ]
12781301
else:
12791302
print "Skipping AESNI tests"
12801303
return tests

src/AESNI.c

+2-2
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ static int AESNI_encrypt(const BlockBase *bb, const uint8_t *in, uint8_t *out, s
222222
}
223223

224224
/** There are 7 blocks or fewer left **/
225-
for (;data_len>0; data_len-=16, in+=16, out+=16) {
225+
for (;data_len>=BLOCK_SIZE; data_len-=BLOCK_SIZE, in+=BLOCK_SIZE, out+=BLOCK_SIZE) {
226226
__m128i pt, data;
227227
unsigned i;
228228

@@ -331,7 +331,7 @@ static int AESNI_decrypt(const BlockBase *bb, const uint8_t *in, uint8_t *out, s
331331
}
332332

333333
/** There are 7 blocks or fewer left **/
334-
for (;data_len>0; data_len-=16, in+=16, out+=16) {
334+
for (;data_len>=BLOCK_SIZE; data_len-=BLOCK_SIZE, in+=BLOCK_SIZE, out+=BLOCK_SIZE) {
335335
__m128i ct, data;
336336
unsigned i;
337337

0 commit comments

Comments
 (0)