- Example Programs and crypttool
- Cryptographic Services and Providers
- Cryptographic Keys
- Encryption and Decryption
- Message Digest
- Message Authentication Code
- Digital Signature
- Key Agreement
- Summary of Cryptographic Operations
- Cryptography with crypttool
- Limited versus Unlimited Cryptography
- Performance of Cryptographic Operations
- Practical Applications
- Legal Issues with Cryptography
- Summary
- Further Reading
Message Authentication Code
Message Authentication Code or MAC is obtained by applying a secret key to the message digest so that only the holder of the secret key can compute the MAC from the digest and hence, the message. This method thwarts the threat posed by a malicious interceptor who could modify the message and replace the digest with the digest of the modified message, for the interceptor won't have access to the secret key. Of course, there has to be a secure way to share the secret key between the sender and the recipient for this to work.
J2SE includes class javax.crypto.Mac to compute MAC. This class is somewhat similar to the MessagDigest class, except for the following:
-
A Mac object must be initialized with a secret key.
-
There is method doFinal() in place of digest().
Another difference between classes for MAC and message digest is that there are no MacInputStream and MacOutputStream classes.
The example program to illustrate MAC computation is similar to the one for Message Digest.
Listing 3-8. Computing Message Authentication Code (MAC)
// File: src\jsbook\ch3\ComputeMAC.java import javax.crypto.Mac; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.io.FileInputStream; public class ComputeMAC { public static void main(String[] unused) throws Exception{ String datafile = "ComputeDigest.java"; KeyGenerator kg = KeyGenerator.getInstance("DES"); kg.init(56); // 56 is the keysize. Fixed for DES SecretKey key = kg.generateKey(); Mac mac = Mac.getInstance("HmacSHA1"); mac.init(key); FileInputStream fis = new FileInputStream(datafile); byte[] dataBytes = new byte[1024]; int nread = fis.read(dataBytes); while (nread > 0) { mac.update(dataBytes, 0, nread); nread = fis.read(dataBytes); }; byte[] macbytes = mac.doFinal(); System.out.println("MAC(in hex):: " + Util.byteArray2Hex(macbytes)); } }
J2SE bundled providers support MAC algorithms HmacSHA1 and HmacMD5, corresponding to message digest algorithms SHA1 and MD5.