目录

Generating an HMAC (ArkTS)

The hash-based message authentication code (HMAC) algorithm employs a designated digest algorithm and takes a shared key and message as inputs to generate a fixed-length message authentication code (MAC) to check the integrity of packets. The HMAC adds key input on the basis of the message digest algorithm to ensure information correctness.

How to Develop

During the HMAC operation, you can pass in all the data at a time or pass in data by segment. The same data will produce the same result no matter how the data is passed. Use the appropriate method based on the data size.

The following provides examples of HMAC operations with different data passing methods.

[h2]Generating an HMAC by Passing In Full Data

  1. Call cryptoFramework.createMac with the MD algorithm SHA256 to create a Mac instance.

  2. Call cryptoFramework.createSymKeyGenerator and SymKeyGenerator.convertKey to generate a symmetric key (SymKey) using HMAC.

    For details, see Converting Binary Data into a Symmetric Key.

  3. Call Mac.init to initialize the Mac instance using the shared symmetric key (SymKey).

  4. Call Mac.update to pass in the data. The amount of data to be passed in by a single Mac.update() call is not limited.

  5. Call Mac.doFinal to generate a MAC.

  6. Call Mac.getMacLength to obtain the length of the MAC, in bytes.

[h2]Generating an HMAC by Passing In Data by Segment

  1. Call cryptoFramework.createMac with the MD algorithm SHA256 to create a Mac instance.

  2. Call cryptoFramework.createSymKeyGenerator and SymKeyGenerator.convertKey to generate a symmetric key (SymKey) using HMAC.

    For details, see Converting Binary Data into a Symmetric Key.

  3. Call Mac.init to initialize the Mac instance using the shared symmetric key (SymKey).

  4. Call Mac.update multiple times to pass in 20 bytes each time.

  5. Call Mac.doFinal to generate a MAC.

  6. Call Mac.getMacLength to obtain the length of the MAC, in bytes.

[h2]HMAC (Passing HmacSpec as a Parameter)

  1. Call cryptoFramework.createMac with the MAC algorithm set to HMAC and MD algorithm set to SHA256 to create a Mac instance.

  2. Call cryptoFramework.createSymKeyGenerator and SymKeyGenerator.convertKey to generate a symmetric key (SymKey) using HMAC.

    For details, see Converting Binary Data into a Symmetric Key.

  3. Call Mac.init to initialize the Mac instance using the shared symmetric key (SymKey).

  4. Call Mac.update to pass in the data. The amount of data to be passed in by a single Mac.update() call is not limited.

  5. Call Mac.doFinal to generate a MAC.

  6. Call Mac.getMacLength to obtain the length of the MAC, in bytes.