

import java.math.BigInteger ;
import java.util.* ;
import java.io.* ;
import java.sql.*;

/**
 * Class for RSAmod Algorithm (RSAmod.java).
 *
 * Generates Prime numbers and Public/Private Keys. Performs Encryption and Decryption.
 *
 * @author  Chue Wai Lian
 * @version
 *
 * 1.0.0	11 Apr 2001
 * <br>		1st release.
 */
public class RSAmod
{
	/**
	 * Bit length of each prime number.
	 */
	int primeSize ;
            
	/**
	 * Two distinct large prime numbers p and q.
	 */
	BigInteger p, q ;

	/**
	 * Modulus N.
	 */
	BigInteger N ;

	/**
	 * phi_n = ( p - 1 ) * ( q - 1 )
	 */
	BigInteger phi_n ;

	/**
	 * Public exponent E and Private exponent D
	 */
	BigInteger E, D ;


	/**
	 * Constructor.
	 *
	 * @param	primeSize		Bit length of each prime number.
	 */
	public RSAmod( int primeSize )
	{
		this.primeSize = primeSize ;

		
		// Generate two distinct large prime numbers p and q.
		generatePrimeNumbers() ;

		// Generate Public and Private Keys.
		generatePublicPrivateKeys() ;
		
	}


	/**
	 * Generate two distinct large prime numbers p and q.
	 */
	public void generatePrimeNumbers()
	{
		//System.out.println
	//	System.out.println("Starting time is ");
	//	long start=getCurrentTime();
		p = new BigInteger( primeSize, 10, new Random() ) ;

		do
		{
			q = new BigInteger( primeSize, 10, new Random() ) ;
		}
		while( q.compareTo( p ) == 0 ) ;
          //      System.out.println("Prime number search completed at ");
	//	long end=getCurrentTime();

	//	System.out.println("Total elapsed time (in nsec) = "+(new Timestamp(end-start)).getNanos());
            
                
	}

	/*
        public long getCurrentTime()
        {
                java.util.Date date=Calendar.getInstance().getTime();
          Timestamp a=new Timestamp(date.getTime()); 
          long currentTime=Calendar.getInstance().getTimeInMillis();
                System.out.println("Time: "+currentTime);
                
                return currentTime;
        }
        */  

	public static long getCurrentTime()
	{
		long currentTime=System.currentTimeMillis();

                //System.out.println("Time: "+currentTime);
                
                return currentTime;
	}



	/**
	 * Generate Public and Private Keys.
	 */
	public void generatePublicPrivateKeys()
	{
		// N = p * q
		N = p.multiply( q ) ;


		// phi_n = ( p - 1 ) * ( q - 1 )
		phi_n = p.subtract( BigInteger.valueOf( 1 ) ) ;
		phi_n = phi_n.multiply( q.subtract( BigInteger.valueOf( 1 ) ) ) ;


		// Choose E, coprime to and less than phi_n
		do
		{
			E = new BigInteger( 2 * primeSize, new Random() ) ;
		}
		while( ( E.compareTo( phi_n ) >= 0 ) || ( E.gcd( phi_n ).compareTo( BigInteger.valueOf( 1 ) ) != 0 ) ) ;


		// Compute D, the inverse of E mod phi_n
		D = E.modInverse( phi_n ) ;
	}


	/**
	 * Encrypts the plaintext (Using Public Key).
	 *
	 * @param	message			String containing the plaintext message to be encrypted.
	 * @return	The ciphertext as a BigInteger array.
	 */
	public BigInteger[] encrypt( String message )
	{
		int i , j , k , szBlock;


		byte[] digits = message.getBytes() ;

		i = 0;

		BigInteger iter = BigInteger.ONE;

		while( true ) {
			j = (int)Math.pow(2 , i);
			iter = BigInteger.valueOf(2).pow(j);
			if ( iter.compareTo( N ) >= 0 ) {
				i--; /*Actual val of k*/
				break;
			}

			i++;
		}
		i -= 3; /*To convert to bytes*/
		szBlock = (int)Math.pow(2 , i);

		byte[] temp = new byte[szBlock] ;
		
		BigInteger[] bigdigits = new BigInteger[((digits.length - 1)/szBlock) + 1] ;

		for( i = 0, k = 0 ; k < bigdigits.length ; k++) {

			for( j = 0 ; j < szBlock && i < digits.length; j++, i++) {
				temp[j] = digits[i] ;
			}
			while( j < szBlock ) {
				temp[j] = 0;
				j++;
			}

			bigdigits[k] = new BigInteger( temp ) ;
		}

		BigInteger[] encrypted = new BigInteger[bigdigits.length] ;

		for( i = 0 ; i < bigdigits.length ; i++ ) 
			encrypted[i] = bigdigits[i].modPow( E, N ) ;

		return( encrypted ) ;
	}


