Skip to content

Commit d6a3b3b

Browse files
committed
evp: skip padding propagation for AEAD and stream cipher modes
On the cipher init path EVP_CIPHER_CTX_set_padding(ctx, 0) was issued whenever the EVP_CIPH_NO_PADDING flag was set, regardless of mode. For AEAD and stream ciphers padding is meaningless and the provider ignores the setting, so this is a redundant OSSL_PARAM round-trip on every init/re-init. Restrict the propagation to the block-oriented ECB and CBC modes, where padding is meaningful; behaviour for paddable ciphers is unchanged. This mainly benefits small-buffer AEAD workloads that reinitialise the context per operation.
1 parent a8b5741 commit d6a3b3b

1 file changed

Lines changed: 18 additions & 6 deletions

File tree

crypto/evp/evp_enc.c

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -154,11 +154,17 @@ static int evp_cipher_init_internal(EVP_CIPHER_CTX *ctx,
154154
}
155155

156156
if ((ctx->flags & EVP_CIPH_NO_PADDING) != 0) {
157+
int mode = EVP_CIPHER_get_mode(cipher);
158+
157159
/*
158-
* If this ctx was already set up for no padding then we need to tell
159-
* the new cipher about it.
160+
* Padding is only meaningful for the block-oriented ECB and CBC modes.
161+
* For AEAD and stream modes the provider ignores the padding setting,
162+
* so skip the costly OSSL_PARAM round-trip on the init hot path (e.g.
163+
* AES-GCM re-init). If this ctx was already set up for no padding we
164+
* still need to tell a newly set up block cipher about it.
160165
*/
161-
if (!EVP_CIPHER_CTX_set_padding(ctx, 0))
166+
if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
167+
&& !EVP_CIPHER_CTX_set_padding(ctx, 0))
162168
return 0;
163169
}
164170

@@ -324,11 +330,17 @@ static int evp_cipher_init_skey_internal(EVP_CIPHER_CTX *ctx,
324330
}
325331

326332
if ((ctx->flags & EVP_CIPH_NO_PADDING) != 0) {
333+
int mode = EVP_CIPHER_get_mode(cipher);
334+
327335
/*
328-
* If this ctx was already set up for no padding then we need to tell
329-
* the new cipher about it.
336+
* Padding is only meaningful for the block-oriented ECB and CBC modes.
337+
* For AEAD and stream modes the provider ignores the padding setting,
338+
* so skip the costly OSSL_PARAM round-trip on the init hot path (e.g.
339+
* AES-GCM re-init). If this ctx was already set up for no padding we
340+
* still need to tell a newly set up block cipher about it.
330341
*/
331-
if (!EVP_CIPHER_CTX_set_padding(ctx, 0))
342+
if ((mode == EVP_CIPH_ECB_MODE || mode == EVP_CIPH_CBC_MODE)
343+
&& !EVP_CIPHER_CTX_set_padding(ctx, 0))
332344
return 0;
333345
}
334346

0 commit comments

Comments
 (0)