加簽:
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+"×tamp="+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; } }