/*
   PKCIPE - public key based configuration tool for CIPE

   p_sha1.c - keystream generator

   Copyright 2000 Olaf Titz <olaf@bigred.inka.de>

   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public License
   as published by the Free Software Foundation; either version
   2 of the License, or (at your option) any later version.
*/
/* $Id: p_sha1.c,v 1.2 2000/12/05 19:21:11 olaf Exp $ */

#include <sys/mman.h>
#include <openssl/hmac.h>
#include "pkcipe.h"

/* This is the P_SHA1 function as of RFC 2246, section 5.
   We use it in a simple block mode only, i.e. output 20 bytes at a time. */

#if 0
void P_SHA1_dump(P_SHA1_CTX *ctx)
{
    if (!(debugging&DEB_PSHA1))
        return;
    Log(LOG_DEBUG, "P_SHA1_dump: seed_len=%d secret_len=%d",
        ctx->seed_len, ctx->secret_len);
    Log(LOG_DEBUG, "A: %s", hexstr(ctx->A, 20));
    Log(LOG_DEBUG, "seed: %s", hexstr(psha1_seed(ctx), ctx->seed_len));
    Log(LOG_DEBUG, "secret: %s", hexstr(psha1_secret(ctx), ctx->secret_len));
}
#endif

P_SHA1_CTX *P_SHA1_init(const char *secret, int secret_len,
                        const char *seed, int seed_len)
{
    int l=sizeof(P_SHA1_CTX)+secret_len+seed_len;
    P_SHA1_CTX *ctx=malloc(l);
    if (!ctx)
        return NULL;
    if (mlock(ctx, l)<0)
        Log(LOG_ERR, "P_SHA1_init: mlock: %m"); /* not fatal */
    ctx->seed_len=seed_len;
    ctx->secret_len=secret_len;
    memcpy(psha1_seed(ctx), seed, seed_len);
    memcpy(psha1_secret(ctx), secret, secret_len);
    /* Compute A(1) := HMAC_SHA1(secret, seed) */
    HMAC(EVP_sha1(), secret, secret_len, seed, seed_len, ctx->A, NULL);
    return ctx;
}

void P_SHA1_block(P_SHA1_CTX *ctx, char *dst)
{
    /* Compute P_SHA1(n) := HMAC_SHA1(secret, A(n)+seed) */
    HMAC(EVP_sha1(), psha1_secret(ctx), ctx->secret_len,
         ctx->A, sizeof(ctx->A)+ctx->seed_len, dst, NULL);
    /* Compute A(n+1) := HMAC_SHA1(secret, A(n)) */
    /* Note: it is allowed to pass the same memory range as input and
       output parameter to HMAC(), since it is implemented as HMAC_Update()
       (reading) followed by HMAC_Final() (writing).
       This is for OpenSSL 0.9.6 but I doubt that will change. */
    HMAC(EVP_sha1(), psha1_secret(ctx), ctx->secret_len,
         ctx->A, sizeof(ctx->A), ctx->A, NULL);
}

void P_SHA1_free(P_SHA1_CTX *ctx)
{
    memset(ctx, 0, sizeof(*ctx)+ctx->seed_len+ctx->secret_len);
    /* do not munlock this, since it may unlock others */
    free(ctx);
}
