歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java對PHP服務器hmac_sha1簽名認證方法的匹配實現

Java對PHP服務器hmac_sha1簽名認證方法的匹配實現

日期:2017/3/1 10:11:58   编辑:Linux編程

如果你的API服務安全認證協議中要求使用hmac_sha1方法對信息進行編碼,

而你的服務是由PHP實現的,客戶端是由JAVA實現的,那麼為了對簽名正確比對,就需要在兩者之間建立能匹配的編碼方式.

PHP側如下:

  1. define('ID','123456');
  2. define('KEY','k123456');
  3. $strToSign = "test_string";
  4. $utf8Str = mb_convert_encoding($strToSign, "UTF-8");
  5. $hmac_sha1_str = base64_encode(hash_hmac("sha1", $utf8Str, KEY));
  6. $signature = urlencode($hmac_sha1_str);
  7. print_r($signature);
JAVA側需要注意如下幾點:

1. hmac_sha1編碼結果需要轉換成hex格式

2. java中base64的實現和php不一致,其中java並不會在字符串末尾填補=號以把字節數補充為8的整數

3. hmac_sha1並非sha1, hmac_sha1是需要共享密鑰的

參考實現如下:

  1. import java.io.UnsupportedEncodingException;
  2. import javax.crypto.Mac;
  3. import javax.crypto.spec.SecretKeySpec;
  4. import org.apache.wicket.util.crypt.Base64UrlSafe;
  5. public class test {
  6. public static void main(String[] args) {
  7. String key = "f85b8b30f73eb2bf5d8063a9224b5e90";
  8. String toHash = "GET"+"\n"+"Thu, 09 Aug 2012 13:33:46 +0000"+"\n"+"/ApiChannel/Report.m";
  9. //String toHashUtf8 = URLEncoder.encode(toHash, "UTF-8");
  10. String res = hmac_sha1(toHash, key);
  11. //System.out.print(res+"\n");
  12. String signature;
  13. try {
  14. signature = new String(Base64UrlSafe.encodeBase64(res.getBytes()),"UTF-8");
  15. signature = appendEqualSign(signature);
  16. System.out.print(signature);
  17. } catch (UnsupportedEncodingException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. public static String hmac_sha1(String value, String key) {
  22. try {
  23. // Get an hmac_sha1 key from the raw key bytes
  24. byte[] keyBytes = key.getBytes();
  25. SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
  26. // Get an hmac_sha1 Mac instance and initialize with the signing key
  27. Mac mac = Mac.getInstance("HmacSHA1");
  28. mac.init(signingKey);
  29. // Compute the hmac on input data bytes
  30. byte[] rawHmac = mac.doFinal(value.getBytes());
  31. // Convert raw bytes to Hex
  32. String hexBytes = byte2hex(rawHmac);
  33. return hexBytes;
  34. } catch (Exception e) {
  35. throw new RuntimeException(e);
  36. }
  37. }
  38. private static String byte2hex(final byte[] b){
  39. String hs="";
  40. String stmp="";
  41. for (int n=0; n<b.length; n++){
  42. stmp=(java.lang.Integer.toHexString(b[n] & 0xFF));
  43. if (stmp.length()==1) hs=hs+"0"+stmp;
  44. else hs=hs+stmp;
  45. }
  46. return hs;
  47. }
  48. private static String appendEqualSign(String s){
  49. int len = s.length();
  50. int appendNum = 8 - (int)(len/8);
  51. for (int n=0; n<appendNum; n++){
  52. s += "%3D";
  53. }
  54. return s;
  55. }
  56. }
Copyright © Linux教程網 All Rights Reserved