#include<stdio.h>
#include<math.h>

/* diffi.c -- it genarates the private key for the Diffie- Hellman key exchange method.]
 *
 * AURHOR: P. Subramanyam
 * DATE  : 29/08/03
 * 
 * Inputs are prime number "p", genarator "g", publickey
 *
 */

main()
{
	unsigned long p=24691,g=106,publickey=12375,c,d,k,t,temp,mask;
	long i,j;	// counter variable	
	for(i=0;i<24691;i++)
	{
		d=1;	// it finally hold "pow(g,i) mod p".
		mask=1;	// used to check each bit in i
		k=1;	// holds number of bits in the variable i in pow(g,i). it doesnot count most significant digit
		t=i;	// temporary variable used to get the number of bits in "i"
		if(i!=0)// if i==0 then d=1 only
		{	
			while(1)
			{
				t<<=1;
				if(!(t&0x80000000)) k++;//first count number of mostsignificant 0's.
				else break;
			}
			k=32-k;// get the actual number of bits
			temp=k;// used to calculate mask which is used to get bit "j" from "i"(see for loop)
			while(temp>1) 
			{
				mask<<=1;
				temp--;
			}
			for(j=k;j>0;j--)
			{
				d=(d*d)%p;
				if(mask&i)	d=(d*g)%p;
				mask>>=1;
			}
		}
		
		if(publickey==d)
		{
			printf("\n\nThe private key is: %ld\n\n",i);
			break;
		}
	}
}
