• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.security.asset (Asset Store Service) (System API)
2
3The asset store service (ASSET) provides secure storage and management of sensitive data less than 1024 bytes in size, including passwords, app tokens, and other critical data (such as bank card numbers).
4
5> **NOTE**
6>
7> - The initial APIs of this module are supported since API version 12. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8> - This topic describes only the system APIs provided by the module. For details about its public APIs, see [ohos.security.asset (Asset Store Service)](js-apis-asset.md).
9
10## Modules to Import
11
12```typescript
13import { asset } from '@kit.AssetStoreKit';
14```
15
16## asset.addAsUser
17
18addAsUser(userId: number, attributes: AssetMap): Promise\<void>
19
20Adds an asset to the specified user space. This API uses a promise to return the result.
21
22To set [IS_PERSISTENT](js-apis-asset.md#tag), the application must have the ohos.permission.STORE_PERSISTENT_DATA permission.
23
24**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
25
26**System capability**: SystemCapability.Security.Asset
27
28| Name    | Type    | Mandatory| Description                                                        |
29| ---------- | -------- | ---- | ------------------------------------------------------------ |
30| userId     | number                                | Yes  | User ID.                                                          |
31| attributes | [AssetMap](js-apis-asset.md#assetmap) | Yes  | Attributes of the asset to add, including the asset plaintext, access control attributes, and custom data.|
32
33**Return value**
34
35| Type         | Description                   |
36| ------------- | ----------------------- |
37| Promise\<void> | Promise that returns no value.|
38
39**Error codes**
40
41For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
42
43| ID| Error Message                                                  |
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**Example**
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
96Removes one or more assets from the specified user space. This API uses a promise to return the result.
97
98**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
99
100**System capability**: SystemCapability.Security.Asset
101
102| Name| Type    | Mandatory| Description                                                  |
103| ------ | -------- | ---- | ------------------------------------------------------ |
104| userId | number                                | Yes  | User ID.                                                 |
105| query  | [AssetMap](js-apis-asset.md#assetmap) | Yes  | Attributes of the asset to remove, such as the asset alias, access control attributes, and custom data.|
106
107**Return value**
108
109| Type         | Description                   |
110| ------------- | ----------------------- |
111| Promise\<void> | Promise that returns no value.|
112
113**Error codes**
114
115For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
116
117| ID| Error Message                                                  |
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**Example**
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
164Updates an asset in the specified user space. This API uses a promise to return the result.
165
166**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
167
168**System capability**: SystemCapability.Security.Asset
169
170| Name            | Type    | Mandatory| Description                                                        |
171| ------------------ | -------- | ---- | ------------------------------------------------------------ |
172| userId             | number                                | Yes  | User ID.                                                        |
173| query              | [AssetMap](js-apis-asset.md#assetmap) | Yes  | Attributes of the asset to update, such as the asset alias, access control attributes, and custom data.|
174| attributesToUpdate | [AssetMap](js-apis-asset.md#assetmap) | Yes  | New attributes of the asset, such as the asset plaintext and custom data.             |
175
176**Return value**
177
178| Type         | Description                   |
179| ------------- | ----------------------- |
180| Promise\<void> | Promise that returns no value.|
181
182**Error codes**
183
184For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
185
186| ID| Error Message                                                  |
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**Example**
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
237Performs preprocessing for the asset query in the specified user space. This API is used when user authentication is required for the access to the asset. After the user authentication is successful, call [asset.queryAsUser](#assetqueryasuser) and [asset.postQueryAsUser](#assetpostqueryasuser). This API uses a promise to return the result.
238
239**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
240
241**System capability**: SystemCapability.Security.Asset
242
243| Name| Type    | Mandatory| Description                                                  |
244| ------ | -------- | ---- | ------------------------------------------------------ |
245| userId | number                                | Yes  | User ID.                                           |
246| query  | [AssetMap](js-apis-asset.md#assetmap) | Yes  | Attributes of the asset, such as the asset aliases, access control attributes, and custom data.|
247
248**Return value**
249
250| Type               | Description                                                 |
251| ------------------- | ----------------------------------------------------- |
252| Promise\<Uint8Array> | Promise used to return a challenge value.<br>**NOTE**: The challenge value is used for subsequent user authentication.|
253
254**Error codes**
255
256For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
257
258| ID| Error Message                                                    |
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**Example**
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
308Queries one or more assets in the specified user space. If user authentication is required for the access to the asset, call [asset.preQueryAsUser](#assetprequeryasuser) before this API and call [asset.postQueryAsUser](#assetpostqueryasuser) after this API. For details about the development procedure, see [Querying an Asset with User Authentication](../../security/AssetStoreKit/asset-js-query-auth.md). This API uses a promise to return the result.
309
310**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
311
312**System capability**: SystemCapability.Security.Asset
313
314| Name  | Type                           | Mandatory| Description                                                        |
315| -------- | ------------------------------- | ---- | ------------------------------------------------------------ |
316| userId   | number                                          | Yes  | User ID.                                                 |
317| query    | [AssetMap](js-apis-asset.md#assetmap)           | Yes  | Attributes of the asset, such as the asset aliases, access control attributes, and custom data.      |
318
319**Return value**
320
321| Type                    | Description                                 |
322| ------------------------ | ------------------------------------- |
323| Promise\<Array\<AssetMap>> | Promise used to return the result obtained.|
324
325**Error codes**
326
327For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
328
329| ID| Error Message                                                  |
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**Example**
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
383Performs postprocessing for the asset query in the specified user space. This API is used when user authentication is required for the access to the asset. This API must be used with [asset.preQueryAsUser](#assetprequeryasuser) together. This API uses a promise to return the result.
384
385**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
386
387**System capability**: SystemCapability.Security.Asset
388
389| Name| Type    | Mandatory| Description                                                        |
390| ------ | -------- | ---- | ------------------------------------------------------------ |
391| userId | number                                | Yes  | User ID.                                                                    |
392| handle | [AssetMap](js-apis-asset.md#assetmap) | Yes  | Handle of the query operation, including the challenge value returned by [asset.preQueryAsUser](#assetprequeryasuser). |
393
394**Return value**
395
396| Type         | Description                   |
397| ------------- | ----------------------- |
398| Promise\<void> | Promise that returns no value.|
399
400**Error codes**
401
402For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
403
404| ID| Error Message                                                  |
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**Example**
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// The new Uint8Array(32) is only an example. Pass in the challenge value returned by 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```
437