/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright Andy Armstrong, andy@tagish.com
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * Initial developer: Andy Armstrong, andy@tagish.com
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.security.internal.realm.lib;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.ow2.jonas.lib.util.Base64;
import org.ow2.jonas.security.realm.lib.HashPassword;


/**
 * Methods to hash Strings. All the methods in here are static so HashHelper
 * should never be instantiated.
 * @author Andy Armstrong, <A HREF="mailto:andy@tagish.com">andy@tagish.com </A>
 * @author Yann Petiot for the modifications
 * @author Florent Benoit modifications for integration in JOnAS
 */
public class HashHelper {

    /**
     * Constant for conversion of hex to string
     */
    private static final int HEX_CONSTANT = 0xFF;

    /**
     * Because of java 1.3, there are only 3 types of algorithms SHA == SHA-1
     */
    private static final String[] ALGORITHM = {"MD5", "MD2", "SHA-1", "SHA"};

    /**
     * Algorithm are recognized as this
     */
    private static final String[] SEPARATOR_ALGORITHM = {"MD5:", "MD2:", "SHA-1:", "SHA:"};

    /**
     * Algorithm are recognized as this too
     */
    private static final String[] SEPARATOR_ALGORITHM_BIS = {"{MD5}", "{MD2}", "{SHA-1}", "{SHA}"};

    /**
     * The default algorithm
     */
    public static final String DEFAULT_ALGO = "MD5";

    /**
     * Can't make this: all the methods are static
     */
    private HashHelper() {
    }

    /**
     * In order to use a specified algorithm, it is necessary to check if it is
     * in ALGORITHM[]
     * @param algo the String to check if it's a valid algorithm
     * @return boolean <ul><li>true if it's valid</li><li>false if it isn't
     *         </li></ul>
     */
    private static boolean isAValidAlgorithm(String algo) {
        for (int i = 0; i < ALGORITHM.length; i++) {
            if (algo.equalsIgnoreCase(ALGORITHM[i])) {
                return true;
            }
        }
        return false;
    }

    /**
     * Return the haspassword object from a string. It extracts algorithm and
     * password from the string
     * @param password contain password and algorithm
     * @return the haspassword object
     */
    public static HashPassword getHashPassword(String password) {
        String pass = null;
        String algo = null;
        //Check with the format ALGO:
        for (int i = 0; i < ALGORITHM.length; i++) {
            if (password.toUpperCase().startsWith(SEPARATOR_ALGORITHM[i])) {
                pass = password.substring(SEPARATOR_ALGORITHM[i].length());
                algo = password.substring(0, SEPARATOR_ALGORITHM[i].length() - 1);
                return new HashPassword(pass, algo);
            }
            if (password.toUpperCase().startsWith(SEPARATOR_ALGORITHM_BIS[i])) {
                pass = password.substring(SEPARATOR_ALGORITHM_BIS[i].length());
                algo = password.substring(1, SEPARATOR_ALGORITHM_BIS[i].length() - 1);
                return new HashPassword(pass, algo);
            }
        }

        //Return a haspassword without algorithm (clear password)
        return new HashPassword(password, null);
    }

    /**
     * Turn a byte array into a char array containing a printable hex
     * representation of the bytes. Each byte in the source array contributes a
     * pair of hex digits to the output array.
     * @param src the source array
     * @return a char array containing a printable version of the source data
     */
    public static char[] hexDump(byte[] src) {
        char[] buf = new char[src.length * 2];

        for (int b = 0; b < src.length; b++) {
            String byt = Integer.toHexString(src[b] & HEX_CONSTANT);

            if (byt.length() < 2) {
                buf[b * 2 + 0] = '0';
                buf[b * 2 + 1] = byt.charAt(0);
            } else {
                buf[b * 2 + 0] = byt.charAt(0);
                buf[b * 2 + 1] = byt.charAt(1);
            }
        }
        return buf;
    }

    /**
     * Zero the contents of the specified array. Typically used to erase
     * temporary storage that has held plaintext passwords so that we don't
     * leave them lying around in memory.
     * @param pwd the array to zero
     */
    public static void smudge(char[] pwd) {
        if (pwd != null) {
            for (int b = 0; b < pwd.length; b++) {
                pwd[b] = 0;
            }
        }
    }

    /**
     * Zero the contents of the specified array.
     * @param pwd the array to zero
     */
    public static void smudge(byte[] pwd) {
        if (pwd != null) {
            for (int b = 0; b < pwd.length; b++) {
                pwd[b] = 0;
            }
        }
    }

    /**
     * Performs the default algorithm hashing on the supplied password and
     * return a char array containing the password as a printable string. The
     * hash is computed on the low 8 bits of each character.
     * @param pwd The password to hash
     * @return a string representation of the hash password
     * @throws NoSuchAlgorithmException if this is not a valid algorithm
     */
    public static String hashPassword(char[] pwd) throws NoSuchAlgorithmException {
        return hashPassword(pwd, DEFAULT_ALGO);
    }

    /**
     * Performs an algorithm specified by the user hashing on the supplied
     * password and return a char array containing the encrypted password as a
     * printable string. The hash is computed on the low 8 bits of each
     * character.
     * @param pwd The password to hash
     * @param algo The type of Message Digest Algorithms
     * @return a string representation of the hash password
     * @throws NoSuchAlgorithmException if the algorithm can not be found
     */
    public static String hashPassword(char[] pwd, String algo) throws NoSuchAlgorithmException {

        if (!isAValidAlgorithm(algo)) {
            throw new NoSuchAlgorithmException("Your algorithm isn't valid or not yet supported.");
        }
        MessageDigest md = MessageDigest.getInstance(algo);
        md.reset();

        byte[] pwdb = new byte[pwd.length];
        byte[] crypt = null;
        for (int b = 0; b < pwd.length; b++) {
            pwdb[b] = (byte) pwd[b];
        }
        crypt = md.digest(pwdb);
        smudge(pwdb);
        return new String(Base64.encode(crypt));
    }

    /**
     * Performs an algorithm specified by the user hashing on the supplied
     * password and return a char array containing the encrypted password as a
     * printable string. The hash is computed on the low 8 bits of each
     * character.
     * @param string The password to hash
     * @param algo The type of Message Digest Algorithms
     * @return a string representation of the hash password
     * @throws NoSuchAlgorithmException if the algorithm can not be found
     */
    public static String hashPassword(String string, String algo) throws NoSuchAlgorithmException {
        return hashPassword(string.toCharArray(), algo);
    }
}