Cryptography in Java. Mac class

Original author: Jakob Jenkov
  • Transfer

Hello, Habr! I present to you the translation of the fourth article "Java Mac" by Jakob Jenkov from a series of articles for beginners who want to learn the basics of cryptography in Java.

Table of contents:

  1. Java cryptography
  2. Java cipher
  3. Messagedigest
  4. Mac
  5. Signature
  6. Keypair
  7. Keygenerator
  8. KeyPairGenerator
  9. Keystore
  10. Keytool
  11. Certificate
  12. CertificateFactory
  13. CertPath

Message Authentication Code (MAC) (message authentication code or a message authentication code )

The Java Mac ( javax.crypto.Mac ) generates message authentication code (MAC) from binary data. MAC is a message digest encrypted with a secret key. Only with a secret key can you verify the authenticity of the MAC.


Before using the Mac class, you must create an instance of Mac. An instance of a Mac class is created using the getInstance () method . Here is an example of creating a Mac instance:

Mac mac = Mac.getInstance("HmacSHA256");

The string parameter passed to getInstance () contains the name of the algorithm used. In this case, the HmacSHA256 algorithm is used.


After creating the instance, the Mac should be initialized. A Mac instance is initialized by calling the init () method , passing in the secret key that will be used by the instance as a parameter. Here is an example of initializing a Mac instance:

byte[] keyBytes   = new byte[]{0,1,2,3,4,5,6,7,8 ,9,10,11,12,13,14,15};
String algorithm  = "RawBytes";
SecretKeySpec key = new SecretKeySpec(keyBytes, algorithm);

The init () method accepts an instance of Key . This example uses SecretKeySpec , which implements the Key interface.

MAC calculation

Using the MAC instance (after initialization), you can begin to calculate MAC data. To calculate the MAC value, you call the update () or doFinal () method . If you only have one block of data to calculate the MAC, you can directly call doFinal () , for example:

byte[] data  = "abcdefghijklmnopqrstuvxyz".getBytes("UTF-8");
byte[] macBytes = mac.doFinal(data);

If you have several data blocks for calculating MAC, for example, if you read the file block by block, then you must call the update () method for each block and end with doFinal () on the last block. Here is an example:

byte[] data  = "abcdefghijklmnopqrstuvxyz".getBytes("UTF-8");
byte[] data2 = "0123456789".getBytes("UTF-8");
byte[] macBytes = mac.doFinal();

Also popular now: