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
13
14
15
16
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
30
31
32
33
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
42
43
44
45
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
54
55
56
57
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
66
67
68
69
70
71
72
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 }