HMAC (Keyed-Hashing for Message Authentication), MAC (Message Authentication Code, Message authentication code algorithm (HMAC) is the hash function algorithm containing the key, compatible with the characteristics of MD and SHA algorithms, and on this basis with the key, so MAC algorithm is often called “HMAC” algorithm.

MAC

Before we start, let’s talk about the MAC algorithm. On modern networks, identity authentication is a frequently used function. During identity authentication, there are many ways to ensure user information security. Message Authentication Code (MAC) is a common method.

Message authentication code is a technique for authenticating messages and confirming their integrity. By using the shared key between sender and receiver, it is possible to identify the presence of masquerade and tampering.

MAC is calculated using the MAC algorithm, key, and information to be encrypted.

Compared with the hash algorithm (message digest), message digest can only guarantee the integrity of the message, that is, the message digest B is generated by the message A. The MAC algorithm can ensure the correctness of the message, that is, the message is sent by message A rather than message C.

In contrast to the public-private key system, because the key of a MAC is the same at the sender and receiver, both the sender and receiver can generate a MAC, and the public-private key system increases non-repudiation by separating the public and private keys.

MAC can be implemented in many ways. The most common MAC algorithm is the Hash algorithm, such as HMAC algorithm. There is also a block cipher based implementation, such as OMAC, CBC-MAC and PMAC.

HMAC

HMAC algorithm is firstly based on information summarization algorithm. At present, MD and SHA are mainly integrated. The ALGORITHMS of MD series include HmacMD2, HmacMD4 and HmacMD5. The SHA algorithm includes HmacSHA1, HmacSHA224, HmacSHA256, HmacSHA384, and HmacSHA512.

HMAC requires a key in addition to the information digest algorithm. The HMAC key can be of any length. If the length of the key exceeds the length of the information packet of the digest algorithm, the digest algorithm is first used to calculate the digest of the key as the new key. It is generally not recommended to use a key that is too short, because the length of the key is related to the strength of the security. Usually, the length of the selected key is not less than the length of the information summary output by the selected algorithm.

Comparison of MD algorithms

algorithm Abstract Length (bit) To implement party
HmacMD5 128 JDK, Bouncy Castle, Commons Codec
HmacSHA1 160 JDK, Bouncy Castle, Commons Codec
HmacSHA224 224 JDK, Bouncy Castle, Commons Codec
HmacSHA256 256 JDK, Bouncy Castle, Commons Codec
HmacSHA384 384 JDK, Bouncy Castle, Commons Codec
HmacSHA512 512 JDK, Bouncy Castle, Commons Codec

HMAC algorithm implementation

JDK HMAC algorithm implementation

JDK about HMAC algorithm implementation:

// Obtain the HMAC Key

public static byte[] getHmacKey(String algorithm) {

    try {

        // create a key generator

        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);

        // 2

        SecretKey secretKey = keyGenerator.generateKey();

        // 3

        byte[] key = secretKey.getEncoded();

        // return the key

        return key;

    } catch (Exception e) {

        throw new RuntimeException(e);

    }

}



/ / the HMAC encryption

public static String encryptHmac(byte[] data, byte[] key, String algorithm) {

    try {

        // 1

        SecretKey secretKey = new SecretKeySpec(key, algorithm);

        // create a MAC object

        Mac mac = Mac.getInstance(algorithm);

        // 3. Set the key

        mac.init(secretKey);

        // 4. Data encryption

        byte[] bytes = mac.doFinal(data);

        // generate data

        String rs = encodeHex(bytes);

        // return hexadecimal encrypted data

        return rs;

    } catch (Exception e) {

        throw new RuntimeException(e);

    }

}

Copy the code
Bouncy Castle’s HMAC algorithm implementation

Bouncy Castle’s implementation of the HMAC algorithm:

// Obtain the HMAC Key

