1# HMAC (ArkTS)
2
3
4A Hash-based Message Authentication Code (HMAC) is a specific type of message authentication code (MAC) involving a cryptographic has function and a secret cryptographic key. For details about the scenarios and supported algorithm specifications, see [HMAC Overview and Algorithm Specifications](huks-hmac-overview.md).
5
6
7
8## How to Develop
9
10**Key Generation**
11
121. Set the key alias.
13
142. Initialize the key property set.
15
163. Use [generateKeyItem](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksgeneratekeyitem9) to generate a key. For details about the HMAC specifications supported, see [huks-key-generation-overview.md#supported-algorithms).
17
18You can also import a key. For details about the supported algorithms, see [Supported Algorithms](huks-key-import-overview.md#supported-algorithms).
19
20**HMAC Generation**
21
221. Obtain the key alias.
23
242. Obtains the data to be calculated.
25
263. Use [initSession](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksinitsession9) to initialize a key session. The session handle is returned after the initialization.
27
284. Use [finishSession](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksfinishsession9) to obtain the hashed data.
29
30
31```ts
32/*
33 * Perform HMAC calculation using promise-based APIs.
34 */
35import { huks } from '@kit.UniversalKeystoreKit';
36
37let HmackeyAlias = 'test_HMAC';
38let handle: number;
39let plainText = '123456';
40let hashData: Uint8Array;
41
42function StringToUint8Array(str: String) {
43  let arr: number[] = new Array();
44  for (let i = 0, j = str.length; i < j; ++i) {
45    arr.push(str.charCodeAt(i));
46  }
47  return new Uint8Array(arr);
48}
49
50function Uint8ArrayToString(fileData: Uint8Array) {
51  let dataString = '';
52  for (let i = 0; i < fileData.length; i++) {
53    dataString += String.fromCharCode(fileData[i]);
54  }
55  return dataString;
56}
57
58function GetHMACProperties() {
59  const properties: Array<huks.HuksParam> = [{
60    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
61    value: huks.HuksKeyAlg.HUKS_ALG_HMAC
62  }, {
63    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
64    value: huks.HuksKeySize.HUKS_AES_KEY_SIZE_256
65  }, {
66    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
67    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_MAC
68  }, {
69    tag: huks.HuksTag.HUKS_TAG_DIGEST,
70    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA384,
71  }];
72  return properties;
73}
74
75async function GenerateHMACKey() {
76  /*
77  * Simulate the key generation scenario.
78  * 1. Set the key alias.
79  */
80  /*
81  * 2. Obtain the parameters for key generation.
82  */
83  let genProperties = GetHMACProperties();
84  let options: huks.HuksOptions = {
85    properties: genProperties
86  }
87  /*
88  * 3. Call generateKeyItem to generate a key.
89  */
90  await huks.generateKeyItem(HmackeyAlias, options)
91    .then((data) => {
92      console.info(`promise: generate HMAC Key success`);
93    }).catch((error: Error) => {
94      console.error(`promise: generate HMAC Key failed, ${JSON.stringify(error)}`);
95    })
96}
97
98async function HMACData() {
99  /*
100  * Simulate the HMAC scenario.
101  * 1. Obtain the key alias.
102  */
103  /*
104  * 2. Obtain the data to be hashed.
105  */
106  /*
107  * 3. Obtain HMAC algorithm parameter settings.
108  */
109  let hmacProperties = GetHMACProperties();
110  let options: huks.HuksOptions = {
111    properties: hmacProperties,
112    inData: StringToUint8Array(plainText)
113  }
114  /*
115  * 4. Call initSession to obtain a session handle.
116  */
117  await huks.initSession(HmackeyAlias, options)
118    .then((data) => {
119      handle = data.handle;
120    }).catch((error: Error) => {
121      console.error(`promise: init EncryptData failed, ${JSON.stringify(error)}`);
122    })
123  /*
124  * 5. Call finishSession to obtain the HMAC result.
125  */
126  await huks.finishSession(handle, options)
127    .then((data) => {
128      console.info(`promise: HMAC data success, data is ` + Uint8ArrayToString(data.outData as Uint8Array));
129      hashData = data.outData as Uint8Array;
130    }).catch((error: Error) => {
131      console.error(`promise: HMAC data failed, ${JSON.stringify(error)}`);
132    })
133}
134```
135