package amazon;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

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

import org.apache.commons.codec.binary.Base64;

public class MACDemo {

	private static final String ALGORITHM = "HmacMD5";
	private static final String CHARACTER_ENCODING = "UTF-8";

	public static byte[] generateSecretKey() throws NoSuchAlgorithmException {
		KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
		SecretKey secretKey = generator.generateKey();
		byte[] key = secretKey.getEncoded();
		return key;
	}

	public static String encodeHmacMD5(byte[] data, byte[] key)
			throws NoSuchAlgorithmException, InvalidKeyException,
			UnsupportedEncodingException {
		SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
		Mac mac = Mac.getInstance(ALGORITHM);
		mac.init(secretKey);
		byte[] digest = mac.doFinal(data);
		// 转换成Base64
		String digestBase64 = new String(Base64.encodeBase64(digest),
				CHARACTER_ENCODING);
		return new String(digestBase64);
	}

	public static void main(String[] args) {
		String dateStr = "这是一个测试数据";
		try {
			byte[] secretKey = generateSecretKey();
			System.out.println(encodeHmacMD5(dateStr.getBytes(), secretKey));
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

}
