Re: [PATCH 2/2] crypto: blake2s - use memcpy_and_pad in __blake2s_init
From: Thorsten Blum
Date: Wed Apr 15 2026 - 08:57:43 EST
On Tue, Apr 14, 2026 at 10:39:15AM -0700, Eric Biggers wrote:
> On Tue, Apr 14, 2026 at 05:49:04PM +0200, Thorsten Blum wrote:
> > Use memcpy_and_pad() instead of memcpy() followed by memset() to
> > simplify __blake2s_init(). Use sizeof(ctx->buf) instead of the macro
> > BLAKE2S_BLOCK_SIZE.
> >
> > Signed-off-by: Thorsten Blum <thorsten.blum@xxxxxxxxx>
> > ---
> > include/crypto/blake2s.h | 5 ++---
> > 1 file changed, 2 insertions(+), 3 deletions(-)
> >
> > diff --git a/include/crypto/blake2s.h b/include/crypto/blake2s.h
> > index 648cb7824358..f0e0ce0b30a5 100644
> > --- a/include/crypto/blake2s.h
> > +++ b/include/crypto/blake2s.h
> > @@ -70,9 +70,8 @@ static inline void __blake2s_init(struct blake2s_ctx *ctx, size_t outlen,
> > ctx->buflen = 0;
> > ctx->outlen = outlen;
> > if (keylen) {
> > - memcpy(ctx->buf, key, keylen);
> > - memset(&ctx->buf[keylen], 0, BLAKE2S_BLOCK_SIZE - keylen);
> > - ctx->buflen = BLAKE2S_BLOCK_SIZE;
> > + memcpy_and_pad(ctx->buf, sizeof(ctx->buf), key, keylen, 0);
> > + ctx->buflen = sizeof(ctx->buf);
>
> I'm wondering if this is actually better. It's another helper function
> to remember. Also 'keylen' can be a compile-time constant here, and
> compilers know what memcpy() and memset() do, so they will optimize the
> code accordingly. The helper function takes away the compiler's ability
> to perform this optimization. If this was already an out-of-line
> function, it would be a bit more convincing.
My motivation was readability/maintainability and avoiding the manual
tail-size arithmetic. memcpy_and_pad() is just a thin wrapper around
memcpy()/memset(), with an additional safety check to prevent integer
wraparound.
Currently, nothing stops __blake2s_init() or blake2s_init_key() from
being called with keylen > BLAKE2S_BLOCK_SIZE. The WARN_ON() in
blake2s_init_key() is only available in DEBUG builds.
That said, happy to drop the patch if the explicit version is preferred
for performance reasons.
Thanks,
Thorsten