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();
}

이 문서의 내용이 도움이 되었습니까?
아니오
정상적으로 제출되었습니다.피드백을 주셔서 감사합니다.앞으로도 개선을 위해 노력하겠습니다.