int HMAC_SHA256_init()

in src/hmac.c [31:64]


int HMAC_SHA256_init(hmac_sha256 *ctx, const char* key, int keylen)
{
    if (ctx == NULL || key == NULL)
        return ERR_NULLPOINTER_HMAC;
    if (keylen < SHA256_HASH_SIZE)
        return ERR_KEYSIZE_HMAC;

    int i;
    char ipad = 0x36;

    // Initialize the underlying SHA256 instance
    HASH256_init(&(ctx->sha256_ctx));
    // Fill k0 with 0s for future padding
    for(i = 0; i < SHA256_BLOCK_SIZE; i++)
        ctx->k0[i] = 0x00;

    // If the key size is larger than the block size, then hash it
    if (keylen > SHA256_BLOCK_SIZE) {
        for(i = 0; i < keylen; i++)
            HASH256_process(&(ctx->sha256_ctx), key[i]);
        HASH256_hash(&(ctx->sha256_ctx), ctx->k0);
    }
    // Otherwise the key is simply padded with 0s into k0
    else {
        for(i = 0; i < keylen; i++)
            ctx->k0[i] = key[i];
    }

    // Update the HMAC instance to process k0 ^ ipad
    for(i = 0; i < SHA256_BLOCK_SIZE; i++)
        HASH256_process(&(ctx->sha256_ctx), (ctx->k0)[i] ^ ipad);

    return SUCCESS;
}