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;
	    }

}

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM