Use of HMAC
The HMAC algorithm is mainly used for authentication, as follows:
1. The client issues
a login request 2. The server returns a random value, which is stored in the session record
3. The client uses the random value as the key, the user password for the HMAC operation, and submits it to the server
4. The server reads the user password in the database, uses the key to do the same as the client HMAC operation, and then compares with the result which the user sends, if consistent, then the user identity is legal.
What is the advantage of doing so? If we are in the process of login, the hacker intercepted the data we sent, he can only get the result of the HMAC encryption, because do not know the key, it is impossible to obtain the user password, thus ensuring security. Types of HMAC
Algorithm kind Summary length
HmacMD5 128
HmacSHA1 160
HmacSHA256 256 HmacSHA384 384
HmacSHA512 512
Use of HMAC
1. As I saw earlier, if you want to use the HMAC algorithm, then we need to generate a key, how does this key be generated. Just fill it out casually. A key generator Keygenerator is used in the JDK to help us generate the key, as shown below
public static byte[] Getsecretkey () throws Exception {keygenerator
keygenerator = Keygenerator.getinstance (" HmacMD5 "); Can fill in hmacsha1,hmacsha256 and other
secretkey key = Keygenerator.generatekey ();
byte[] keybytes = key.getencoded ();
return keybytes;
}
2. Now that we've got the key, we're going to start the Message digest algorithm, and before that, because the key we generated was returned in a byte array, we need to revert it to Secretkey, as follows
public static String Encrypthmac (byte[] key, byte[] data throws Exception {secretkey
secretkey = new Secretkeyspec (k EY, "HmacMD5");
Mac Mac = mac.getinstance ("HmacMD5");
Mac.init (Secretkey);
byte[] Resultbytes = mac.dofinal (data);
String resultstring = bytetohexstring (resultbytes);
return resultstring;
}
If you want to use other algorithms, you can fill in the HmacMD5 of all the fields you want to use the algorithm, such as HmacSHA1, HmacSHA256, and so on.
The following HelloWorld execution algorithm view results
1efd5e8d4d0c20f68bdc732fd7a79677