package de.thomasjacob.improve.logic.user;

import de.thomasjacob.webcore.TechnicalException;

import java.security.MessageDigest;


/**
 * The docname.
 * 
 * @author Thomas Jacob
 */
public class Digester
{
	/**
	 * The docname singleton.
	 */
	private static final Digester INSTANCE = new Digester();

	/**
	 * Creates a new docname. This constructor is private to prevent multiple instantiation.
	 */
	private Digester()
	{
	}

	/**
	 * Returns the docname singleton.
	 * 
	 * @return The singleton.
	 */
	public static Digester getInstance()
	{
		return INSTANCE;
	}

	public static void main(String[] args) throws TechnicalException
	{
		System.out.println(getInstance().hash(args[0]));
	}

	public String hash(String password) throws TechnicalException
	{
		try
		{
			MessageDigest digest = MessageDigest.getInstance("MD5");
			digest.update(password.getBytes("UTF8"));
			byte[] resultBytes = digest.digest();

			char[] result = new char[resultBytes.length * 2];
			for (int i = 0; i < resultBytes.length; i++)
			{
				String converted = Integer.toHexString((resultBytes[i] + 256) % 256);
				if (converted.length() > 1)
				{
					result[i * 2 + 0] = converted.charAt(0);
					result[i * 2 + 1] = converted.charAt(1);
				}
				else
				{
					result[i * 2 + 0] = '0';
					result[i * 2 + 1] = converted.charAt(0);
				}
			}

			return new String(result);
		}
		catch (Exception exception)
		{
			throw new TechnicalException("Cannot build hash", exception);
		}
	}
}