1
0

KeyTools.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package com.zhpan.idea.utils;
  2. import java.security.MessageDigest;
  3. import java.security.NoSuchAlgorithmException;
  4. import java.security.SignatureException;
  5. import javax.crypto.Mac;
  6. import javax.crypto.spec.SecretKeySpec;
  7. /**
  8. * Created by zhpan on 2017/10/20.
  9. * Description:
  10. */
  11. public class KeyTools {
  12. private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
  13. private static final String TAG = "KeyTools";
  14. /**
  15. * 获取MD5加密的之后的hex字符串
  16. * @param info
  17. * @return
  18. */
  19. public static String getMD5(String info) {
  20. try {
  21. MessageDigest md5 = MessageDigest.getInstance("MD5");
  22. md5.update(info.getBytes());
  23. byte[] encryption = md5.digest();
  24. return DataConversionTools.bytesToHexString(encryption);
  25. } catch (NoSuchAlgorithmException e) {
  26. return "";
  27. }
  28. }
  29. /**
  30. * 获取HMAC-SHA1加密之后的hex字符串
  31. * @param data
  32. * @param key
  33. * @return
  34. * @throws SignatureException
  35. */
  36. public static String getHmacSHA1(String data, String key) throws SignatureException {
  37. try {
  38. // get an hmac_sha1 key from the raw key bytes
  39. SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(),
  40. HMAC_SHA1_ALGORITHM);
  41. // get an hmac_sha1 Mac instance and initialize with the signing key
  42. Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
  43. mac.init(signingKey);
  44. // compute the hmac on input data bytes
  45. byte[] rawHmac = mac.doFinal(data.getBytes());
  46. return DataConversionTools.bytesToHexString(rawHmac);
  47. } catch (Exception e) {
  48. throw new SignatureException("Failed to generate HMAC : "
  49. + e.getMessage());
  50. }
  51. }
  52. }