HmacUtil.java 2.41 KB
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");
    }
}