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