crypto

Generate Message Authentication Code (MAC)

With this example we are going to demonstrate how to generate a Message Authentication Code (MAC). We are using the Mac class that provides the functionality of a “Message Authentication Code” (MAC) algorithm. In short, to generate a Message Authentication Code you should:

  • Create a new KeyGenerator for the HmacMD5 algorithm.
  • Generate a SecretKey, using generateKey() API method of KeyGenerator.
  • Create a Mac object.
  • Initialize the MAC with the above key, using init(Key key) API method of Mac.
  • Create a new String message and get its byte array.
  • Use doFinal(byte[] input) API method of Mac to process the given array of bytes and finish the MAC operation.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;

public class GenerateMessageAuthenticationCode {
	
	public static void main(String[] args) {
		
		try {
			
			// get a key generator for the HMAC-MD5 keyed-hashing algorithm
		    KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
		    
		    // generate a key from the generator
		    SecretKey key = keyGen.generateKey();
	
  
		    // create a MAC and initialize with the above key
		    Mac mac = Mac.getInstance(key.getAlgorithm());
		    mac.init(key);

		    String message = "This is a confidential message";
		    
		    // get the string as UTF-8 bytes
		    byte[] b = message.getBytes("UTF-8");
		    
		    // create a digest from the byte array
		    byte[] digest = mac.doFinal(b);
	
  
		}
		catch (NoSuchAlgorithmException e) {
			System.out.println("No Such Algorithm:" + e.getMessage());
			return;
		}
		catch (UnsupportedEncodingException e) {
			System.out.println("Unsupported Encoding:" + e.getMessage());
			return;
		}
		catch (InvalidKeyException e) {
			System.out.println("Invalid Key:" + e.getMessage());
			return;
		}
		
	}

}

 
This was an example of how to generate a Message Authentication Code (MAC) in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button