/* ***************************************************************************+
 * ITX package (cnrg.itx) for telephony application programming.              *
 * Copyright (c) 1999  Cornell University, Ithaca NY.                         *
 * A copy of the license is distributed with this package.  Look in the docs  *
 * directory, filename GPL.  Contact information: bergmark@cs.cornell.edu     *
 ******************************************************************************/
package cnrg.itx.ds;

import java.security.*;

/**
 * This class provides an encapsulation to store user's password information.
 */
public class Password
{
	// private data member
	private byte[] m_passwd = null;
	static private String keySALT = "ITX";

	/**
	 * Constructor for String
	 * @param strPW input password string
	 */
	public Password(String strPW) {
		MessageDigest md = null;
		String toencode;
		try {
			// using Secure Hash Algorithm (SHA)
			md = MessageDigest.getInstance("SHA");
			toencode = keySALT + strPW;
			md.reset();
			m_passwd = md.digest(toencode.getBytes());
		} catch (NoSuchAlgorithmException ex) {
			// resort to other algorithm as an alternative
			System.out.println(ex.getMessage());
			ex.printStackTrace();
		}
	}
	
	/**
	 * Verify against a given password object
	 * @param inputPW input password
	 * @return true if verified successfully; false otherwise
	 */
	public boolean verified(Password inputPW){
		return ( this.toString().compareTo(inputPW.toString()) == 0);
	}
	
	/**
	 * Verify against a given authenticated record object
	 * @param inputSEC input authenticated record object
	 * @return true if verified successfully; false otherwise
	 */
	boolean verified(AuthenticateRecord inputSEC){
		return (this.toString().compareTo(inputSEC.getKey()) == 0);
	}

	private static final char[] digits = {'0', '1', '2', '3',
					'4', '5', '6', '7',
					'8', '9', 'a', 'b',
					'c', 'd', 'e', 'f'};

	/**
	 * Converts to string representation to be stored in the directory database
	 * @return string representation of this Password object
	 */
	public String toString() {
		StringBuffer s = new StringBuffer(m_passwd.length * 2);
		for (int i = 0; i< m_passwd.length; i++) {
			byte b = m_passwd[i];
			s.append(digits[ (b & 0xf0)>>4 ]);
			s.append(digits[ (b & 0x0f) ]);
		}
		return s.toString();
	}
}
