#if !defined(lint) && !defined(__INSIGHT__)
static char sos__rcsid[] = "auth.c,v 1.1.1.1 1995/06/16 17:42:40 seth Exp";
static char sos__copyright[] = "Copyright (c) 1994, 1995 SOS Corporation";
static char sos__contact[] = "SOS Corporation <sos-info@soscorp.com> +1 800 SOS UNIX";
#endif /* not lint */

/*
 * ++Copyright Released Product++
 *
 * Copyright (c) 1994, 1995 Sources of Supply Corporation ("SOS").
 * All rights reserved.
 *
 * The SOS Released Product License Agreement specifies the terms and
 * conditions for redistribution.  You may find the License Agreement
 * in the file LICENSE.
 *
 * SOS Corporation
 * 461 5th Ave.; 16th floor
 * New York, NY 10017
 *
 * +1 800 SOS UNIX
 * <sos-info@soscorp.com>
 *
 * --Copyright Released Product--
 */

/*
 * SOS's trivial authentication routines
 */

#include "sos.h"
#include "md5.h"

/*
 * Hash 'em together but output in 64 characterspace with prepended salt
 */
unsigned char *sos_statichash(unsigned char salt[4], unsigned char *password)
{
  static unsigned char outbuf[40];
  MD5_CTX context;

  if (!salt || !password)
    return NULL;

  MD5Init (&context);
  MD5Update(&context, salt, sizeof(salt));
  MD5Update(&context, password, strlen(password));
  MD5Final(&context);

  memset(outbuf,0,sizeof(outbuf));
  memcpy(outbuf,salt,sizeof(salt));

  sprintf(outbuf+sizeof(salt),"%08x%08x%08x%08x",
	  htonl((*(int *)(&(context.digest[0])))),
	  htonl((*(int *)(&(context.digest[4])))),
	  htonl((*(int *)(&(context.digest[8])))),
	  htonl((*(int *)(&(context.digest[12])))));

  return outbuf;
}

/*
 * Returns 8 bytes of BINARY data which represent (one half) the hash
 *
 * We are only using 8 bytes instead of 16 to ease user entry
 */
unsigned char *sos_dynamichash(char *salt, unsigned char challenge[8], unsigned char *password)
{
  static unsigned char output[18];
  MD5_CTX context;

  if (!challenge || !password)
    return NULL;

  *((unsigned int *)&(challenge[0])) = htonl(*((unsigned int *)&(challenge[0])));
  *((unsigned int *)&(challenge[4])) = htonl(*((unsigned int *)&(challenge[4])));

  MD5Init (&context);
  MD5Update(&context, salt, strlen(salt));
  MD5Update(&context, challenge, sizeof(challenge));
  MD5Update(&context, password, strlen(password));
  MD5Final(&context);

  memset(output,0,sizeof(output));
  memcpy(output,&(context.digest[0]),8);

  *((unsigned int *)&(output[0])) = htonl(*((unsigned int *)&(output[0])));
  *((unsigned int *)&(output[4])) = htonl(*((unsigned int *)&(output[4])));

  return output;
}
