HMAC-SHA1 Example

更新时间: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();
}

本篇文档内容对您是否有帮助?
有帮助
我要反馈
提交成功!非常感谢您的反馈,我们会继续努力做到更好!