From 66ba999b66c152410af08b90ef77bc47b235f098 Mon Sep 17 00:00:00 2001 From: wbond Date: Tue, 23 Jul 2019 11:56:34 -0400 Subject: [PATCH] Fix winlegacy implementation of AES CBC with no padding --- oscrypto/_win/symmetric.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/oscrypto/_win/symmetric.py b/oscrypto/_win/symmetric.py index e392f1c..e93cd13 100644 --- a/oscrypto/_win/symmetric.py +++ b/oscrypto/_win/symmetric.py @@ -866,9 +866,7 @@ def _advapi32_encrypt(cipher, key, data, iv, padding): # Remove padding when not required. CryptoAPI doesn't support this, so # we just manually remove it. - if cipher == 'aes' and not padding: - if output[-16:] != (b'\x10' * 16): - raise ValueError('Invalid padding generated by OS crypto library') + if cipher == 'aes' and not padding and len(output) == len(data) + 16: output = output[:-16] return output @@ -1059,17 +1057,17 @@ def _advapi32_decrypt(cipher, key, data, iv, padding): try: context_handle, key_handle = _advapi32_create_handles(cipher, key, iv) - # Add removed padding when not required. CryptoAPI doesn't support no - # padding, so we just add it back in - if cipher == 'aes' and not padding: - data += (b'\x10' * 16) + if cipher == 'aes' and not padding and len(data) % 16 != 0: + raise ValueError('Invalid data - ciphertext length must be a multiple of 16') buffer = buffer_from_bytes(data) out_len = new(advapi32, 'DWORD *', len(data)) res = advapi32.CryptDecrypt( key_handle, null(), - True, + # To skip padding, we have to tell the API that this is not + # the final block + False if cipher == 'aes' and not padding else True, 0, buffer, out_len