View Javadoc
1   package com.foxinmy.weixin4j.util;
2   
3   import javax.crypto.Mac;
4   import javax.crypto.spec.SecretKeySpec;
5   import java.security.InvalidKeyException;
6   import java.security.MessageDigest;
7   import java.security.NoSuchAlgorithmException;
8   
9   /**
10   * 签名工具类
11   * 
12   * @className DigestUtil
13   * @author jinyu(foxinmy@gmail.com)
14   * @date 2015年5月6日
15   * @since JDK 1.6
16   * @see
17   */
18  public final class DigestUtil {
19  
20  	private static MessageDigest getDigest(final String algorithm) {
21  		try {
22  			return MessageDigest.getInstance(algorithm);
23  		} catch (final NoSuchAlgorithmException e) {
24  			throw new IllegalArgumentException(e);
25  		}
26  	}
27  
28  	/**
29  	 * SHA1签名
30  	 * 
31  	 * @param content
32  	 *            待签名字符串
33  	 * @return 签名后的字符串
34  	 */
35  	public static String SHA1(String content) {
36  		byte[] data = StringUtil.getBytesUtf8(content);
37  		return HexUtil.encodeHexString(getDigest(Consts.SHA1).digest(data));
38  	}
39  
40  	/**
41  	 * SHA签名
42  	 * 
43  	 * @param content
44  	 *            待签名字符串
45  	 * @return 签名后的字符串
46  	 */
47  	public static String SHA(String content) {
48  		byte[] data = StringUtil.getBytesUtf8(content);
49  		return HexUtil.encodeHexString(getDigest(Consts.SHA).digest(data));
50  	}
51  
52  	/**
53  	 * MD5签名
54  	 * 
55  	 * @param content
56  	 *            待签名字符串
57  	 * @return 签名后的字符串
58  	 */
59  	public static String MD5(String content) {
60  		byte[] data = StringUtil.getBytesUtf8(content);
61  		return HexUtil.encodeHexString(getDigest(Consts.MD5).digest(data));
62  	}
63  
64  	/**
65  	 * HMAC-SHA256签名
66  	 *
67  	 * @param content
68  	 * 			待签名字符串
69  	 * @param key
70  	 * 			支付密钥
71  	 * @return
72  	 * @throws InvalidKeyException
73  	 */
74  	public static String HMACSHA256(String content, String key) throws InvalidKeyException{
75  		try {
76  			Mac mac = Mac.getInstance("HmacSHA256");
77  			SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), "HmacSHA256");
78  			mac.init(secret_key);
79  			byte[] bytes = mac.doFinal(content.getBytes());
80  			return HexUtil.encodeHexString(bytes);
81  		} catch (NoSuchAlgorithmException e) {
82  		}
83  		return null;
84  	}
85  }