java HmacSHA1 计算

此处使用SecretKeySpec 构造 key,用Mac对象初始化构造的key对象,

//MAC算法主要集合了MD和SHA两大系列消息摘要算法。MD系列的算法有HmacMD2、HmacMD4、HmacMD5三种算法;
//SHA系列的算法有HmacSHA1、HmacSHA224、HmacSHA256、HmacSHA384.HmacSHA512五种算法。

/**
	 * hmac+签名算法 加密
	 * @param content  内容
	 * @param charset  字符编码
	 * @param key	         加密秘钥
	 * @param hamaAlgorithm hamc签名算法名称:例如HmacMD5,HmacSHA1,HmacSHA256 
	 * @return
	 */
	public static String getHmacSign(String content, String charset,String key,String hamaAlgorithm){
		byte[] result = null;  
        try {  
            //根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称    
            SecretKeySpec signinKey = new SecretKeySpec(key.getBytes(), hamaAlgorithm);  
            //生成一个指定 Mac 算法 的 Mac 对象    
            Mac mac = Mac.getInstance(hamaAlgorithm);  
            //用给定密钥初始化 Mac 对象    
            mac.init(signinKey);  
            //完成 Mac 操作     
            byte[] rawHmac;
			rawHmac = mac.doFinal(content.getBytes(charset));
            result = Base64.encodeBase64(rawHmac);  
  
        } catch (NoSuchAlgorithmException e) {  
            System.err.println(e.getMessage());  
        } catch (InvalidKeyException e) {  
            System.err.println(e.getMessage());  
        }  catch (IllegalStateException | UnsupportedEncodingException e) {
        	System.err.println(e.getMessage());
		} 
        if (null != result) {  
            return new String(result);  
        } else {  
            return null;  
        }  
    }  
	
	public static void main(String[] args) {
		String hmacSign = getHmacSign("testjoiaj", "UTF-8", "gail", "HmacMD5");
		String hmacSign2 = getHmacSign("testjoiaj", "UTF-8", "gail", "HmacSHA1");
		String hmacSign3 = getHmacSign("testjoiaj", "UTF-8", "gail", "HmacSHA256");
		System.out.println(hmacSign);
		System.out.println(hmacSign2);
		System.out.println(hmacSign3);
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值