Hi, 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.
Java Mac ( javax.crypto.Mac ) generates a message authentication code (MAC) from binary data. MAC is a message digest encrypted with a secret key. Only if you have a secret key, you can verify the authenticity of the MAC.
Before using the Mac class, you must create an instance of Mac. Creating an instance of a Mac class is done using the getInstance () method. Here is an example of creating a Mac instance:
Mac mac = Mac.getInstance("HmacSHA256");
The string parameter passed to the getInstance () method 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 as a parameter the secret key that the instance will use. 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); mac.init(key);
The init () method accepts an instance of Key . This example uses SecretKeySpec , which implements the Key interface.
Using the MAC instance (after initialization), you can begin to calculate the MAC data. To calculate the MAC value, you call the update () or doFinal () method. If you only have one data block 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 to calculate the MAC, for example, if you read the file block by block, then you must call the update () method for each block and end up with the doFinal () call on the last block. Here is an example:
byte[] data = "abcdefghijklmnopqrstuvxyz".getBytes("UTF-8"); byte[] data2 = "0123456789".getBytes("UTF-8"); mac.update(data); mac.update(data2); byte[] macBytes = mac.doFinal();
Source: https://habr.com/ru/post/445228/
All Articles