/* -*- C -*- */
/*
 * Assembler/Disassembler for DOCSIS cable modem configuration files
 *
 * $Id: hmac_md5.c,v 1.1 2000/03/01 23:19:37 petras Exp $
 * 
 * Copyright (C) 2000  Dietmar Petras  <Dietmar.Petras@ELSA.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.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 * History:
 * $Log: hmac_md5.c,v $
 * Revision 1.1  2000/03/01 23:19:37  petras
 * Initial revision.
 *
*/

#include "hmac_md5.h"
#include <stdio.h>

unsigned char     OuterScrambleBuffer[64];

void HMAC_MD5Init(struct MD5Context *context, const unsigned char *secret, int len) {
  unsigned char scramble_buffer[64];
  int i;

 /* The secret length MUST be <= 64 bytes and SHOULD be >= 20 */
  if (len > 64)  {
    fprintf(stderr, "secret is too long (>6 character) for HMAC-MD5 algorithm\n");
    abort();
  }
  /* scrambled secret */
  for (i=0; i<len; i++) {
    scramble_buffer[i]     = secret[i] ^ 0x36;
    OuterScrambleBuffer[i] = secret[i] ^ 0x5c;
  }
  for (i=len; i<64; i++) {
    scramble_buffer[i]     = 0x36;
    OuterScrambleBuffer[i] = 0x5c;
  }

  MD5Init(context); /* initialize MD5 module for inner loop */
  MD5Update(context, scramble_buffer, 64); /* the first block is the scrambled secret */
}

void HMAC_MD5Update(struct MD5Context *context, const unsigned char *buf, int len) {
  MD5Update(context, buf, len);
}

void HMAC_MD5Final(unsigned char digest[16], struct MD5Context *context) {
  unsigned char inner_loop_digest[20];

  MD5Final(inner_loop_digest, context); /* finalize inner loop */

  MD5Init(context); /* initialize MD5 for outer loop */
  MD5Update(context, OuterScrambleBuffer, 64); /* the first block is the scrambled secret */
  MD5Update(context, inner_loop_digest, 20); /* next block is the result from inner loop */
  MD5Final(digest, context); /* finalize outer loop. */
}


/* {{{ Local variables */

/*
  Local variables:
  folded-file: t
  c-basic-offset: 2
  End:
*/

/* }}} */
