/*
 * otpCalc - A one time password calculator.
 *
 * Copyright (C) 2001 Anthony D. Urso
 * Copyright 2008-2021 Gentoo Authors
 *
 * 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, 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.
 *
 */

#include <string.h>

#include "crypto.h"
#include "config.h"

#include <openssl/md4.h>
#include <openssl/md5.h>
#include <openssl/ripemd.h>
#include <openssl/sha.h>


/*
 * Perform an MD5 transform on the passwd+seed, and fold the results into 64
 * bits.
 */

void md4lite(unsigned char *message, unsigned int len)
{

	unsigned char digest[16];
	unsigned short i;


	MD4(message, len, digest);

	/* Fold the 128 bit result to 64 bits */
	for (i = 0; i < 8; i++)
		digest[i] ^= digest[i+8];

	memcpy(message, digest, 8);

}


/*
 * Perform an MD5 transform on the passwd+seed, and fold the results into 64
 * bits.
 */

void md5lite(unsigned char *message, unsigned int len)
{

	unsigned char digest[16];
	unsigned short i;


	MD5(message, len, digest);

	/* Fold the 128 bit result to 64 bits */
	for (i = 0; i < 8; i++)
		digest[i] ^= digest[i+8];

	memcpy(message, digest, 8);

}


/*
 * Perform an RIPEMD-160 transform on the passwd+seed, and fold the results
 * into 64 bits.
 */

void rmd160lite(unsigned char *message, unsigned int len)
{

	unsigned char digest[20];
	unsigned short i;


	RIPEMD160(message, len, digest);

	/* Fold the 160 bit result to 64 bits */
	for (i = 0; i < 8; i++)
		digest[i] ^= digest[i+8];
	for (i = 0; i < 4; i++)
		digest[i] ^= digest[i+16];

	memcpy(message, digest, 8);

}


/*
 * Perform an SHA-1 transform on the passwd+seed, and fold the results
 * into 64 bits.
 */

void sha1lite(unsigned char *message, unsigned int len)
{

	unsigned char digest[20];
	unsigned short i;


	SHA1(message, len, digest);

	/* Fold the 160 bit result to 64 bits */
	for (i = 0; i < 8; i++)
		digest[i] ^= digest[i+8];
	for (i = 0; i < 4; i++)
		digest[i] ^= digest[i+16];

	/* Fix byte order, as required by RFC 2289 Appendix A */
	for (i = 0; i < 8; i++)
		 message[i] = digest[i^3];

}