	/**
	 * Decrypts the ciphertext (Using Private Key).
	 *
	 * @param	encrypted		BigInteger array containing the ciphertext to be decrypted.
	 * @return	The decrypted plaintext.
	 */
	public String decrypt( BigInteger[] encrypted )
	{
		int i , j , szBlock;

		i = 0;

		BigInteger iter = BigInteger.ONE;

		while( true ) {
			j = (int)Math.pow(2 , i);
			iter = BigInteger.valueOf(2).pow(j);
			if ( iter.compareTo( N ) >= 0 ) {
				i--; /*Actual val of k*/
				break;
			}

			i++;
		}
		i -= 3; /*To convert to bytes*/
		szBlock = (int)Math.pow(2 , i);

		byte[] temp = new byte[szBlock] ;
	
		BigInteger[] decrypted = new BigInteger[encrypted.length] ;
		char[] charArray = new char[decrypted.length * szBlock] ;

		for( i = 0 ; i < decrypted.length ; i++ ) {
			decrypted[i] = encrypted[i].modPow( D, N ) ;
			temp = decrypted[i].toByteArray();

			for( j = 0 ; j < temp.length ; j++ ) 
				charArray[(i * szBlock) + j] = (char)temp[j];
		}

		return( new String( charArray ) ) ;
	}


	/**
	 * Get prime number p.
	 *
	 * @return	Prime number p.
	 */
	public BigInteger getp()
	{
		return( p ) ;
	}


	/**
	 * Get prime number q.
	 *
	 * @return	Prime number q.
	 */
	public BigInteger getq()
	{
		return( q ) ;
	}


	/**
	 * Get phi_n.
	 *
	 * @return	phi_n.
	 */
	public BigInteger getphi_n()
	{
		return( phi_n ) ;
	}


	/**
	 * Get modulus N.
	 *
	 * @return	Modulus N.
	 */
	public BigInteger getN()
	{
		return( N ) ;
	}


	/**
	 * Get Public exponent E.
	 *
	 * @return	Public exponent E.
	 */
	public BigInteger getE()
	{
		return( E ) ;
	}


	/**
	 * Get Private exponent D.
	 *
	 * @return	Private exponent D.
	 */
	public BigInteger getD()
	{
		return( D ) ;
	}



	/**
	 * RSA Main program for Unit Testing.
	 */
	public static void main( String[] args ) throws IOException
	{
		if( args.length != 1 )
		{
			System.out.println( "Syntax: java RSA PrimeSize" ) ;
			System.out.println( "e.g. java RSA 8" ) ;
			System.out.println( "e.g. java RSA 512" ) ;
			System.out.println( "Exiting program ..." ) ;
      
			System.exit( -1 ) ;
		}

		long sKey, eKey, sEnc, eEnc, sDec, eDec;
		//args=new String[1];
		//args[0]="1024";

		//args=new String[1];
		//args[0]="512";
		//args[0]="1024";
		// Get bit length of each prime number
		int primeSize = Integer.parseInt( args[0] ) ;


		sKey = getCurrentTime();
		// Generate Public and Private Keys

		RSAmod rsa = new RSAmod( primeSize ) ;
		eKey = getCurrentTime();

	//	System.out.println(end-start);

	/*
		System.out.println( "Key Size: [" + primeSize + "]" ) ;
		System.out.println( "" ) ;

		System.out.println( "Generated prime numbers p and q" ) ;
		System.out.println( "p: [" + rsa.getp().toString( 16 ).toUpperCase() + "]" ) ;
		System.out.println( "q: [" + rsa.getq().toString( 16 ).toUpperCase() + "]" ) ;
		System.out.println( "" ) ;

		System.out.println( "The public key is the pair (N, E) which will be published." ) ;
		System.out.println( "N: [" + rsa.getN().toString( 16 ).toUpperCase() + "]" ) ;
		System.out.println( "E: [" + rsa.getE().toString( 16 ).toUpperCase() + "]" ) ;
		System.out.println( "" ) ;

		System.out.println( "The private key is the pair (N, D) which will be kept private." ) ;
		System.out.println( "N: [" + rsa.getN().toString( 16 ).toUpperCase() + "]" ) ;
		System.out.println( "D: [" + rsa.getD().toString( 16 ).toUpperCase() + "]" ) ;
		System.out.println( "" ) ;


		// Get message (plaintext) from user
		System.out.println( "Please enter message (plaintext):" ) ;
	*/	String plaintext = ( new BufferedReader( new InputStreamReader( System.in ) ) ).readLine() ;
	//	System.out.println( "" ) ;
	
		sEnc = getCurrentTime();
		// Encrypt Message
		BigInteger[] ciphertext = rsa.encrypt( plaintext ) ;
		
		eEnc = getCurrentTime();
	//	System.out.println(end-start);

	/*	System.out.print( "Ciphertext: [" ) ;
		for( int i = 0 ; i < ciphertext.length ; i++ )
		{
			System.out.print( ciphertext[i].toString( 16 ).toUpperCase() ) ;

			if( i != ciphertext.length - 1 )
				System.out.print( " " ) ;
		}
		System.out.println( "]" ) ;
		System.out.println( "" ) ;
	
*/
		sDec = getCurrentTime();
		String recoveredPlaintext = rsa.decrypt( ciphertext ) ;
		
		eDec = getCurrentTime();
	//	System.out.println(end-start);
		
		System.out.println(primeSize + " " + (eKey-sKey) + " " + (eEnc-sEnc) + " " + (eDec-sDec));

	//	System.out.println( "Recovered plaintext: [" + recoveredPlaintext + "]" ) ;
	}
}

