The HMAC of the Java encryption and decryption technology series
- Order
- Background
- Body
- Code
- Conclusion
Order
The second one-way encryption algorithm--sha is briefly introduced in the previous article, and the Java code of SHA-1 is also given. Children's shoes with this need can be consulted. Today this article will introduce the third one-way encryption algorithm--hmac, in fact, this encryption algorithm is not so common, at least, before I write a series of blogs, I have not heard of it. Of course, this is not to say that HMAC is not famous, it must be my solitary fall know.
Background
This "uncommon" algorithm is introduced in one-way encryption algorithm, one is because "not seen", and the second is because it is one of the same one-way encryption algorithm, but also is based on the cryptographic key hash algorithm authentication protocol. Therefore, it is decided to introduce briefly.
Body
HMAC, all known as "hash Message authentication Code", Chinese name "Hash messages authentication Code", mainly using a hashing algorithm, a key and a message as input, generate a message digest as output. In general, the message identification code is used to verify transmission in two totala message between the units that enjoy a key. HMAC can be used in bundles with any iteration hash function. MD5 and SHA-1 are the hash functions. HMAC can also use a key that computes and confirms the authentication value of the message.
HMAC, hash Message identification code, is based on the cryptographic key hash algorithm authentication protocol. It is implemented by using public functions and keys to generate a fixed-length value as the authentication identifier, which is used to identify the integrity of the message. Use a key to generate a small, fixed-size block of data, the MAC, and add it to the message and transfer it. The receiver uses the key shared with the sender for authentication, and so on.
The main functions of this structure are:
And the source code is open and universal.
- You can maintain the performance of the hash function without causing it to degrade.
- It can make the encryption strength analysis of the message authentication mechanism based on the reasonable assumption of the underlying hash function easy to understand.
- The substitution of the underlying hash function can be easily implemented when a hash function is found or needs to be computationally fast or more secure.
Defining an HMAC requires an encryption with a hash function (denoted as H) and a key K. We assume that H isa hash function that encrypts a block of data with a basic iterative compression function. We use B to denote the length of the data block. (The partition data block of the hash function mentioned above is word B = 64), and L is used to denote the output data length of the hash function (L = SHA-1 in MD5, L = 20). The length of the authentication key can be any positive integer value that is less than or equal to the number of block word lengths. If the key length used in the application is larger than B, it is first used with the hash function H and then the L-length string with the H output as the actual key used in the HMAC. in general, the recommended minimum key K length is L-word lengths. (equal to the output data length of H).
We will define two fixed and different string Ipad,opad:(' i ', ' o ' denotes internal and external)
ipad = The byte 0x36 repeated B times
- Opad = The byte 0x5C repeated B times
h (k xor Opad, H (k xor ipad, text))
Calculation Steps
Bytes, b=60 bytes, then K is added with 44 0-byte 0x00)
- Make a different or operation of the B-word string from the previous step with the ipad
- Fills the data stream text into the result string in the second step
- Data flow generated with H acting on the third step
- The B-word string generated by the first step is opad or calculated with the
- The result of the fourth step is then filled into the result of the fifth step.
- The data stream generated by the H action in the sixth step outputs the final result
secret key
The key used for HMAC can be any length (the key that is longer than B will be processed first by H). But when the keywhen the length is less than L, the safety intensity of the function is reduced. A key with a length greater than L is also possible, but the extra length does not significantly increase the security strength of the function.
The key must be randomly selected (or use a robust random seed-based pseudo-random generation method) and be periodically updated. The current attack does not indicate the frequency of a valid replacement key, because those attacks are actually not working. However, periodic update of keys is a basic security measure against potential flaws in functions and keys , and can reduce the harm caused by leaking keys.
Code implementation
Importcom.google.common.base.Strings; ImportSun.misc.BASE64Decoder; ImportSun.misc.BASE64Encoder; ImportJavax.crypto.KeyGenerator; ImportJavax.crypto.Mac; ImportJavax.crypto.SecretKey; ImportJavax.crypto.spec.SecretKeySpec; Importjava.security.NoSuchAlgorithmException; /*** Created by Xiang.li on 2015/2/27. */ Public classHMAC {/*** Define encryption method * Mac algorithm can choose the following multiple algorithms * <pre> * HmacMD5 * HmacSHA1 * HmacSHA256 * Hmacsha 384 * HmacSHA512 * </pre>*/ Private Final StaticString Key_mac = "HmacMD5"; /*** Global Array*/ Private Final StaticString[] hexdigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "B", "C", "D", "E", "F" }; /*** Constructor Function*/ PublicHMAC () {}/*** BASE64 Encryption *@paramkey requires an encrypted byte array *@returnString *@throwsException*/ Public StaticString EncryptBase64 (byte[] key)throwsException {return(NewBase64encoder ()). Encodebuffer (key); } /*** BASE64 Decryption *@paramkey needs to decrypt the string *@returnbyte array *@throwsException*/ Public Static byte[] decryptBase64 (String key)throwsException {return(NewBase64decoder ()). Decodebuffer (key); } /*** Initialize HMAC key *@return */ Public StaticString init () {Secretkey key; String Str= ""; Try{keygenerator Generator=keygenerator.getinstance (KEY_MAC); Key=Generator.generatekey (); STR=encryptBase64 (key.getencoded ()); } Catch(nosuchalgorithmexception e) {e.printstacktrace (); } Catch(Exception e) {e.printstacktrace (); } returnstr; } /*** HMAC Encryption *@paramdata requires an encrypted byte array *@paramKey Key *@returnbyte array*/ Public Static byte[] Encrypthmac (byte[] data, String key) {Secretkey Secretkey; byte[] bytes =NULL; Try{Secretkey=NewSecretkeyspec (DecryptBase64 (key), KEY_MAC); Mac Mac=mac.getinstance (Secretkey.getalgorithm ()); Mac.init (Secretkey); Bytes=mac.dofinal (data); } Catch(Exception e) {e.printstacktrace (); } returnbytes; } /*** HMAC Encryption *@paramdata requires an encrypted string *@paramKey Key *@returnstring*/ Public Staticstring Encrypthmac (string data, string key) {if(Strings.isnullorempty (data)) {return NULL; } byte[] bytes =Encrypthmac (Data.getbytes (), key); returnbytearraytohexstring (bytes); } /*** Converts a byte into a string of 16 binary forms *@paramB-byte array *@returnstring*/ Private StaticString bytetohexstring (byteb) {intRET =b; //System.out.println ("ret =" + ret); if(Ret < 0) {ret+ = 256; } intm = ret/16; intn = ret% 16; returnHEXDIGITS[M] +Hexdigits[n]; } /*** Convert byte array to hexadecimal string *@parambytes byte array *@returnhexadecimal string*/ Private StaticString bytearraytohexstring (byte[] bytes) {StringBuffer SB=NewStringBuffer (); for(inti = 0; i < bytes.length; i++) {sb.append (bytetohexstring (bytes[i)); } returnsb.tostring (); } /*** Test method *@paramargs*/ Public Static voidMain (string[] args)throwsException {String key=Hmac.init (); System.out.println ("Mac key: \ n" +key); String Word= "123"; System.out.println (Encrypthmac (Word, key)); } }
Conclusion
After reading this article, HMAC you have learned a lot, and later encountered this noun, of course you can also say a Sanlai. However, in the application, perhaps under normal circumstances, if the security factors, I think, this irreversible encryption algorithm is good, because you need to provide an additional set of keys, and this set of keys for outsiders do not know, therefore, security is relatively reliable.
HMAC of the 4.Java encryption and decryption technology series