C Token Generator Code

Example C code to generate an API Token

#include	"hmacmd5.h"
#include	<stdio.h>
#include	<string.h>
#include	<time.h>
#include	<Windows.h>
struct	timezone2	
{
				__int32		tz_minuteswest;	
				unsigned	short		tz_dsttime;				
};
struct	timeval2	{
				__int32				tv_sec;									
				__int32				tv_usec;						
};
const	__int64	DELTA_EPOCH_IN_MICROSECS=	11644473600000000;
//-----------------------------------------------------------------------------
int	gettimeofday(struct	timeval2 *tv,	struct	timezone2	*tz)
{
				FILETIME	ft;
				__int64	tmpres	=	0;
				TIME_ZONE_INFORMATION	tz_winapi;
				int	rez=0;
				ZeroMemory(&ft,sizeof(ft));
				ZeroMemory(&tz_winapi,sizeof(tz_winapi));
				GetSystemTimeAsFileTime(&ft);
				tmpres	=	ft.dwHighDateTime;
				tmpres	<<=	32;
				tmpres	|=	ft.dwLowDateTime;
				tmpres	/=	10;		
				tmpres	-=	DELTA_EPOCH_IN_MICROSECS;	
				tv->tv_sec	=	(__int32)(tmpres*0.000001);
				tv->tv_usec	=(tmpres%1000000);
				rez=GetTimeZoneInformation(&tz_winapi);
				tz->tz_dsttime=(rez==2)?	1	:	0;
				tz->tz_minuteswest	=	tz_winapi.Bias	+	((rez==2)?tz_winapi.DaylightBias:0);
				return	0;
}
//-----------------------------------------------------------------------------
__int64	get_timestamp()
{
				struct	timeval2	tv;
				struct	timezone2	tz;
				unsigned	char*	token;					
				__int64	timestamp;
				ZeroMemory(&tv,sizeof(tv));
				ZeroMemory(&tz,sizeof(tz));
				gettimeofday(&tv,	&tz);	
				timestamp	=	(__int64)tv.tv_sec*1000;
				return	timestamp;
}
//-----------------------------------------------------------------------------
unsigned	char*	get_token(const	unsigned	char*	secret)
{
			__int64	timestamp	=	get_timestamp();
				
				//char*	key_string	=	"testsecret:1380125439077";		
			char	key_string[1024];		
				unsigned	char	buf[16];
				unsigned	char*	token	=	(unsigned	char*)malloc(sizeof(char)	*	33);
				unsigned	char*	buf2;
				HMACMD5Context	ctx;
				int	i	=	0;
				size_t	s;
				sprintf(key_string,"%s:%llu",	secret,	timestamp);
				memset(token,	0,	sizeof(token));
				hmac_md5_init_limK_to_64((const	unsigned	char*)secret,	strlen(secret),	&ctx);
				hmac_md5_update(key_string,	strlen(key_string),	&ctx);
				hmac_md5_final(buf,	&ctx);
				buf2	=	token;
				for	(i	=	0;	i<16;	i++)
				{
								buf2	+=	sprintf(buf2,	"%02x",	buf[i]);
				}
				buf2	+=	sprintf(buf2,	"\0");
				return	token;
}				
//-----------------------------------------------------------------------------
int	main(int	argc,	char*	argv[])
{
				char*	token	=	get_token("testsecret");
				printf("%s",	token);
				return	0;
}

Example

Running this code with the timestamp 1380125439077 yields the value:

99f72d63f3cfc5d4c82765794a5ca3a7

Last updated

Was this helpful?