View Javadoc
1   package org.oxerr.chbtc.util;
2   
3   import java.nio.charset.Charset;
4   import java.nio.charset.StandardCharsets;
5   import java.security.MessageDigest;
6   import java.security.NoSuchAlgorithmException;
7   import java.util.Arrays;
8   
9   public class EncryDigestUtil {
10  
11  	private static final Charset ENCODING_CHARSET = StandardCharsets.UTF_8;
12  
13  	/**
14  	 * 生成签名消息
15  	 * @param aValue  要签名的字符串
16  	 * @param aKey  签名密钥
17  	 * @return the signature.
18  	 */
19  	public static String hmacSign(String aValue, String aKey) {
20  		byte k_ipad[] = new byte[64];
21  		byte k_opad[] = new byte[64];
22  		byte keyb[];
23  		byte value[];
24  		keyb = aKey.getBytes(ENCODING_CHARSET);
25  		value = aValue.getBytes(ENCODING_CHARSET);
26  
27  		Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
28  		Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
29  		for (int i = 0; i < keyb.length; i++) {
30  			k_ipad[i] = (byte) (keyb[i] ^ 0x36);
31  			k_opad[i] = (byte) (keyb[i] ^ 0x5c);
32  		}
33  
34  		MessageDigest md = null;
35  		try {
36  			md = MessageDigest.getInstance("MD5");
37  		} catch (NoSuchAlgorithmException e) {
38  
39  			return null;
40  		}
41  		md.update(k_ipad);
42  		md.update(value);
43  		byte dg[] = md.digest();
44  		md.reset();
45  		md.update(k_opad);
46  		md.update(dg, 0, 16);
47  		dg = md.digest();
48  		return toHex(dg);
49  	}
50  
51  	public static String toHex(byte input[]) {
52  		if (input == null) {
53  			return null;
54  		}
55  		StringBuffer output = new StringBuffer(input.length * 2);
56  		for (byte element : input) {
57  			int current = element & 0xff;
58  			if (current < 16) {
59  				output.append("0");
60  			}
61  			output.append(Integer.toString(current, 16));
62  		}
63  
64  		return output.toString();
65  	}
66  
67  	public static String getHmac(String[] args, String key) {
68  		if (args == null || args.length == 0) {
69  			return null;
70  		}
71  		StringBuffer str = new StringBuffer();
72  		for (String arg : args) {
73  			str.append(arg);
74  		}
75  		return hmacSign(str.toString(), key);
76  	}
77  
78  	/**
79  	 * SHA加密
80  	 * @param aValue string to digest.
81  	 * @return the digested string.
82  	 */
83  	public static String digest(String aValue) {
84  		aValue = aValue.trim();
85  		byte value[];
86  		value = aValue.getBytes(ENCODING_CHARSET);
87  		MessageDigest md = null;
88  		try {
89  			md = MessageDigest.getInstance("SHA");
90  		} catch (NoSuchAlgorithmException e) {
91  			e.printStackTrace();
92  			return null;
93  		}
94  		return toHex(md.digest(value));
95  
96  	}
97  
98  }