public static byte[] getHmacKey(String algorithm) {

    try {

        // create a key generator

        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);

        // 2

        SecretKey secretKey = keyGenerator.generateKey();

        // 3

        byte[] key = secretKey.getEncoded();

  // return the key

        return key;

    } catch (Exception e) {

        throw new RuntimeException(e);

    }

}



/ / the HMAC encryption

public static String encryptHmac(byte[] data, byte[] key, String algorithm) {

    HMac hmac = generateHmacByAlgorithm(algorithm);

    KeyParameter keyParameter = new KeyParameter(key);

    hmac.init(keyParameter);

    hmac.update(data, 0, data.length);

    byte[] rsData = new byte[hmac.getMacSize()];

    hmac.doFinal(rsData, 0);



    return Hex.toHexString(rsData);

}

Copy the code
Commons Codec HMAC algorithm implementation

Commons Codec provides HMAC algorithm implementation:

// Obtain the HMAC Key

public static byte[] getHmacKey(String algorithm) {

    try {

        // create a key generator

        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);

        // 2

        SecretKey secretKey = keyGenerator.generateKey();

        // 3

        byte[] key = secretKey.getEncoded();

  // return the key

        return key;

    } catch (Exception e) {

        throw new RuntimeException(e);

    }

}



/ / the HMAC encryption

public static String encryptHmac(byte[] data, byte[] key, String algorithm) {

    Mac mac = HmacUtils.getInitializedMac(HmacAlgorithms.HMAC_MD5, key);

    return Hex.encodeHexString(mac.doFinal(data));

}

Copy the code

For the full code visit: github.com/ForTheDevel…

Application of HMAC algorithm

1. Verify the validity of the peer user

A typical application of HMAC algorithm is Challenge/Response authentication. The authentication process is as follows:

(1) The client sends an authentication request to the server (suppose it is a browser GET request).

(2) After receiving this request, the server generates a random number and transmits it to the client through the network (this is a challenge).

(3) The client performs HMAC calculation on the random number received with its own key and returns a result to the server as authentication evidence (this is the response).

(4) At the same time, the server also uses the random number to perform HMAC calculation with the client key stored in the server database. If the calculation result of the server is the same as the response result returned by the client, the client is considered to be a legitimate user.

In this process, the random numbers sent by the server and the HMAC results returned by the client may be attacked, and these two values are meaningless to the hacker who intercepted them. The introduction of random values makes HMAC valid only in the current session, greatly enhancing security and practicability.

2. Send a message to (or receive a message from) another person

For example, you share a key K with the other party, and now you want to send a message to the other party. To ensure that the message is not tampered with (integrity), and to prove that the message is really sent by you (source authentication), send the original message and the key K calculated by HMAC. After receiving the message, the other party uses the key K in his hand and the original message to calculate the HMAC value. If it is consistent with the HMAC you sent, it can be considered that the message is neither tampered with nor faked.

The difference between ordinary hash algorithm and HMAC algorithm

The common hash algorithm uses hash to digest the data to be output. When receiving the data, it hashes the source data and compares the received data with the given hash value to see whether the received data is consistent with the calculated hash value.

Generally speaking, the transmitted data and hashes are provided by different channels, such as the MD5 or SHA hashes displayed on a web page, but the download link is from a mirror site, which does not affect the correctness of the file you downloaded.

If you want to send data and hash values (such as message authentication codes) through the same channel, you need to consider whether the data and hash values can be tampered with at the same time. If a third party modiates the data, then performs MD5 hash and sends the data to the recipient together, the recipient will not be aware of the tampering.

The HMAC algorithm can calculate with a key that both sender and receiver have, and a third party that does not have this key cannot calculate the correct hash value, thus preventing the source party from being tampered with.

conclusion

Currently, the HMAC algorithm is used in few scenarios. Usually, the encryption algorithm is directly used to ensure the correctness of the source party. However, HMAC can be used in certain scenarios. In addition, you are welcome to pay attention to our public number, reply [encryption and decryption] to get all the source code of this series.

Writing is not easy, if you like this article, please like and forward, your attention is our motivation to continue to move forward