/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package securehash;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author tcolburn
 */
public class HashedPassword {
    
    public HashedPassword(String password, String algorithm) {
        
        MessageDigest md = null;
        
        try {
            md = MessageDigest.getInstance(algorithm);
        }
        catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(HashedPassword.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        md.update(password.getBytes());
        hashBytes = md.digest();
    }


    /**
     * Use this constructor after retrieving a user's hashed password from
     * the database
     * @param hashBytes the 64-byte hash string stored in the database
     */
    public HashedPassword(byte[] hashBytes) {
        this.hashBytes = hashBytes;
    }
    

    /**
     * Use this to test hashed password equality.  Succeeds if this object's
     * hash string matches the other object's hash string byte for byte.
     * @param o the other hashed password object
     * @return whether the two objects' hash strings match
     */
    public boolean equals(Object o) {
        
        if ( o.getClass() != this.getClass() ) {
            return false;
        }

        byte[] otherBytes = ((HashedPassword) o).hashBytes;

        if ( otherBytes.length != hashBytes.length ) {
            return false;
        }

        for (int i = 0; i < hashBytes.length; i++ ) {
            if ( hashBytes[i] != otherBytes[i] ) {
                return false;
            }
        }
        
        return true;
    }

    /**
     * Use this accessor to get the hash string from a hashed password in order
     * to store the string in the database.
     * @return the hash string for this hashed password object
     */
    public byte[] getHashBytes() {
        return hashBytes;
    }

    private byte[] hashBytes;

}