HMAC-SHA1签名工具类

package cn.manmanda.core.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/** 
 * 
 * ━━━━━━神兽出没━━━━━━ 
 *    ┏┓   ┏┓ 
 *   ┏┛┻━━━┛┻┓ 
 *   ┃       ┃ 
 *   ┃   ━   ┃ 
 *   ┃ ┳┛ ┗┳ ┃ 
 *   ┃       ┃ 
 *   ┃   ┻   ┃ 
 *   ┃       ┃ 
 *   ┗━┓   ┏━┛Code is far away from bug with the animal protecting 
 *     ┃   ┃    神兽保佑,代码无bug 
 *     ┃   ┃ 
 *     ┃   ┗━━━┓ 
 *     ┃       ┣┓ 
 *     ┃       ┏┛ 
 *     ┗┓┓┏━┳┓┏┛ 
 *      ┃┫┫ ┃┫┫ 
 *      ┗┻┛ ┗┻┛ 
 * 
 * ━━━━━━感觉萌萌哒━━━━━━ 
 */
public class HMAC_SHA1Util {

    private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";  

    /** 
     * 使用 HMAC-SHA1 签名方法对data进行签名 
     *  
     * @param data 
     *            被签名的字符串 
     * @param key 
     *            密钥      
     * @return  
                      加密后的字符串 
     */  
    public static String genHMAC(String data, String key) {  
        byte[] result = null;  
        try {  
            byte[] bytekey = key.getBytes("UTF-8");
            //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称    
            SecretKeySpec signinKey = new SecretKeySpec(bytekey, HMAC_SHA1_ALGORITHM);  
            //生成一个指定 Mac 算法 的 Mac 对象    
            Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);  
            //用给定密钥初始化 Mac 对象    
            mac.init(signinKey);  
            //完成 Mac 操作     
            byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));  
            result = Base64.encodeBase64(rawHmac);  

        } catch (NoSuchAlgorithmException e) {  
            System.err.println(e.getMessage());  
        } catch (InvalidKeyException e) {  
            System.err.println(e.getMessage());  
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } 

        if (null != result) {  
            return new String(result);  
        } else {  
            return null;  
        } 
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值