/*
 * skey.c
 *		 Copyright (C) 1995 Kazuhiko Yamamoto
 *	      Kazuhiko Yamamoto <kazu@is.aist-nara.ac.jp>
 *		 Copyright (C) 2016 Peter Pentchev <roam@ringlet.net>
 */

#include "config.h"
#include "donkey.h"
#include "md.h"

static void sevenbit(char *s)
{
	/* make sure there are only 7 bit code in the line*/
	while(*s){
		*s = 0x7f & (*s);
		s++;
	}
}

int keycrunch(char * const result, const char * const seed, const char * const passwd)
{
	D_MDX_CTX md;
	UINT4 results[4];
	
	const size_t buflen = strlen(seed) + strlen(passwd);
	char * const buf = malloc(buflen + 1);
	if(buf == NULL)
		return(RET_ERROR);
	strcpy(buf, seed);
	strcat(buf, passwd);

	/* Crunch the key through MD[45] */
	sevenbit(buf);
	(*mdsw[MD].md_init)(&md);
	(*mdsw[MD].md_update)(&md, (POINTER)buf, buflen);
	(*mdsw[MD].md_final)((POINTER)results, &md);
	free(buf);

	results[0] ^= results[2];
	results[1] ^= results[3];

	memcpy(result,(char *)results,8);

	return(RET_SUCCESS);
}

void secure_hash(char * const x)
{
	D_MDX_CTX md;
	UINT4 results[4];

	(*mdsw[MD].md_init)(&md);
	(*mdsw[MD].md_update)(&md,(POINTER)x, 8);
	(*mdsw[MD].md_final)((POINTER)results, &md);
	/* Fold 128 to 64 bits */
	results[0] ^= results[2];
	results[1] ^= results[3];

	/* Only works on byte-addressed little-endian machines!! */
	memcpy(x, (char *)results, 8);
}

/*
 * This code is imported from Bollcore's S/KEY
 */
