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.