HMAC-SHA1 Signature

Last update:2022-03-01 18:00:57

Java Version Sample Code

  1. /**
  2. * HMAC-SHA1 encryption scheme<br>
  3. * @param content-content to be encrypted
  4. * @param secretKey-key
  5. * @return HMAC_SHA1 encrypted character string
  6. */
  7. publicstatic String HMACSHA1(String content, String secretKey) {
  8. try {
  9. byte[] secretKeyBytes = secretKey.getBytes();
  10. SecretKey secretKeyObj = new SecretKeySpec(secretKeyBytes, "HmacSHA1");
  11. Mac mac = Mac.getInstance("HmacSHA1");
  12. mac.init(secretKeyObj);
  13. byte[] text = content.getBytes("UTF-8");
  14. byte[] encryptContentBytes = mac.doFinal(text);
  15. // length of signature obtained via SHA1 algorithm, all are 160-digit binary codes, which are converted to hexadecimal code character strings for representation.
  16. String encryptContent = bytesToHexString(encryptContentBytes);
  17. return encryptContent;
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. }
  21. return content;
  22. }
  23. /**
  24. * form of expression of hexadecimal character string of byte array obtained<br>
  25. * Example: 0xff->'ff'
  26. * @param bytes byte array
  27. * @return string-form of expression of hexadecimal character string
  28. */
  29. privatestatic String bytesToHexString(byte[] bytes) {
  30. StringBuilder hexString = new StringBuilder("");
  31. for(byte ib : bytes) {
  32. char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  33. char[] ob = newchar[2];
  34. ob[0] = Digit[(ib >>> 4) & 0X0f];
  35. ob[1] = Digit[ib & 0X0F];
  36. hexString.append(ob);
  37. }
  38. return hexString.toString();
  39. }
Is the content of this document helpful to you?
Yes
I have suggestion
Submitted successfully! Thank you very much for your feedback, we will continue to strive to do better!