key0-96/
key0-96/doc/key/
key0-96/doc/key/credits/
key0-96/doc/key/developers/
key0-96/doc/key/developers/resources/
key0-96/setup/caves/
key0-96/setup/help/
key0-96/setup/ruins/
key0-96/src/
key0-96/src/commands/
key0-96/src/events/
key0-96/src/hack/
key0-96/src/sql/
key0-96/src/swing/
key0-96/src/talker/forest/
key0-96/src/talker/objects/
key0-96/src/terminals/
/*
**               j###t  ########## ####   ####
**              j###t   ########## ####   ####
**             j###T               "###L J###"
**          ######P'    ##########  #########
**          ######k,    ##########   T######T
**          ####~###L   ####
**          #### q###L  ##########   .#####
**          ####  \###L ##########   #####"
**
**  $Id$
**
**  Class History
**
**  Date        Name         Description
**  ---------|------------|-----------------------------------------------
**  23Sep98     subtle      created
**
*/

package key.primitive;

import key.Key;
import key.Log;
import key.util.HTUU;
import key.InteractiveConnection;
import key.PasswordEntryCancelled;

import java.io.*;
import java.net.UnknownHostException;
import java.net.ProtocolException;
import java.util.Random;
import java.util.StringTokenizer;

/**
  *  This class is not immutable and should not be given
  *  out to people you don't want to be able to modify it.
 */
public final class Password implements java.io.Serializable
{
	public static final String FAIL_PASSWORD_LOG = "failPassword";
	public static final int MAX_PASSWORD = 10;
	
	private String password;
	
	public Password()
	{
		password = null;
	}
	
	public String toString()
	{
		if( password != null )
			return( "<set>" );
		else
			return( "<not set>" );
	}
	
	public boolean isSet()
	{
		return( (password != null) && (password.length() != 0) );
	}
	
	public boolean check( String enteredPassword )
	{
		enteredPassword = enteredPassword.substring( 0, Math.min( enteredPassword.length(), MAX_PASSWORD ) );
		
		try
		{
			if( password.equals( HTUU.encode( enteredPassword ) ) )
				return true;
			else
				return false;
		}
		catch( Exception e )
		{
			return( false );
		}
	}
	
	public boolean check( String name, InteractiveConnection ic )
		throws IOException, PasswordEntryCancelled
	{
		if( password != null && password.length() > 0 )
		{
			String in = ic.hiddenInput( "Enter your password: " );
			if( in.length() == 0 )
				throw new PasswordEntryCancelled();
			in = in.substring( 0, Math.min( in.length(), MAX_PASSWORD ) );
			
			if( check( in ) )
			{
				ic.blankLine();
				return( true );
			}
			else
			{
				ic.send( "Password incorrect." );
				ic.blankLine();
				
				Log.log( FAIL_PASSWORD_LOG, name + " from " + ic.getFullSiteName() );
				return( false );
			}
		}
		else
		{
			//ic.error( "Cannot authenticate - no password" );
			return( true );
		}
	}
	
	public void set( String newValue )
	{
		password = HTUU.encode( newValue.substring( 0, Math.min( newValue.length(), MAX_PASSWORD ) ) );
	}
}