• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Non-anonymous Key Attestation (ArkTS)
2
3<!--Kit: Universal Keystore Kit-->
4<!--Subsystem: Security-->
5<!--Owner: @wutiantian-gitee-->
6<!--Designer: @HighLowWorld-->
7<!--Tester: @wxy1234564846-->
8<!--Adviser: @zengyawen-->
9
10The caller must have the [ohos.permission.ATTEST_KEY](../AccessToken/permissions-for-system-apps.md#ohospermissionattest_key) permission. You need to request the permission based on the APL of your permission. For details, see [Workflow for Using Permissions](../AccessToken/determine-application-mode.md).
11
12## How to Develop
13
141. Specify the key alias. For details about the naming rules, see [Key Generation Overview and Algorithm Specifications](huks-key-generation-overview.md).
15
162. Initializes a parameter set. The **properties** field in [HuksOptions](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksoptions) must contain [HUKS_TAG_ATTESTATION_CHALLENGE](../../reference/apis-universal-keystore-kit/js-apis-huks.md#hukstag). Optional parameters include [HUKS_TAG_ATTESTATION_ID_VERSION_INFO](../../reference/apis-universal-keystore-kit/js-apis-huks.md#hukstag) and [HUKS_TAG_ATTESTATION_ID_ALIAS](../../reference/apis-universal-keystore-kit/js-apis-huks.md#hukstag).
17
183. Generate an asymmetric key. For details, see [Key Generation](huks-key-generation-overview.md).
19
204. Use [attestKeyItem](../../reference/apis-universal-keystore-kit/js-apis-huks.md#huksattestkeyitem9) with the key alias and parameter set to perform key attestation.
21
22```ts
23/*
24 * Perform non-anonymous key attestation. This example uses promise-based APIs.
25 */
26import { huks } from '@kit.UniversalKeystoreKit';
27
28function StringToUint8Array(str: string) {
29  let arr: number[] = [];
30  for (let i = 0, j = str.length; i < j; ++i) {
31    arr.push(str.charCodeAt(i));
32  }
33  return new Uint8Array(arr);
34}
35
36/* 1. Set the key alias. */
37let keyAliasString = "key attest";
38let aliasString = keyAliasString;
39let aliasUint8 = StringToUint8Array(keyAliasString);
40let securityLevel = StringToUint8Array('sec_level');
41let challenge = StringToUint8Array('challenge_data');
42let versionInfo = StringToUint8Array('version_info');
43let attestCertChain: Array<string>;
44
45class throwObject {
46  isThrow: boolean = false;
47}
48
49/* Encapsulate the key parameter set. */
50let genKeyProperties: Array<huks.HuksParam> = [
51  {
52    tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
53    value: huks.HuksKeyAlg.HUKS_ALG_RSA
54  },
55  {
56    tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
57    value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
58  },
59  {
60    tag: huks.HuksTag.HUKS_TAG_PURPOSE,
61    value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
62  },
63  {
64    tag: huks.HuksTag.HUKS_TAG_DIGEST,
65    value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
66  },
67  {
68    tag: huks.HuksTag.HUKS_TAG_PADDING,
69    value: huks.HuksKeyPadding.HUKS_PADDING_PSS
70  },
71  {
72    tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
73    value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
74  },
75  {
76    tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
77    value: huks.HuksCipherMode.HUKS_MODE_ECB
78  }
79]
80let genOptions: huks.HuksOptions = {
81  properties: genKeyProperties
82};
83
84/* 2. Encapsulate the parameter set for key attestation. */
85let attestKeyproperties: Array<huks.HuksParam> = [
86  {
87    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO,
88    value: securityLevel
89  },
90  {
91    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_CHALLENGE,
92    value: challenge
93  },
94  {
95    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_VERSION_INFO,
96    value: versionInfo
97  },
98  {
99    tag: huks.HuksTag.HUKS_TAG_ATTESTATION_ID_ALIAS,
100    value: aliasUint8
101  }
102]
103let huksOptions: huks.HuksOptions = {
104  properties: attestKeyproperties
105};
106
107function generateKeyItem(keyAlias: string, huksOptions: huks.HuksOptions, throwObject: throwObject) {
108  return new Promise<void>((resolve, reject) => {
109    try {
110      huks.generateKeyItem(keyAlias, huksOptions, (error, data) => {
111        if (error) {
112          reject(error);
113        } else {
114          resolve(data);
115        }
116      });
117    } catch (error) {
118      throwObject.isThrow = true;
119      throw (error as Error);
120    }
121  });
122}
123
124/* 3. Generate a key. */
125async function publicGenKeyFunc(keyAlias: string, huksOptions: huks.HuksOptions) {
126  console.info(`enter promise generateKeyItem`);
127  let throwObject: throwObject = { isThrow: false };
128  try {
129    await generateKeyItem(keyAlias, huksOptions, throwObject)
130      .then((data) => {
131        console.info(`promise: generateKeyItem success, data = ${JSON.stringify(data)}`);
132      })
133      .catch((error: Error) => {
134        if (throwObject.isThrow) {
135          throw (error as Error);
136        } else {
137          console.error(`promise: generateKeyItem failed, ${JSON.stringify(error)}`);
138        }
139      });
140  } catch (error) {
141    console.error(`promise: generateKeyItem input arg invalid, ${JSON.stringify(error)}`);
142  }
143}
144
145/* 4. Attest the key. */
146function attestKeyItem(keyAlias: string, huksOptions: huks.HuksOptions, throwObject: throwObject) {
147  return new Promise<huks.HuksReturnResult>((resolve, reject) => {
148    try {
149      huks.attestKeyItem(keyAlias, huksOptions, (error, data) => {
150        if (error) {
151          reject(error);
152        } else {
153          resolve(data);
154        }
155      });
156    } catch (error) {
157      throwObject.isThrow = true;
158      throw (error as Error);
159    }
160  });
161}
162
163async function publicAttestKey(keyAlias: string, huksOptions: huks.HuksOptions) {
164  console.info(`enter promise attestKeyItem`);
165  let throwObject: throwObject = { isThrow: false };
166  try {
167    await attestKeyItem(keyAlias, huksOptions, throwObject)
168      .then((data) => {
169        console.info(`promise: attestKeyItem success, data = ${JSON.stringify(data)}`);
170        if (data !== null && data.certChains !== null) {
171          attestCertChain = data.certChains as string[];
172        }
173      })
174      .catch((error: Error) => {
175        if (throwObject.isThrow) {
176          throw (error as Error);
177        } else {
178          console.error(`promise: attestKeyItem failed, ${JSON.stringify(error)}`);
179        }
180      });
181  } catch (error) {
182    console.error(`promise: attestKeyItem input arg invalid, ${JSON.stringify(error)}`);
183  }
184}
185
186async function AttestKeyTest() {
187  await publicGenKeyFunc(aliasString, genOptions);
188  await publicAttestKey(aliasString, huksOptions);
189  console.info('attest certChain data: ' + attestCertChain)
190}
191```
192