Welcome to little lamb

Code » limb » master » tree

[master] / src / liblimb / hmac.h / hmac.c

/* This file is part of limb                           https://lila.oss/limb
 * Copyright (C) 2023 Olivier Brunel                          jjk@jjacky.com */
/* SPDX-License-Identifier: GPL-2.0-only */
#include <string.h>
#include <limb/bytestr.h>
#include <limb/hmac.h>
#include <limb/memxor.h>

void
hmac(char *out, hasher *h, const void *key, size_t klen, const void *msg, size_t mlen)
{
    unsigned char secret[h->blen];
    size_t l;

    if (klen > h->blen) {
        hinit(h);
        hupdate(key, klen, h);
        hfinal(secret, h);
        l = h->hlen;
    } else {
        memcpy(secret, key, klen);
        l = klen;
    }
    memset(secret + l, 0, h->blen - l);

    unsigned char buf[h->blen];
    memset(buf, 0x36, h->blen);
    memxor(buf, secret, h->blen);
    unsigned char tmp[h->blen];
    memset(tmp, 0x5c, h->blen);
    memxor(secret, tmp, h->blen);

    hinit(h);
    hupdate(buf, h->blen, h);
    hupdate(msg, mlen, h);
    hfinal(buf, h);

    hinit(h);
    hupdate(secret, h->blen, h);
    hupdate(buf, h->hlen, h);
    hfinal(out, h);

    byte_zero(secret, h->blen);
}