From 38a29ee5d07705826682ec54384e350f0cae790b Mon Sep 17 00:00:00 2001 From: Andy Leiserson Date: Fri, 28 Apr 2017 20:01:49 -0700 Subject: [PATCH] return plaintext data faster on unpadded decryption --- library/cipher.c | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/library/cipher.c b/library/cipher.c index ff0327380..7369f4823 100644 --- a/library/cipher.c +++ b/library/cipher.c @@ -325,8 +325,10 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i /* * If there is not enough data for a full block, cache it. */ - if( ( ctx->operation == MBEDTLS_DECRYPT && + if( ( ctx->operation == MBEDTLS_DECRYPT && NULL != ctx->add_padding && ilen <= block_size - ctx->unprocessed_len ) || + ( ctx->operation == MBEDTLS_DECRYPT && NULL == ctx->add_padding && + ilen < block_size - ctx->unprocessed_len ) || ( ctx->operation == MBEDTLS_ENCRYPT && ilen < block_size - ctx->unprocessed_len ) ) { @@ -372,9 +374,17 @@ int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *i return MBEDTLS_ERR_CIPHER_INVALID_CONTEXT; } + /* Encryption: only cache partial blocks + * Decryption w/ padding: always keep at least one whole block + * Decryption w/o padding: only cache partial blocks + */ copy_len = ilen % block_size; - if( copy_len == 0 && ctx->operation == MBEDTLS_DECRYPT ) + if( copy_len == 0 && + ctx->operation == MBEDTLS_DECRYPT && + NULL != ctx->add_padding) + { copy_len = block_size; + } memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ), copy_len );