The HMAC of the Java encryption and decryption technology series

Source: Internet
Author: User
Tags base64 hmac random seed



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:
    • You can use the appropriate hash function without modification, and the hash function behaves well in software, and The source code is open and generic.
    • You can maintain the performance of the hash function without causing it to degrade.
    • can make the encryption strength analysis based on reasonable message authentication mechanism of the underlying hash function hypothesis easy to understand.
    • When you find or need a hash function that is faster or more secure, you can easily implement the underlying the substitution of the hash function.

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 represent blocks of data.the word length. (The split block of the hash function mentioned above is the length B = 64), and L is used to denote the hash function.The output data is word length (L = + in MD5, L = 20 in SHA-1). The length of the authentication key can be less than or equal to the numberany positive integer value of the block word length. If the key length used in the application is larger than B, the hash is used firstThe function H acts on it and then uses the L-length string of 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

Calculate the HMAC of ' text ':
    • H (K xor Opad, H (k xor ipad, text))

Calculation Steps
  • Add a zero after the key K to create a string that Zichang to B. (for example, if the word length of k is b=60 bytes, then K will add 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. Length greater thanL's key is also possible, but the extra length does not significantly increase the security strength of the function.
The key must be randomly selected (or using a powerful random seed-based pseudo-random generation method), and the cyclethe update of the sex. The current attack does not indicate the frequency of a valid replacement key, because those attacks actuallycannot be done. However, a periodic update of a key is a fundamental problem in dealing with the potential pitfalls of functions and keyssecurity, and can reduce the harm caused by the leaking key.

Code implementation
<span style= "Font-family:comic Sans ms;font-size:12px;" >package Com.sica.hmac;import Com.google.common.base.strings;import Sun.misc.base64decoder;import Sun.misc.base64encoder;import Javax.crypto.keygenerator;import Javax.crypto.mac;import Javax.crypto.SecretKey; Import Javax.crypto.spec.secretkeyspec;import java.security.nosuchalgorithmexception;/** * Created by Xiang.li on 2015 /2/27. */public class HMAC {/** * defines encryption method * Mac algorithm can choose the following algorithms * <pre> * HmacMD5 * HmacSHA1 * Hmacsha    HmacSHA384 * HmacSHA512 * </pre> * * Private final static String Key_mac = "HmacMD5"; /** * Global Array */private final static string[] hexdigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8    "," 9 "," a "," B "," C "," D "," E "," F "}; /** * constructor */public HMAC () {}/** * BASE64 encryption * @param key required to encrypt byte array * @return String * @t Hrows Exception */public static String encryptBase64 (byte[] key) throwS Exception {return (new Base64encoder ()). Encodebuffer (key); }/** * BASE64 decryption * @param key The string to decrypt * @return byte array * @throws Exception */public static Byte    [] decryptBase64 (String key) throws Exception {return (new Base64decoder ()). Decodebuffer (key);        }/** * Initializes the HMAC key * @return */public static String 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 ();    } return str; }/** * HMAC encryption * @param data requires an encrypted byte array * @param key key * @return byte array */public static byte[] en        Crypthmac (byte[] data, String key) {Secretkey secretkey;        byte[] bytes = NULL; try {            Secretkey = new Secretkeyspec (DecryptBase64 (key), KEY_MAC);            Mac Mac = Mac.getinstance (Secretkey.getalgorithm ());            Mac.init (Secretkey);        bytes = mac.dofinal (data);        } catch (Exception e) {e.printstacktrace ();    } return bytes; }/** * HMAC encryption * @param data requires an encrypted string * @param key key * @return String */public static string ENCR        Ypthmac (string data, string key) {if (Strings.isnullorempty (data)) {return null;        } byte[] bytes = Encrypthmac (Data.getbytes (), key);    Return bytearraytohexstring (bytes); }/** * Converts a byte into a 16-binary string * @param B-byte array * @return String */private static string Bytetohexstring (by        Te b) {int ret = b;        System.out.println ("ret =" + ret);        if (Ret < 0) {ret + = 256;        } int m = RET/16;        int n = ret% 16;    return hexdigits[m] + hexdigits[n]; }    /**     *Convert byte array to hexadecimal String * @param bytes byte array * @return Hexadecimal string * * * private static string bytearraytohexstring (byte[] B        ytes) {StringBuffer sb = new StringBuffer ();        for (int i = 0; i < bytes.length; i++) {Sb.append (bytetohexstring (bytes[i]));    } return sb.tostring (); }/** * Test method * @param args */public static void main (string[] args) throws Exception {String ke        y = Hmac.init ();        SYSTEM.OUT.PRINTLN ("Mac key: \ n" + key);        String Word = "123";    System.out.println (Encrypthmac (Word, key)); }}</span>


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.

The HMAC of the Java encryption and decryption technology series

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.