HmacUtil.java
2.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package com.bckefu.uccc.hmac;
import org.apache.commons.codec.digest.HmacUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.SignatureException;
/**
* Created by caoliang on 2017/8/4.
*/
public class HmacUtil {
Logger logger = LoggerFactory.getLogger(HmacUtil.class);
/**
*
* @param message
* @param issuer
* @param ttl
* @throws HmacException
*/
public String encodeMac(String message , String issuer , Integer ttl) throws HmacException{
HmacToken hmacToken = SecurityUtils.getSignedToken(SecurityUtils.generateSecret(),issuer,ttl,null);
return SecurityUtils.encodeMac(hmacToken.getSecret(),message, "HmacSHA256");
}
/**
*
* @param message
* @return
* @throws HmacException
*/
public String encodeMac(String message) throws HmacException{
HmacToken hmacToken = SecurityUtils.getSignedToken(SecurityUtils.generateSecret(),"BCKEFU", 10,null);
return SecurityUtils.encodeMac(hmacToken.getSecret(),message, "HmacSHA256");
}
/**
*
* @param data
* @param key
* @return
* @throws java.security.SignatureException
*/
public static String calculateRFC2104HMAC(String data, String key , String algorithm) throws SignatureException {
String result;
try {
HmacUtils.hmacSha256(key ,data);
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(),algorithm);
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes());
// base64-encode the hmac
result = new BASE64Encoder().encode(rawHmac);
} catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
/**
*
* @param message
* @param key
* @return
* @throws SignatureException
*/
public static String calculateRFC2104HMAC(String message , String key) throws SignatureException {
return calculateRFC2104HMAC(message , key , "HmacSHA1");
}
}