/* ************************************************************************
#
#  DivConq
#
#  http://divconq.com/
#
#  Copyright:
#    Copyright 2012 eTimeline, LLC. All rights reserved.
#
#  License:
#    See the license.txt file in the project's top-level directory for details.
#
#  Authors:
#    * Andy White
#
************************************************************************ */
package divconq.util;

import java.security.MessageDigest;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class HashUtil {
	/**
	 * Calculate an MD5 on a string, return a hex formated string of the MD5
	 * 
	 * @param str source to hash
	 * @return hex MD5 value
	 */
	public static String getMd5(String str) {
		try {
	        MessageDigest md = MessageDigest.getInstance("MD5");
	        md.update(str.getBytes());
	        return HexUtil.bufferToHex(md.digest(), 0, md.digest().length);
		}
		catch (Exception x) {
		}
		
		return null;
    }
	
	/**
	 * Calculate an SHA-512 on a string, return a hex formated string of the SHA
	 * 
	 * @param str source to hash
	 * @return hex SHA value
	 */
	public static String getSha2(String str) {
		try {
	        MessageDigest md = MessageDigest.getInstance("SHA-512");
	        md.update(str.getBytes());
	        byte[] rv = md.digest();
	        return HexUtil.bufferToHex(rv, 0, rv.length);
		}
		catch (Exception x) {
		}
		
		return null;
    }
	
	/**
	 * Calculate an SHA-512 on a string, return a hex formated string of the SHA.
	 * This is a keyed hash (HMAC), provide a key.  Any size will work, however,
	 * SHA-512 uses a 1024 bit block size so 1024 is the largest size useful,
	 * anything larger will be truncated.  Anything smaller will be zero padded
	 * which means it is less unique.
	 * 
	 * @param str source to hash
	 * @param key 
	 * @return hex SHA value
	 */
	public static String getMacSha2(String str, byte[] key) {
		try {
			SecretKeySpec skey = new SecretKeySpec(key, "hmacSHA512");
			Mac mac = Mac.getInstance("hmacSHA512");
			mac.init(skey);
			
			byte[] rv = mac.doFinal(str.getBytes());
	        return HexUtil.bufferToHex(rv, 0, rv.length);
		} 
		catch (Exception x) {
		}	
		
		return null;
	}
}
