The HMAC (hash message authentication code) hashes the authorization code, which encrypts the message digest using a key based on the Message digest algorithm (for example, the Md5,sha Series algorithm). It is equivalent to a vest, inside can use MD5,SHA1, SHA256,SHA384,SHA512 and other message digest algorithms, based on the generated message digest, a number of encryption operations. So HMAC includes, hmacmd5,hmacsha1,hmacsha384, HMACSHA512 and other types. It is because the HMAC is only a vest, it has a lot of flexibility, the bottom of the messagedigest algorithm which is easy to use which, say which with which, disassembly convenient.
HMAC is also useful in practice, which is often used in this way:
(1) The client initiates a request to the server and accesses the login page. The server generates a key, stores the key in the session, and returns the key to the client.
(2) The client fills in the login form, clicks Submit, runs the HMAC algorithm, encrypts the user information according to the key after post to the server.
(3) The server reads the password in the database, uses the HMAC to encrypt the password and the key in session to generate the cipher ciphertext, and compares the cipher text with the user's submission.
In this process, the intruder can do is catch the server sent to the client's key and client-submitted ciphertext. Only the key without the password can not be encrypted, there is ciphertext can not crack the password. Also, the key is placed in the session, each landing is not the same, security is very high. When the server returns a key to the client , you can use Base64 to convert a byte[] type key into a string.
Here's how to encrypt and decrypt using HMAC in Java.
Importjava.security.InvalidKeyException;Importjava.security.NoSuchAlgorithmException;Importjava.util.Base64;ImportJavax.crypto.KeyGenerator;ImportJavax.crypto.Mac;ImportJavax.crypto.SecretKey;ImportJavax.crypto.spec.SecretKeySpec; Public classHAMC {/*** Define encryption Mode Mac algorithm can choose the following several algorithms * * <pre> * HmacMD5 * HmacSHA1 * HmacSHA256 * HmacSHA384 * HmacSHA512 * </pre> * *@throwsnosuchalgorithmexception *@throwsinvalidkeyexception*/ Public Static voidMain (string[] args)throwsnosuchalgorithmexception, invalidkeyexception {byte[] srcdata = "Weidiao haha". GetBytes (); FinalString algorithm = "HmacMD5"; Keygenerator Keygenerator=keygenerator.getinstance (algorithm); byte[] key =Keygenerator.generatekey (). getencoded (); Secretkey Secretkey=NewSecretkeyspec (key, algorithm); Mac Mac=mac.getinstance (Secretkey.getalgorithm ()); Mac.init (Secretkey); byte[] data =mac.dofinal (Srcdata); System.out.println ("Key:" +Base64.getencoder (). encodetostring (key)); System.out.println ("Ciphertext:" +Base64.getencoder (). encodetostring (data)); }}
HMAC Encrypted message Digest code