HMac
Introduction
Introduction to HMAC
HMAC, which stands for “Hash Message Authentication Code”, is a message digest generated using a hash algorithm with a key and a message as inputs. Typically, message authentication codes are used to verify messages transmitted between two entities that share a common key. HMAC can be used with any iterative hash function, such as MD5 and SHA-1. It can also use a key to calculate and verify the message authentication value.
Algorithm Types Supported by Hutool
Hmac Algorithms
Without introducing third-party libraries, the JDK supports a limited number of digest algorithms:
- HmacMD5
- HmacSHA1
- HmacSHA256
- HmacSHA384
- HmacSHA512
Usage
HMac
Taking HmacMD5 as an example:
String testStr = "test中文";
// If the key contains non-ASCII characters, consider encoding it.
byte[] key = "password".getBytes();
HMac mac = new HMac(HmacAlgorithm.HmacMD5, key);
// b977f4b13f93f549e06140971bded384
String macHex1 = mac.digestHex(testStr);
More HMac Algorithms
Similar to digest algorithms, more algorithms can be invoked by adding the Bouncy Castle
library, and the usage is similar:
HMac mac = new HMac("XXXX", key);