package mit.krb4 ;

public class Authenticate
{
	private static String crealm = "ATHENA.MIT.EDU" ;
	private static String srealm = "ATHENA.MIT.EDU" ;
	private static String kdc = "KERBEROS.MIT.EDU" ;

	private static String sinstFrom( String alias )
	throws Exception
	{
		java.net.InetAddress aliasAddr
		= java.net.InetAddress.getByName( alias ) ;
		java.net.InetAddress realAddr
		= java.net.InetAddress.getByName( aliasAddr.getHostAddress() ) ;
		String realHost = realAddr.getHostName().toLowerCase() ;
		int index = realHost.indexOf( "." ) ;
		if( -1 != index )
		{
			realHost = realHost.substring( 0 , index ) ;
		}
		return realHost ;
	}

	public static krb4.lib.Krb4Creds getUserCredentials( String clientName , String clientInst , char[] clientPassWord  )
	throws Throwable
	{
		byte[] key = krb4.lib.crypto.des.string_to_key_bytes( new String( clientPassWord ) ) ;

		krb4.lib.Krb4ASReq as_req
			= new krb4.lib.Krb4ASReq
				( clientName
				, clientInst
				, crealm
				, srealm
				) ;
		as_req.send( kdc ) ;
		krb4.lib.Krb4ASRep as_rep = as_req.getKrb4ASRep() ;
		return as_rep.getCreds( key ) ;
	}								

	public static byte[] getServiceTicket( krb4.lib.Krb4Creds clientCredentials , String service , String host , String clientName , String clientInst )
	throws Throwable
	{
		if( null != clientCredentials )
		{
			krb4.lib.Krb4TGSReq tgs_req
				= new krb4.lib.Krb4TGSReq
					( clientCredentials
					, clientName
					, clientInst
					, crealm
					, service
					, sinstFrom( host )
					, srealm
					);
			tgs_req.send( kdc ) ;
			krb4.lib.Krb4TGSRep tgs_rep = tgs_req.getKrb4TGSRep() ;
			krb4.lib.Krb4Creds creds = tgs_rep.getCreds( clientCredentials ) ;
			krb4.lib.Krb4APReq ap_req
				= new krb4.lib.Krb4APReq
					( creds
					, clientName
					, clientInst
					, crealm
					, false
					) ;

			return ap_req.encode() ;
		}
		return null ;
	}								

	public static String isValidClient( byte[] clientTicket , byte[] clientAddress , byte[] srvtab )
	throws Throwable
	{
		krb4.lib.Krb4Encode ref = new krb4.lib.Krb4Encode( srvtab );
		String service = ref.getString();
		String instance = ref.getString();
		String realm = ref.getString();
		byte keyVersion = ref.getByte();
		byte[] servKey = ref.getBytes(8);
		krb4.lib.Krb4APReq ap_req = new krb4.lib.Krb4APReq( clientTicket ) ;
		ap_req.authenticate
			( servKey
			, service
			, instance
			, realm
			, clientAddress
			) ;

		return new String( ap_req.getSessionKey() ) ;
	}								

}