1# @ohos.security.asset (关键资产存储服务)(系统接口)
2
3关键资产存储服务提供了用户短敏感数据的安全存储及管理能力。其中,短敏感数据可以是密码类(账号/密码)、Token类(应用凭据)、其他关键明文(如银行卡号)等长度较短的用户敏感数据。
4
5> **说明:**
6>
7> - 本模块首批接口从API version 12 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8> - 当前页面仅包含本模块的系统接口,其他公开接口参见[ohos.security.asset (关键资产存储服务)](js-apis-asset.md)。
9
10## 导入模块
11
12```typescript
13import { asset } from '@kit.AssetStoreKit';
14```
15
16## asset.addAsUser
17
18addAsUser(userId: number, attributes: AssetMap): Promise\<void>
19
20在指定用户空间中新增一条关键资产,使用Promise方式异步返回结果。
21
22如果要设置[IS_PERSISTENT](js-apis-asset.md#tag)属性,需要申请ohos.permission.STORE_PERSISTENT_DATA权限。
23
24**需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
25
26**系统能力:** SystemCapability.Security.Asset
27
28| 参数名     | 类型     | 必填 | 说明                                                         |
29| ---------- | -------- | ---- | ------------------------------------------------------------ |
30| userId     | number                                | 是   | 用户ID。                                                           |
31| attributes | [AssetMap](js-apis-asset.md#assetmap) | 是   | 待新增关键资产的属性集合,包括关键资产明文、访问控制属性、自定义数据等。 |
32
33**返回值:**
34
35| 类型          | 说明                    |
36| ------------- | ----------------------- |
37| Promise\<void> | Promise对象,无返回值。 |
38
39**错误码:**
40
41以下错误码的详细介绍请参见[关键资产存储服务错误码](errorcode-asset.md)
42
43| 错误码ID | 错误信息                                                   |
44| -------- | ---------------------------------------------------------- |
45| 201      | The caller doesn't have the permission.                    |
46| 202      | Non-system applications use system APIs.                   |
47| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified. <br> 2. Incorrect parameter types. <br> 3. Parameter verification failed.           |
48| 24000001 | The ASSET service is unavailable.                          |
49| 24000003 | The asset already exists.                                  |
50| 24000005 | The screen lock status does not match.                         |
51| 24000006 | Insufficient memory.                                       |
52| 24000007 | The asset is corrupted.                                    |
53| 24000008 | The database operation failed.                          |
54| 24000009 | The cryptography operation failed.                      |
55| 24000010 | IPC failed.                                |
56| 24000011 | Calling the Bundle Manager service failed. |
57| 24000012 | Calling the OS Account service failed.     |
58| 24000013 | Calling the Access Token service failed.   |
59| 24000014 | The file operation failed.                           |
60| 24000015 | Getting the system time failed.            |
61
62**示例代码:**
63
64```typescript
65import { asset } from '@kit.AssetStoreKit';
66import { util } from '@kit.ArkTS';
67import { BusinessError } from '@kit.BasicServicesKit';
68
69function stringToArray(str: string): Uint8Array {
70  let textEncoder = new util.TextEncoder();
71  return textEncoder.encodeInto(str);
72}
73
74let userId: number = 100;
75let attr: asset.AssetMap = new Map();
76attr.set(asset.Tag.SECRET, stringToArray('demo_pwd'));
77attr.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
78attr.set(asset.Tag.ACCESSIBILITY, asset.Accessibility.DEVICE_FIRST_UNLOCKED);
79attr.set(asset.Tag.DATA_LABEL_NORMAL_1, stringToArray('demo_label'));
80try {
81  asset.addAsUser(userId, attr).then(() => {
82    console.info(`Asset added to user space successfully.`);
83  }).catch((err: BusinessError) => {
84    console.error(`Failed to add Asset to user space. Code is ${err.code}, message is ${err.message}`);
85  })
86} catch (error) {
87  let err = error as BusinessError;
88  console.error(`Failed to add Asset to user space. Code is ${err.code}, message is ${err.message}`);
89}
90```
91
92## asset.removeAsUser
93
94removeAsUser(userId: number, query: AssetMap): Promise\<void>
95
96从指定用户空间中删除符合条件的一条或多条关键资产,使用Promise方式异步返回结果。
97
98**需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
99
100**系统能力:** SystemCapability.Security.Asset
101
102| 参数名 | 类型     | 必填 | 说明                                                   |
103| ------ | -------- | ---- | ------------------------------------------------------ |
104| userId | number                                | 是   | 用户ID。                                                  |
105| query  | [AssetMap](js-apis-asset.md#assetmap) | 是   | 待删除关键资产的搜索条件,如别名、访问控制属性、自定义数据等。 |
106
107**返回值:**
108
109| 类型          | 说明                    |
110| ------------- | ----------------------- |
111| Promise\<void> | Promise对象,无返回值。 |
112
113**错误码:**
114
115以下错误码的详细介绍请参见[关键资产存储服务错误码](errorcode-asset.md)
116
117| 错误码ID | 错误信息                                                   |
118| -------- | ---------------------------------------------------------- |
119| 201      | The caller doesn't have the permission.                    |
120| 202      | Non-system applications use system APIs.                   |
121| 401      | Parameter error. Possible causes: <br> 1. Incorrect parameter types.  <br> 2. Parameter verification failed. |
122| 24000001 | The ASSET service is unavailable.                          |
123| 24000002 | The asset is not found.                        |
124| 24000006 | Insufficient memory.                                       |
125| 24000007 | The asset is corrupted.                                    |
126| 24000008 | The database operation failed.                          |
127| 24000010 | IPC failed.                                |
128| 24000011 | Calling the Bundle Manager service failed. |
129| 24000012 | Calling the OS Account service failed.     |
130| 24000013 | Calling the Access Token service failed.   |
131| 24000015 | Getting the system time failed.            |
132
133**示例代码:**
134
135```typescript
136import { asset } from '@kit.AssetStoreKit';
137import { util } from '@kit.ArkTS';
138import { BusinessError } from '@kit.BasicServicesKit';
139
140function stringToArray(str: string): Uint8Array {
141  let textEncoder = new util.TextEncoder();
142  return textEncoder.encodeInto(str);
143}
144
145let userId: number = 100;
146let query: asset.AssetMap = new Map();
147query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
148try {
149  asset.removeAsUser(userId, query).then(() => {
150    console.info(`Asset removed from user space successfully.`);
151  }).catch((err: BusinessError) => {
152    console.error(`Failed to remove Asset from user space. Code is ${err.code}, message is ${err.message}`);
153  });
154} catch (error) {
155  let err = error as BusinessError;
156  console.error(`Failed to remove Asset from user space. Code is ${err.code}, message is ${err.message}`);
157}
158```
159
160## asset.updateAsUser
161
162updateAsUser(userId: number, query: AssetMap, attributesToUpdate: AssetMap): Promise\<void>
163
164在指定用户空间中更新符合条件的一条关键资产,使用Promise方式异步返回结果。
165
166**需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
167
168**系统能力:** SystemCapability.Security.Asset
169
170| 参数名             | 类型     | 必填 | 说明                                                         |
171| ------------------ | -------- | ---- | ------------------------------------------------------------ |
172| userId             | number                                | 是   | 用户ID。                                                         |
173| query              | [AssetMap](js-apis-asset.md#assetmap) | 是   | 待更新关键资产的搜索条件,如关键资产别名、访问控制属性、自定义数据等。 |
174| attributesToUpdate | [AssetMap](js-apis-asset.md#assetmap) | 是   | 待更新关键资产的属性集合,如关键资产明文、自定义数据等。              |
175
176**返回值:**
177
178| 类型          | 说明                    |
179| ------------- | ----------------------- |
180| Promise\<void> | Promise对象,无返回值。 |
181
182**错误码:**
183
184以下错误码的详细介绍请参见[关键资产存储服务错误码](errorcode-asset.md)
185
186| 错误码ID | 错误信息                                                   |
187| -------- | ---------------------------------------------------------- |
188| 201      | The caller doesn't have the permission.                    |
189| 202      | Non-system applications use system APIs.                   |
190| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified. <br> 2. Incorrect parameter types. <br> 3. Parameter verification failed.           |
191| 24000001 | The ASSET service is unavailable.                          |
192| 24000002 | The asset is not found.                        |
193| 24000005 | The screen lock status does not match.                         |
194| 24000006 | Insufficient memory.                                       |
195| 24000007 | The asset is corrupted.                                    |
196| 24000008 | The database operation failed.                          |
197| 24000009 | The cryptography operation failed.                      |
198| 24000010 | IPC failed.                                |
199| 24000011 | Calling the Bundle Manager service failed. |
200| 24000012 | Calling the OS Account service failed.     |
201| 24000013 | Calling the Access Token service failed.   |
202| 24000015 | Getting the system time failed.            |
203
204**示例代码:**
205
206```typescript
207import { asset } from '@kit.AssetStoreKit';
208import { util } from '@kit.ArkTS';
209import { BusinessError } from '@kit.BasicServicesKit';
210
211function stringToArray(str: string): Uint8Array {
212  let textEncoder = new util.TextEncoder();
213  return textEncoder.encodeInto(str);
214}
215
216let userId: number = 100;
217let query: asset.AssetMap = new Map();
218query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
219let attrsToUpdate: asset.AssetMap = new Map();
220attrsToUpdate.set(asset.Tag.SECRET, stringToArray('demo_pwd_new'));
221try {
222  asset.updateAsUser(userId, query, attrsToUpdate).then(() => {
223    console.info(`Asset updated in user space successfully.`);
224  }).catch((err: BusinessError) => {
225    console.error(`Failed to update Asset in user space. Code is ${err.code}, message is ${err.message}`);
226  });
227} catch (error) {
228  let err = error as BusinessError;
229  console.error(`Failed to update Asset in user space. Code is ${err.code}, message is ${err.message}`);
230}
231```
232
233## asset.preQueryAsUser
234
235preQueryAsUser(userId: number, query: AssetMap): Promise\<Uint8Array>
236
237在指定用户空间中查询的预处理,用于需要用户认证的关键资产。在用户认证成功后,应当随后调用[asset.queryAsUser](#assetqueryasuser)、[asset.postQueryAsUser](#assetpostqueryasuser)。使用Promise方式异步返回结果。
238
239**需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
240
241**系统能力:** SystemCapability.Security.Asset
242
243| 参数名 | 类型     | 必填 | 说明                                                   |
244| ------ | -------- | ---- | ------------------------------------------------------ |
245| userId | number                                | 是   | 用户ID。                                            |
246| query  | [AssetMap](js-apis-asset.md#assetmap) | 是   | 关键资产的查询条件,如别名、访问控制属性、自定义数据等。 |
247
248**返回值:**
249
250| 类型                | 说明                                                  |
251| ------------------- | ----------------------------------------------------- |
252| Promise\<Uint8Array> | Promise对象,返回挑战值。<br>**说明:** 挑战值用于后续用户认证。 |
253
254**错误码:**
255
256以下错误码的详细介绍请参见[关键资产存储服务错误码](errorcode-asset.md)
257
258| 错误码ID | 错误信息                                                     |
259| -------- | ------------------------------------------------------------ |
260| 201      | The caller doesn't have the permission.                      |
261| 202      | Non-system applications use system APIs.                     |
262| 401      | Parameter error. Possible causes: <br> 1. Incorrect parameter types.  <br> 2. Parameter verification failed. |
263| 24000001 | The ASSET service is unavailable.                            |
264| 24000002 | The asset is not found.                          |
265| 24000005 | The screen lock status does not match.                           |
266| 24000006 | Insufficient memory.                                         |
267| 24000007 | The asset is corrupted.                                      |
268| 24000008 | The database operation failed.                            |
269| 24000009 | The cryptography operation failed.                        |
270| 24000010 | IPC failed.                                  |
271| 24000011 | Calling the Bundle Manager service failed.   |
272| 24000012 | Calling the OS Account service failed.       |
273| 24000013 | Calling the Access Token service failed.     |
274| 24000016 | The cache exceeds the limit.                                 |
275| 24000017 | The capability is not supported.                             |
276
277**示例代码:**
278
279```typescript
280import { asset } from '@kit.AssetStoreKit';
281import { util } from '@kit.ArkTS';
282import { BusinessError } from '@kit.BasicServicesKit';
283
284function stringToArray(str: string): Uint8Array {
285  let textEncoder = new util.TextEncoder();
286  return textEncoder.encodeInto(str);
287}
288
289let userId: number = 100;
290let query: asset.AssetMap = new Map();
291query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
292try {
293  asset.preQueryAsUser(userId, query).then((challenge: Uint8Array) => {
294    console.info(`Succeeded in pre-querying Asset from user space.`);
295  }).catch ((err: BusinessError) => {
296    console.error(`Failed to pre-query Asset from user space. Code is ${err.code}, message is ${err.message}`);
297  });
298} catch (error) {
299  let err = error as BusinessError;
300  console.error(`Failed to pre-query Asset from user space. Code is ${err.code}, message is ${err.message}`);
301}
302```
303
304## asset.queryAsUser
305
306queryAsUser(userId: number, query: AssetMap): Promise\<Array\<AssetMap>>
307
308在指定用户空间中查询一条或多条符合条件的关键资产。若查询需要用户认证的关键资产,则需要在本函数前调用[asset.preQueryAsUser](#assetprequeryasuser),在本函数后调用[asset.postQueryAsUser](#assetpostqueryasuser),开发步骤请参考[开发指导](../../security/AssetStoreKit/asset-js-query-auth.md)。使用Promise回调异步返回结果。
309
310**需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
311
312**系统能力:** SystemCapability.Security.Asset
313
314| 参数名   | 类型                            | 必填 | 说明                                                         |
315| -------- | ------------------------------- | ---- | ------------------------------------------------------------ |
316| userId   | number                                          | 是   | 用户ID。                                                  |
317| query    | [AssetMap](js-apis-asset.md#assetmap)           | 是   | 关键资产的查询条件,如别名、访问控制属性、自定义数据等。       |
318
319**返回值:**
320
321| 类型                     | 说明                                  |
322| ------------------------ | ------------------------------------- |
323| Promise\<Array\<AssetMap>> | Promise对象,返回查询结果列表。 |
324
325**错误码:**
326
327以下错误码的详细介绍请参见[关键资产存储服务错误码](errorcode-asset.md)
328
329| 错误码ID | 错误信息                                                   |
330| -------- | ---------------------------------------------------------- |
331| 201      | The caller doesn't have the permission.                    |
332| 202      | Non-system applications use system APIs.                   |
333| 401      | Parameter error. Possible causes: <br> 1. Incorrect parameter types.  <br> 2. Parameter verification failed. |
334| 24000001 | The ASSET service is unavailable.                          |
335| 24000002 | The asset is not found.                        |
336| 24000004 | Access denied.                             |
337| 24000005 | The screen lock status does not match.                         |
338| 24000006 | Insufficient memory.                                       |
339| 24000007 | The asset is corrupted.                                    |
340| 24000008 | The database operation failed.                          |
341| 24000009 | The cryptography operation failed.                      |
342| 24000010 | IPC failed.                                |
343| 24000011 | Calling the Bundle Manager service failed. |
344| 24000012 | Calling the OS Account service failed.     |
345| 24000013 | Calling the Access Token service failed.   |
346| 24000017 | The capability is not supported.                           |
347
348**示例代码:**
349
350```typescript
351import { asset } from '@kit.AssetStoreKit';
352import { util } from '@kit.ArkTS';
353import { BusinessError } from '@kit.BasicServicesKit';
354
355function stringToArray(str: string): Uint8Array {
356  let textEncoder = new util.TextEncoder();
357  return textEncoder.encodeInto(str);
358}
359
360let userId: number = 100;
361let query: asset.AssetMap = new Map();
362query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
363try {
364  asset.queryAsUser(userId, query).then((res: Array<asset.AssetMap>) => {
365    for (let i = 0; i < res.length; i++) {
366      // parse the attribute.
367      let accessibility: number = res[i].get(asset.Tag.ACCESSIBILITY) as number;
368    }
369    console.info(`Succeeded in querying Asset from user space.`);
370  }).catch ((err: BusinessError) => {
371    console.error(`Failed to query Asset from user space. Code is ${err.code}, message is ${err.message}`);
372  });
373} catch (error) {
374  let err = error as BusinessError;
375  console.error(`Failed to query Asset from user space. Code is ${err.code}, message is ${err.message}`);
376}
377```
378
379## asset.postQueryAsUser
380
381postQueryAsUser(userId: number, handle: AssetMap): Promise\<void>
382
383在指定用户空间中查询的后置处理,用于需要用户认证的关键资产。需与[asset.preQueryAsUser](#assetprequeryasuser)函数成对出现。使用Promise方式异步返回结果。
384
385**需要权限:** ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
386
387**系统能力:** SystemCapability.Security.Asset
388
389| 参数名 | 类型     | 必填 | 说明                                                         |
390| ------ | -------- | ---- | ------------------------------------------------------------ |
391| userId | number                                | 是   | 用户ID。                                                                     |
392| handle | [AssetMap](js-apis-asset.md#assetmap) | 是   | 待处理的查询句柄,当前包含[asset.preQueryAsUser](#assetprequeryasuser)执行成功返回的挑战值。 |
393
394**返回值:**
395
396| 类型          | 说明                    |
397| ------------- | ----------------------- |
398| Promise\<void> | Promise对象,无返回值。 |
399
400**错误码:**
401
402以下错误码的详细介绍请参见[关键资产存储服务错误码](errorcode-asset.md)
403
404| 错误码ID | 错误信息                                                   |
405| -------- | ---------------------------------------------------------- |
406| 201      | The caller doesn't have the permission.                    |
407| 202      | Non-system applications use system APIs.                   |
408| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified. <br> 2. Incorrect parameter types. <br> 3. Parameter verification failed.           |
409| 24000001 | The ASSET service is unavailable.                          |
410| 24000006 | Insufficient memory.                                       |
411| 24000010 | IPC failed.                                |
412| 24000011 | Calling the Bundle Manager service failed. |
413| 24000012 | Calling the OS Account service failed.     |
414| 24000013 | Calling the Access Token service failed.   |
415
416**示例代码:**
417
418```typescript
419import { asset } from '@kit.AssetStoreKit';
420import { BusinessError } from '@kit.BasicServicesKit';
421
422let userId: number = 100;
423let handle: asset.AssetMap = new Map();
424// 此处传入的new Uint8Array(32)仅作为示例,实际应传入asset.preQueryAsUser执行成功返回的挑战值
425handle.set(asset.Tag.AUTH_CHALLENGE, new Uint8Array(32));
426try {
427  asset.postQueryAsUser(userId, handle).then(() => {
428    console.info(`Succeeded in post-querying Asset from user space.`);
429  }).catch ((err: BusinessError) => {
430    console.error(`Failed to post-query Asset from user space. Code is ${err.code}, message is ${err.message}`);
431  });
432} catch (error) {
433  let err = error as BusinessError;
434  console.error(`Failed to post-query Asset from user space. Code is ${err.code}, message is ${err.message}`);
435}
436```