MACs

A message authentication code (MAC) is basically a keyed message digest. Like a message digest, a MAC takes an arbitrary amount of input data and creates a short digest value. Unlike a message digest, a MAC uses a key to create the digest value. This makes it useful for protecting the integrity of data that is sent over an insecure network. The javax.crypto.Mac class encapsulates a MAC.

Setting Up

To create a Mac , use one of its getInstance() methods:

public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException

This method returns a new Mac for the given algorithm.

public static final Mac getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException

This method returns a new Mac for the given algorithm using the supplied provider.

Once you have obtained the Mac, you need to initialize it with a key. You can also use algorithm-specific initialization information, if you wish.

public final void init(Key key) throws InvalidKeyException

Use this method to initialize the Macwith the supplied key. An exception is thrown if the key cannot be used.

public final void init(Key key, AlgorithmParameterSpec params) throws InvalidKeyException, InvalidAlgorithmParameterException

This method initializes the Mac with the supplied key and algorithm-specific parameters.

Feeding

A Mac has several update() methods for adding data. These are just like the update() methods in MessageDigest:

public final void update(byte input) throws IllegalStateException ...

Get Java Cryptography now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.