HMAC-SHA1 Example

Last update:2023-12-27 17:29:30

Java example code for HMAC-SHA1

/**
 * HMAC-SHA1 encryption method<br>
 * @param content - content to be encrypted
 * @param secretKey - secret key
 * @return the string after HMAC_SHA1 encryption
 */
public static 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);
        //The signature length obtained by the SHA1 algorithm is all 160-bit binary code, converted to a hexadecimal encoded string
        String encryptContent = bytesToHexString(encryptContentBytes);
        return encryptContent;  
    } catch (Exception e) {
        e.printStackTrace();
    }
    return content;
}
/**
 * Get the hexadecimal string representation of a byte array<br>
 * For example: 0xff -&gt; 'ff'
 * @param bytes - byte array
 * @return string - hexadecimal string representation
 */
private static 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 = new char[2];
        ob[0] = Digit[(ib &gt;&gt;&gt; 4) &amp; 0X0f];
        ob[1] = Digit[ib &amp; 0X0F];
        hexString.append(ob);
    }
    return hexString.toString();
}

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!