Java encryption and decryption research-MAC algorithm family __ algorithm

Source: Internet
Author: User
Tags generator

Come from:http://blog.csdn.net/lonelyroamer/article/details/7630594


I. Overview

The MAC algorithm combines the advantages of the MD5 and Sha algorithms and joins the key support, which is a more secure message digest algorithm.

MAC (Message authentication code, messaging authentication Code algorithm) is a hash function algorithm with key, which is compatible with the characteristics of MD and SHA algorithm, and adds a key on this basis. On the day, we often call the Mac HMAC (Keyed-hash message authentication Code).

The MAC algorithm mainly sets up the MD and SHA two series of Message digest algorithms. The MD Series algorithm has HmacMD2, HmacMD4, HmacMD5 Three kinds of algorithms, the SHA Series algorithm has HmacSHA1, HmacSHA224, HmacSHA256, hmacsha384.hmacsha512 five kinds of algorithms.

Digest values obtained by MAC algorithms can also be represented by hexadecimal encoding, whose summary value is the same length as the summary value of the participating implementation. For example, the HMACSHA1 algorithm obtains the summary length is the SHA1 algorithm obtains the summary length, is 160 bits binary code, converts the hexadecimal code to 40 bits.


II. Implementation and application

1, Sun's implementation and application

In Java6, Mac-series algorithms need to be supported by Mac classes. The JAVA6 provides only four algorithms for HmacMD5, HmacSHA1, HmacSHA256, HmacSHA384, and HmacSHA512.

Mac algorithm is a message digest algorithm with a key, so the realization is divided into two steps:

1), Build key

2), Executive Message Digest

