歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android HMAC_SHA1 算法簡單實現

Android HMAC_SHA1 算法簡單實現

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

想簽名以下信息:
PUT /quotes/nelson HTTP/1.0
Content-Md5: c8fdb181845a4ca6b8fec737b3581d76
Content-Type: text/html
Date: Thu, 17 Nov 2005 18:49:58 GMT
X-OSS-Meta-Author: [email protected]
X-OSS-Magic: abracadabra
假如AccessID是: "44CF9590006BF252F707"
AccessKey 是 "OtxrzxIsfpFjA7SwPzILwy8Bw21TLhquhboDYROV",可用以下
方法簽名

簽名計算結果應該為”63mwfl zYIOG6k95yxbgMruQ6QI=”

  1. private String hmac_sha1(String key, String datas)
  2. {
  3. String reString = "";
  4. try
  5. {
  6. byte[] data = key.getBytes("UTF-8");
  7. //根據給定的字節數組構造一個密鑰,第二參數指定一個密鑰算法的名稱
  8. SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
  9. //生成一個指定 Mac 算法 的 Mac 對象
  10. Mac mac = Mac.getInstance("HmacSHA1");
  11. //用給定密鑰初始化 Mac 對象
  12. mac.init(secretKey);
  13. byte[] text = datas.getBytes("UTF-8");
  14. //完成 Mac 操作
  15. byte[] text1 = mac.doFinal(text);
  16. reString = Base64.encodeToString(text1, Base64.DEFAULT);
  17. } catch (Exception e)
  18. {
  19. // TODO: handle exception
  20. }
  21. return reString;
  22. }
Copyright © Linux教程網 All Rights Reserved