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
Macfor the given algorithm.- public static final Mac getInstance(String algorithm, String provider) throws NoSuchAlgorithmException, NoSuchProviderException
This method returns a new
Macfor 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
Macwith 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access