使用JAVA實現PHP中hash_hmac 函數

來源:互聯網
上載者:User
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();// }// }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.