hmac-md5

 1 import java.io.UnsupportedEncodingException;
 2 import java.security.MessageDigest;
 3 import java.security.NoSuchAlgorithmException;
 4 import java.util.Arrays;
 5 public class SignatureUtil {
 6     private static String encodingCharset = "UTF-8";
 7     public static String hmacSign(String aValue, String aKey) {
 8         byte k_ipad[] = new byte[64];
 9         byte k_opad[] = new byte[64];
10         byte keyb[];
11         byte value[];
12         try {
13             keyb = aKey.getBytes(encodingCharset);
14             value = aValue.getBytes(encodingCharset);
15         } catch (UnsupportedEncodingException e) {
16             keyb = aKey.getBytes();
17             value = aValue.getBytes();
18         }
19         Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
20         Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
21         for (int i = 0; i < keyb.length; i++) {
22             k_ipad[i] = (byte) (keyb[i] ^ 0x36);
23             k_opad[i] = (byte) (keyb[i] ^ 0x5c);
24         }
25         MessageDigest md = null;
26         try {
27             md = MessageDigest.getInstance("MD5");
28         } catch (NoSuchAlgorithmException e) {
29             return null;
30         }
31         md.update(k_ipad);
32         md.update(value);
33         byte dg[] = md.digest();
34         md.reset();
35         md.update(k_opad);
36         md.update(dg, 0, 16);
37         dg = md.digest();
38         return toHex(dg);
39     }
40 public static String toHex(byte input[]) {
41         if (input == null)
42             return null;
43         StringBuffer output = new StringBuffer(input.length * 2);
44         for (int i = 0; i < input.length; i++) {
45             int current = input[i] & 0xff;
46             if (current < 16)
47                 output.append("0");
48             output.append(Integer.toString(current, 16));
49         }
50         return output.toString();
51     }
52 }

 

posted @ 2020-06-01 12:04  Johnson718  阅读(261)  评论(0编辑  收藏  举报