Last update:2025-08-18 15:33:03
This example demonstrates how to implement the HMAC-SHA1 encryption algorithm using Java code.
Java Version Sample Code
/*** HMAC-SHA1 encryption scheme<br>* @param content-content to be encrypted* @param secretKey-key* @return HMAC_SHA1 encrypted character string*/publicstatic String HMACSHA1(String content, String secretKey) {try {byte[] secretKeyBytes = secretKey.getBytes();SecretKey secretKeyObj = new SecretKeySpec(secretKeyBytes, "HmacSHA1");Mac mac = Mac.getInstance("HmacSHA1");mac.init(secretKeyObj);byte[] text = content.getBytes("UTF-8");byte[] encryptContentBytes = mac.doFinal(text);// length of signature obtained via SHA1 algorithm, all are 160-digit binary codes, which are converted to hexadecimal code character strings for representation.String encryptContent = bytesToHexString(encryptContentBytes);return encryptContent;} catch (Exception e) {e.printStackTrace();}return content;}/*** form of expression of hexadecimal character string of byte array obtained<br>* Example: 0xff->'ff'* @param bytes byte array* @return string-form of expression of hexadecimal character string*/privatestatic String bytesToHexString(byte[] bytes) {StringBuilder hexString = new StringBuilder("");for(byte ib : bytes) {char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};char[] ob = newchar[2];ob[0] = Digit[(ib >>> 4) & 0X0f];ob[1] = Digit[ib & 0X0F];hexString.append(ob);}return hexString.toString();}