java http接口 加签,验签

加签:

		Random random = new Random(); 
		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;//5位随即数
		String nonce = rannum + "";
		String signature = HMACSHA1Util.getHmacSHA1(createtime+nonce, appKey);//appKey =公共密钥
        String smsUrl="http://"+sjyUrl+":"+sjyPort+"}/rest/sendMessage?appid="+appId+"&timestamp="+createtime+"&nonce="+nonce+"&signature="+signature;  
		
		
		

解签

		String timestamp = map != null ? (String)map.get("timestamp") : null;//验签参数(时间戳)
		String nonce = map != null ? (String)map.get("nonce") : null;//验签参数(随机数)
		String sjySignature = map != null ? (String)map.get("signature") : null;//验签参数(签名)
		String mySignature=HMACSHA1Util.getHmacSHA1(timestamp + nonce, appKey);

工具类

package com.paic.umap.ucm.common.utils;

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

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

import sun.misc.BASE64Encoder;

public class HMACSHA1Util {
	/**
	    * HMAC-SHA1签名
	    * 
	     * @param message
	    * @param key
	    * @return
	    */
	    public static String getHmacSHA1(String message, String key) {
	        String hmacSha1 = null;
	        try {
	            // url encode
	            message = URLEncoder.encode(message, "UTF-8");
	            // hmac-sha1加密
	            Mac mac = Mac.getInstance("HmacSHA1");
	            SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
	            mac.init(spec);
	            byte[] byteHMAC = mac.doFinal(message.getBytes());
	            // base64 encode
	            hmacSha1 = new BASE64Encoder().encode(byteHMAC);
	        } catch (NoSuchAlgorithmException e) {
	        } catch (InvalidKeyException e) {
	        } catch (UnsupportedEncodingException e) {
	        }
	        return hmacSha1;
	    }

}

  

转载于:https://www.cnblogs.com/hailei/p/5238776.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值