package com.trade.com796;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;/** * 1. hmac_sha1編碼結果需要轉換成hex格式 * * 2. java中base64的實現和php不一致,其中java並不會在字串末尾填補=號以把位元組數補充為8的整數 * * 3. hmac_sha1並非sha1, hmac_sha1是需要共用密鑰的 * * @author LEI * */public class HMACSHA1 {private static final String HMAC_SHA1 = "HmacSHA1";/** * 產生簽名資料_HmacSHA1加密 * * @param data * 待加密的資料 * @param key * 加密使用的key * @throws InvalidKeyException * @throws NoSuchAlgorithmException */public static String getSignature(String data, String key) throws Exception {byte[] keyBytes = key.getBytes();// 根據給定的位元組數組構造一個密鑰。SecretKeySpec signingKey = new SecretKeySpec(keyBytes, HMAC_SHA1);Mac mac = Mac.getInstance(HMAC_SHA1);mac.init(signingKey);byte[] rawHmac = mac.doFinal(data.getBytes());String hexBytes = byte2hex(rawHmac);return hexBytes;}private static String byte2hex(final byte[] b) {String hs = "";String stmp = "";for (int n = 0; n < b.length; n++) {// 以十六進位(基數 16)不帶正負號的整數形式返回一個整數參數的字串表示形式。stmp = (java.lang.Integer.toHexString(b[n] & 0xFF));if (stmp.length() == 1) {hs = hs + "0" + stmp;} else {hs = hs + stmp;}}return hs;}// /**// * @param args// */// public static void main(String[] args) {// try {// System.out.println(HMACSHA1.getSignature("abc", "abc"));// } catch (Exception e) {// e.printStackTrace();// }// }}