[Java] View Plain copy print? package com.tao.test;      import java.security.nosuchalgorithmexception;       import javax.crypto.keygenerator;   import javax.crypto.mac;   import javax.crypto.secretkey;   import javax.crypto.spec.secretkeyspec;   Import  javax.xml.bind.annotation.adapters.HexBinaryAdapter;     /**   *  Mac algorithm tools    *  for HmacMD5, HmacSHA1, HmacSHA256, HmacSHA384, HmacSHA512 the application of the steps are identical. Look at the following code    */   class maccoder {       /**       *  Generate HMACMD5 Digest algorithm key        */        public static byte[] inithmacmd5key ()  throws  nosuchalgorithmexception {           //  Initialize the HMACMD5 digest algorithm key generator    &NBsp;       keygenerator generator = keygenerator.getinstance ("HmacMD5");           //  generate key             secretkey secretkey = generator.generatekey ();           //  get key             byte[] key = secretkey.getencoded ();            return key;       }           /**       * HMACMD5 Digest algorithm        *   for a given generation of different keys, the resulting digest message will be different, so in practical applications, to save our key        */        PUBLIC STATIC STRING ENCODEHMACMD5 (Byte[] data, byte[] key)   Throws exception {           //  restore keys             secretkey secretkey = new secretkeyspec (key,  "HmacMD5") ;           //  instantiation mac            mac mac = mac.getinstance (Secretkey.getalgorithm ());           //initialization mac            mac.init (Secretkey);           //Executive Message Digest            byte[] digest = mac.dofinal (data);           return new hexbinaryadapter (). Marshal (Digest);// Hex string        }                      /**       *  generate HmacSHA1 Digest algorithm key         */       public static byte[]  Inithmacshakey ()  throws NoSuchAlgorithmException {            //  Initialization HmacMD5 Digest algorithm key generator             Keygenerator generator = keygenerator.getinstance ("HmacSHA1");            //  Generate key             Secretkey secretkey = generator.generatekey ();            //  get key            byte[] key =  secretkey.getencoded ();           return key;        }          /**       * HMACSHA1 Digest algorithm        *  for a given generation of different keys, the resulting digest message will be different, so in practical applications, to save our key         */       public static string encodehmacsha (byte[] data ,  byte[] key)  throws Exception {            //  Restore key            secretkey secretkey  = new secretkeyspec (key,  "HmacSHA1");            //  instantiation of mac           mac mac =  mac.getinstance (Secretkey.getalgorithm ());           // Initialize mac           mac.init (secretkey);            //Executive Message Digest            byte[] digest  = mac.dofinal (data);           return new  Hexbinaryadapter (). Marshal (Digest);//hexadecimal string        }                              /**       *  generate HmacSHA256 Digest algorithm key         */       public static byte[] inithmacsha256key ()   throws nosuchalgorithmexception {           //   Initialization HmacMD5 digest algorithm key generator            KeyGenerator  Generator = keygenerator.getinstance ("HmacSHA256");            //  Generate Key            SecretKey secretKey =  Generator.generatekey ();           //  get key            byte[] key = secretkey.getencoded ();            return key;       }           /**       * HMACSHA1 Digest algorithm        *  for a given generated different key, the summary message will be different, so in practical applications, to save our key         */       public static string encodehmacsha256 (byte[)  data, byte[] key)  throws Exception {            //  Restore key            SecretKey  Secretkey = new secrEtkeyspec (key,  "HmacSHA256");           //  instantiation mac            mac mac = mac.getinstance ( Secretkey.getalgorithm ());           //initialization mac           mac.init (secretkey);            //Executive Message Digest            byte[] digest  = mac.dofinal (data);           return new  Hexbinaryadapter (). Marshal (Digest);//hexadecimal string        }                         /**       *  Generate HmacSHA256 Digest algorithm key        */       pUblic static byte[] inithmacsha384key ()  throws NoSuchAlgorithmException {            //  Initialization HmacMD5 digest algorithm key generator             keygenerator generator = keygenerator.getinstance (" HmacSHA384 ");           //  generate key             secretkey secretkey = generator.generatekey ();           //  get key             byte[] key = secretkey.getencoded ();            return key;       }           /**       * HMACSHA1 Digest algorithm        *   for a given generation of different keys, the resulting digest message willDifferent, so in practical applications, to save our key        */       public  static string encodehmacsha384 (Byte[] data, byte[] key)  throws Exception  {           //  restore key             secretkey secretkey = new secretkeyspec (key,  " HmacSHA384 ");           //  instantiation mac            mac mac = mac.getinstance (SecretKey.getAlgorithm ());            //Initialization mac            mac.init (secretkey);           //Execution Message Digest            byte[] digest = mac.dofinal (data);      &NBSp;     return new hexbinaryadapter (). Marshal (Digest);//hexadecimal string         }                         /**       *  generating key for HMACSHA256 Digest algorithm        */       public static byte[]  Inithmacsha512key ()  throws NoSuchAlgorithmException {            //  Initialization HmacMD5 Digest algorithm key generator             Keygenerator generator = keygenerator.getinstance ("HmacSHA512");            //  Generate key             Secretkey secretkey = generator.generatekey ();            //  Get key            byte[] key =  secretkey.getencoded ();           return key;        }          /**        * HMACSHA1 Digest algorithm        *  for a given generation of different keys, the resulting digest message will be different, so in practical applications, To save our key        */       public static  string encodehmacsha512 (Byte[] data, byte[] key)  throws Exception {            //  restore key             secretkey secretkey = new secretkeyspec (key,  "HmacSHA512");            //  instantiation mac            Mac mac = mac.getinstance (Secretkey.getalgorithm ());           / /Initialization of mac           mac.init (secretkey);            //Executive Message Digest             Byte[] digest = mac.dofinal (data);            Return new hexbinaryadapter (). Marshal (Digest);//hexadecimal string           }      public class mactest {        Public static void main (String[] args)  throws Exception {            String testString =  "ASDASD";                       byte[]  KeyHmacMD5=maccoder.inithmacmd5key ();           system.out.println ( MACCODER.ENCODEHMACMD5 (Teststring.getbytes (), keyHmacMD5));                       byte[] keyhmacsha1= Maccoder.inithmacshakey ();           system.out.println ( Maccoder.encodehmacsha (Teststring.getbytes (), keyHmacSHA1));                       byte[] keyhmacsha256= Maccoder.inithmacsha256key ();           system.out.println ( maccoder.encodehmacsha256 (Teststring.getbytes (), keyHmacSHA256));                       byte[] keyhmacsha384= Maccoder.inithmacsha384key ();     &Nbsp;     system.out.println (maccoder.encodehmacsha384) (TestString.getBytes (), keyHmacSHA384));                       byte[] keyhmacsha512=maccoder.inithmacsha512key ();            system.out.println (maccoder.encodehmacsha512) (TestString.getBytes (), keyHmacSHA512);       }  }  

Package com.tao.test;

Import java.security.NoSuchAlgorithmException;
Import Javax.crypto.KeyGenerator;
Import Javax.crypto.Mac;
Import Javax.crypto.SecretKey;
Import Javax.crypto.spec.SecretKeySpec;

Import Javax.xml.bind.annotation.adapters.HexBinaryAdapter; /** * Mac Algorithm Tool class * for HmacMD5, HmacSHA1, HmacSHA256, HmacSHA384, HmacSHA512 application procedures are identical. Specifically look at the following code/class Maccoder {/** * Generate HMACMD5 Digest algorithm key/public static byte[] Inithmacmd5key () throws Nosuchalgorithm
		Exception {//Initialization HmacMD5 Digest algorithm key generator Keygenerator generator = keygenerator.getinstance ("HmacMD5");
		Generate key Secretkey Secretkey = Generator.generatekey ();
		Get key byte[] key = secretkey.getencoded ();
	Return key;  /** * HMACMD5 Digest algorithm * For a given generated different keys, the resulting digest message will be different, so in practical applications, to save our key/public static String encodeHmacMD5 (byte[] data,
		Byte[] key) throws Exception {//restore key Secretkey Secretkey = new Secretkeyspec (Key, "HmacMD5");
		Instantiate Mac Mac = Mac.getinstance (Secretkey.getalgorithm ()); Initialize Mac MAC.INIT (Secretkey);
		Execution Message digest byte[] Digest = mac.dofinal (data); return new Hexbinaryadapter (). Marshal (Digest);//Convert to hexadecimal string}/** * Generate HMACSHA1 Digest algorithm key/public static byte[] in Ithmacshakey () throws NoSuchAlgorithmException {//Initialization HmacMD5 Digest algorithm's key generator Keygenerator generator = Keygenerator.getinst
		ance ("HmacSHA1");
		Generate key Secretkey Secretkey = Generator.generatekey ();
		Get key byte[] key = secretkey.getencoded ();
	Return key; /** * HmacSHA1 Digest algorithm * For a given generated different keys, the resulting digest message will be different, so in practical applications, to save our key/public static String Encodehmacsha (byte[] Data
		, byte[] key) throws Exception {//restore key Secretkey Secretkey = new Secretkeyspec (Key, "HmacSHA1");
		Instantiate Mac Mac = Mac.getinstance (Secretkey.getalgorithm ());
		Initialize Mac Mac.init (Secretkey);
		Execution Message digest byte[] Digest = mac.dofinal (data); return new Hexbinaryadapter (). Marshal (Digest);//Convert to hexadecimal string}/** * Generate HMACSHA256 Digest algorithm key/public static byte[ ] Inithmacsha256key () throws Nosuchalgorithmexception {///Initialize key generator for HmacMD5 digest algorithm Keygenerator generator = keygenerator.getinstance ("HmacSHA256");
		Generate key Secretkey Secretkey = Generator.generatekey ();
		Get key byte[] key = secretkey.getencoded ();
	Return key; /** * HmacSHA1 Digest algorithm * For a given generated different keys, the resulting digest message will be different, so in practical applications, to save our key/public static String encodeHmacSHA256 (byte[) d
		ATA, byte[] key throws Exception {//restore keys Secretkey Secretkey = new Secretkeyspec (Key, "HmacSHA256");
		Instantiate Mac Mac = Mac.getinstance (Secretkey.getalgorithm ());
		Initialize Mac Mac.init (Secretkey);
		Execution Message digest byte[] Digest = mac.dofinal (data); return new Hexbinaryadapter (). Marshal (Digest);//Convert to hexadecimal string}/** * Generate HmacSHA256 Digest algorithm
Related Article

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.