[PATCH v2 2/5] lib: implement sm3 256 hash
Ilias Apalodimas
ilias.apalodimas at linaro.org
Tue Nov 11 10:47:08 CET 2025
I think this would be easier to review/ack if you split the cmd
implementation from the actual hashing algo.
[...]
> +void sm3_init(struct sm3_context *sctx)
> +{
> + memset(sctx, 0, sizeof(struct sm3_context));
I usually prefer sizeof(*sctx), but up to you
> +
> + /* Load initial values */
> + sctx->state[0] = SM3_IVA;
> + sctx->state[1] = SM3_IVB;
> + sctx->state[2] = SM3_IVC;
> + sctx->state[3] = SM3_IVD;
> + sctx->state[4] = SM3_IVE;
> + sctx->state[5] = SM3_IVF;
> + sctx->state[6] = SM3_IVG;
> + sctx->state[7] = SM3_IVH;
> + sctx->count = 0;
> +}
> +
> +static inline void sm3_block(struct sm3_context *sctx,
> + u8 const *data, int blocks, u32 W[16])
> +{
> + while (blocks--) {
> + sm3_transform(sctx, data, W);
> + data += SM3_BLOCK_SIZE;
> + }
> +}
> +
> +void sm3_update(struct sm3_context *sctx, const uint8_t *input, size_t ilen)
> +{
> + unsigned int partial = sctx->count % SM3_BLOCK_SIZE;
> + u32 W[16];
> +
> + sctx->count += ilen;
> +
> + if ((partial + ilen) >= SM3_BLOCK_SIZE) {
> + int blocks;
> +
> + if (partial) {
> + int p = SM3_BLOCK_SIZE - partial;
> +
> + memcpy(sctx->buffer + partial, input, p);
> + input += p;
> + ilen -= p;
> +
> + sm3_block(sctx, sctx->buffer, 1, W);
> + }
> +
> + blocks = ilen / SM3_BLOCK_SIZE;
> + ilen %= SM3_BLOCK_SIZE;
> +
> + if (blocks) {
> + sm3_block(sctx, input, blocks, W);
> + input += blocks * SM3_BLOCK_SIZE;
> + }
> +
> + memset(W, 0, sizeof(W));
> +
> + partial = 0;
> + }
> + if (ilen)
> + memcpy(sctx->buffer + partial, input, ilen);
> +}
> +
> +void sm3_final(struct sm3_context *sctx, uint8_t output[SM3_DIGEST_SIZE])
I think it's more readable to just define this as output[]
[...]
> +/**
> + * sm3_hash - Calculate SM3 hash of input data
> + * @input: Input data
> + * @ilen: Input data length in bytes
> + * @output: Output buffer for hash (32 bytes)
> + */
> +void sm3_hash(const uint8_t *input, size_t ilen, uint8_t output[SM3_DIGEST_SIZE])
> +{
> + struct sm3_context sctx;
> +
> + sm3_init(&sctx);
> + sm3_update(&sctx, input, ilen);
> + sm3_final(&sctx, output);
Ah ignore my comment on patch #4
init, update, final is wrapped in this function
[...]
Thanks
/Ilias
More information about the U-Boot
mailing list