package net.y3n20u.rfc2898;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;

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

/**
 * An implementation of {@link PseudorandomFunction}. This class uses the
 * Hmac-SHA1 algorithm.
 * 
 * @author y3n20u@gmail.com
 * 
 */
public class PrfHmacSha1 implements PseudorandomFunction {
	/**
	 * the length in octets of output. 20bytes (160bits)
	 */
	public static final int OUTPUT_LENGTH = 20;

	/**
	 * the name of the used algorithm.
	 */
	private static final String MAC_ALGORITHM = "HmacSHA1";

	private static final String MESSAGE_ALGORITHM_NOT_SUPPORTED = MessageFormat.format(
			"Algorithm not supported in this environment: {0}", MAC_ALGORITHM);

	@Override
	public int getLengthOfOutput() {
		return OUTPUT_LENGTH;
	}

	@Override
	public byte[] getPseudorandomBytes(byte[] p, byte[] u) {
		SecretKeySpec secretKeySpec = new SecretKeySpec(p, MAC_ALGORITHM);
		Mac mac;
		try {
			mac = Mac.getInstance(MAC_ALGORITHM);
			mac.init(secretKeySpec);
		} catch (NoSuchAlgorithmException nsle) {
			throw new RuntimeException(MESSAGE_ALGORITHM_NOT_SUPPORTED, nsle);
		} catch (InvalidKeyException ike) {
			throw new RuntimeException(ike);
		}
		return mac.doFinal(u);
	}

}
