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**Parameters**
29
30| Name    | Type    | Mandatory| Description                                                        |
31| ---------- | -------- | ---- | ------------------------------------------------------------ |
32| userId     | number                                | Yes  | User ID.                                                          |
33| attributes | [AssetMap](js-apis-asset.md#assetmap) | Yes  | Attributes of the asset to add, including the asset plaintext, access control attributes, and custom data.|
34
35**Return value**
36
37| Type         | Description                   |
38| ------------- | ----------------------- |
39| Promise\<void> | Promise that returns no value.|
40
41**Error codes**
42
43For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
44
45| ID| Error Message                                                  |
46| -------- | ---------------------------------------------------------- |
47| 201      | The caller doesn't have the permission.                    |
48| 202      | Non-system applications use system APIs.                   |
49| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified. <br> 2. Incorrect parameter types. <br> 3. Parameter verification failed.           |
50| 24000001 | The ASSET service is unavailable.                          |
51| 24000003 | The asset already exists.                                  |
52| 24000005 | The screen lock status does not match.                         |
53| 24000006 | Insufficient memory.                                       |
54| 24000007 | The asset is corrupted.                                    |
55| 24000008 | The database operation failed.                          |
56| 24000009 | The cryptography operation failed.                      |
57| 24000010 | IPC failed.                                |
58| 24000011 | Calling the Bundle Manager service failed. |
59| 24000012 | Calling the OS Account service failed.     |
60| 24000013 | Calling the Access Token service failed.   |
61| 24000014 | The file operation failed.                           |
62| 24000015 | Getting the system time failed.            |
63
64**Example**
65
66```typescript
67import { asset } from '@kit.AssetStoreKit';
68import { util } from '@kit.ArkTS';
69import { BusinessError } from '@kit.BasicServicesKit';
70
71function stringToArray(str: string): Uint8Array {
72  let textEncoder = new util.TextEncoder();
73  return textEncoder.encodeInto(str);
74}
75
76let userId: number = 100;
77let attr: asset.AssetMap = new Map();
78attr.set(asset.Tag.SECRET, stringToArray('demo_pwd'));
79attr.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
80attr.set(asset.Tag.ACCESSIBILITY, asset.Accessibility.DEVICE_FIRST_UNLOCKED);
81attr.set(asset.Tag.DATA_LABEL_NORMAL_1, stringToArray('demo_label'));
82try {
83  asset.addAsUser(userId, attr).then(() => {
84    console.info(`Asset added to user space successfully.`);
85  }).catch((err: BusinessError) => {
86    console.error(`Failed to add Asset to user space. Code is ${err.code}, message is ${err.message}`);
87  })
88} catch (error) {
89  let err = error as BusinessError;
90  console.error(`Failed to add Asset to user space. Code is ${err.code}, message is ${err.message}`);
91}
92```
93
94## asset.removeAsUser
95
96removeAsUser(userId: number, query: AssetMap): Promise\<void>
97
98Removes one or more assets from the specified user space. This API uses a promise to return the result.
99
100**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
101
102**System capability**: SystemCapability.Security.Asset
103
104**Parameters**
105
106| Name| Type    | Mandatory| Description                                                  |
107| ------ | -------- | ---- | ------------------------------------------------------ |
108| userId | number                                | Yes  | User ID.                                                 |
109| 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.|
110
111**Return value**
112
113| Type         | Description                   |
114| ------------- | ----------------------- |
115| Promise\<void> | Promise that returns no value.|
116
117**Error codes**
118
119For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
120
121| ID| Error Message                                                  |
122| -------- | ---------------------------------------------------------- |
123| 201      | The caller doesn't have the permission.                    |
124| 202      | Non-system applications use system APIs.                   |
125| 401      | Parameter error. Possible causes: <br> 1. Incorrect parameter types.  <br> 2. Parameter verification failed. |
126| 24000001 | The ASSET service is unavailable.                          |
127| 24000002 | The asset is not found.                        |
128| 24000006 | Insufficient memory.                                       |
129| 24000007 | The asset is corrupted.                                    |
130| 24000008 | The database operation failed.                          |
131| 24000010 | IPC failed.                                |
132| 24000011 | Calling the Bundle Manager service failed. |
133| 24000012 | Calling the OS Account service failed.     |
134| 24000013 | Calling the Access Token service failed.   |
135| 24000015 | Getting the system time failed.            |
136
137**Example**
138
139```typescript
140import { asset } from '@kit.AssetStoreKit';
141import { util } from '@kit.ArkTS';
142import { BusinessError } from '@kit.BasicServicesKit';
143
144function stringToArray(str: string): Uint8Array {
145  let textEncoder = new util.TextEncoder();
146  return textEncoder.encodeInto(str);
147}
148
149let userId: number = 100;
150let query: asset.AssetMap = new Map();
151query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
152try {
153  asset.removeAsUser(userId, query).then(() => {
154    console.info(`Asset removed from user space successfully.`);
155  }).catch((err: BusinessError) => {
156    console.error(`Failed to remove Asset from user space. Code is ${err.code}, message is ${err.message}`);
157  });
158} catch (error) {
159  let err = error as BusinessError;
160  console.error(`Failed to remove Asset from user space. Code is ${err.code}, message is ${err.message}`);
161}
162```
163
164## asset.updateAsUser
165
166updateAsUser(userId: number, query: AssetMap, attributesToUpdate: AssetMap): Promise\<void>
167
168Updates an asset in the specified user space. This API uses a promise to return the result.
169
170**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
171
172**System capability**: SystemCapability.Security.Asset
173
174**Parameters**
175
176| Name            | Type    | Mandatory| Description                                                        |
177| ------------------ | -------- | ---- | ------------------------------------------------------------ |
178| userId             | number                                | Yes  | User ID.                                                        |
179| 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.|
180| attributesToUpdate | [AssetMap](js-apis-asset.md#assetmap) | Yes  | New attributes of the asset, such as the asset plaintext and custom data.             |
181
182**Return value**
183
184| Type         | Description                   |
185| ------------- | ----------------------- |
186| Promise\<void> | Promise that returns no value.|
187
188**Error codes**
189
190For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
191
192| ID| Error Message                                                  |
193| -------- | ---------------------------------------------------------- |
194| 201      | The caller doesn't have the permission.                    |
195| 202      | Non-system applications use system APIs.                   |
196| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified. <br> 2. Incorrect parameter types. <br> 3. Parameter verification failed.           |
197| 24000001 | The ASSET service is unavailable.                          |
198| 24000002 | The asset is not found.                        |
199| 24000005 | The screen lock status does not match.                         |
200| 24000006 | Insufficient memory.                                       |
201| 24000007 | The asset is corrupted.                                    |
202| 24000008 | The database operation failed.                          |
203| 24000009 | The cryptography operation failed.                      |
204| 24000010 | IPC failed.                                |
205| 24000011 | Calling the Bundle Manager service failed. |
206| 24000012 | Calling the OS Account service failed.     |
207| 24000013 | Calling the Access Token service failed.   |
208| 24000015 | Getting the system time failed.            |
209
210**Example**
211
212```typescript
213import { asset } from '@kit.AssetStoreKit';
214import { util } from '@kit.ArkTS';
215import { BusinessError } from '@kit.BasicServicesKit';
216
217function stringToArray(str: string): Uint8Array {
218  let textEncoder = new util.TextEncoder();
219  return textEncoder.encodeInto(str);
220}
221
222let userId: number = 100;
223let query: asset.AssetMap = new Map();
224query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
225let attrsToUpdate: asset.AssetMap = new Map();
226attrsToUpdate.set(asset.Tag.SECRET, stringToArray('demo_pwd_new'));
227try {
228  asset.updateAsUser(userId, query, attrsToUpdate).then(() => {
229    console.info(`Asset updated in user space successfully.`);
230  }).catch((err: BusinessError) => {
231    console.error(`Failed to update Asset in user space. Code is ${err.code}, message is ${err.message}`);
232  });
233} catch (error) {
234  let err = error as BusinessError;
235  console.error(`Failed to update Asset in user space. Code is ${err.code}, message is ${err.message}`);
236}
237```
238
239## asset.preQueryAsUser
240
241preQueryAsUser(userId: number, query: AssetMap): Promise\<Uint8Array>
242
243Performs preprocessing for the asset query in the specified user space. This API is used when user authentication is required for the access to an asset. After the user authentication is successful, call [asset.queryAsUser](#assetqueryasuser) and [asset.postQueryAsUser](#assetpostqueryasuser). This API uses a promise to return the result.
244
245**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
246
247**System capability**: SystemCapability.Security.Asset
248
249**Parameters**
250
251| Name| Type    | Mandatory| Description                                                  |
252| ------ | -------- | ---- | ------------------------------------------------------ |
253| userId | number                                | Yes  | User ID.                                           |
254| query  | [AssetMap](js-apis-asset.md#assetmap) | Yes  | Conditions for querying the asset, such as the asset aliases, access control attributes, and custom data.|
255
256**Return value**
257
258| Type               | Description                                                 |
259| ------------------- | ----------------------------------------------------- |
260| Promise\<Uint8Array> | Promise used to return a challenge value.<br>**NOTE**: The challenge value is used for subsequent user authentication.|
261
262**Error codes**
263
264For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
265
266| ID| Error Message                                                    |
267| -------- | ------------------------------------------------------------ |
268| 201      | The caller doesn't have the permission.                      |
269| 202      | Non-system applications use system APIs.                     |
270| 401      | Parameter error. Possible causes: <br> 1. Incorrect parameter types.  <br> 2. Parameter verification failed. |
271| 24000001 | The ASSET service is unavailable.                            |
272| 24000002 | The asset is not found.                          |
273| 24000005 | The screen lock status does not match.                           |
274| 24000006 | Insufficient memory.                                         |
275| 24000007 | The asset is corrupted.                                      |
276| 24000008 | The database operation failed.                            |
277| 24000009 | The cryptography operation failed.                        |
278| 24000010 | IPC failed.                                  |
279| 24000011 | Calling the Bundle Manager service failed.   |
280| 24000012 | Calling the OS Account service failed.       |
281| 24000013 | Calling the Access Token service failed.     |
282| 24000016 | The cache exceeds the limit.                                 |
283| 24000017 | The capability is not supported.                             |
284
285**Example**
286
287```typescript
288import { asset } from '@kit.AssetStoreKit';
289import { util } from '@kit.ArkTS';
290import { BusinessError } from '@kit.BasicServicesKit';
291
292function stringToArray(str: string): Uint8Array {
293  let textEncoder = new util.TextEncoder();
294  return textEncoder.encodeInto(str);
295}
296
297let userId: number = 100;
298let query: asset.AssetMap = new Map();
299query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
300try {
301  asset.preQueryAsUser(userId, query).then((challenge: Uint8Array) => {
302    console.info(`Succeeded in pre-querying Asset from user space.`);
303  }).catch ((err: BusinessError) => {
304    console.error(`Failed to pre-query Asset from user space. Code is ${err.code}, message is ${err.message}`);
305  });
306} catch (error) {
307  let err = error as BusinessError;
308  console.error(`Failed to pre-query Asset from user space. Code is ${err.code}, message is ${err.message}`);
309}
310```
311
312## asset.queryAsUser
313
314queryAsUser(userId: number, query: AssetMap): Promise\<Array\<AssetMap>>
315
316Queries 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.
317
318**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
319
320**System capability**: SystemCapability.Security.Asset
321
322**Parameters**
323
324| Name  | Type                           | Mandatory| Description                                                        |
325| -------- | ------------------------------- | ---- | ------------------------------------------------------------ |
326| userId   | number                                          | Yes  | User ID.                                                 |
327| query    | [AssetMap](js-apis-asset.md#assetmap)           | Yes  | Conditions for querying the asset, such as the asset aliases, access control attributes, and custom data.      |
328
329**Return value**
330
331| Type                    | Description                                 |
332| ------------------------ | ------------------------------------- |
333| Promise\<Array\<AssetMap>> | Promise used to return the result obtained.|
334
335**Error codes**
336
337For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
338
339| ID| Error Message                                                  |
340| -------- | ---------------------------------------------------------- |
341| 201      | The caller doesn't have the permission.                    |
342| 202      | Non-system applications use system APIs.                   |
343| 401      | Parameter error. Possible causes: <br> 1. Incorrect parameter types.  <br> 2. Parameter verification failed. |
344| 24000001 | The ASSET service is unavailable.                          |
345| 24000002 | The asset is not found.                        |
346| 24000004 | Access denied.                             |
347| 24000005 | The screen lock status does not match.                         |
348| 24000006 | Insufficient memory.                                       |
349| 24000007 | The asset is corrupted.                                    |
350| 24000008 | The database operation failed.                          |
351| 24000009 | The cryptography operation failed.                      |
352| 24000010 | IPC failed.                                |
353| 24000011 | Calling the Bundle Manager service failed. |
354| 24000012 | Calling the OS Account service failed.     |
355| 24000013 | Calling the Access Token service failed.   |
356| 24000017 | The capability is not supported.                           |
357
358**Example**
359
360```typescript
361import { asset } from '@kit.AssetStoreKit';
362import { util } from '@kit.ArkTS';
363import { BusinessError } from '@kit.BasicServicesKit';
364
365function stringToArray(str: string): Uint8Array {
366  let textEncoder = new util.TextEncoder();
367  return textEncoder.encodeInto(str);
368}
369
370let userId: number = 100;
371let query: asset.AssetMap = new Map();
372query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
373try {
374  asset.queryAsUser(userId, query).then((res: Array<asset.AssetMap>) => {
375    for (let i = 0; i < res.length; i++) {
376      // parse the attribute.
377      let accessibility: number = res[i].get(asset.Tag.ACCESSIBILITY) as number;
378    }
379    console.info(`Succeeded in querying Asset from user space.`);
380  }).catch ((err: BusinessError) => {
381    console.error(`Failed to query Asset from user space. Code is ${err.code}, message is ${err.message}`);
382  });
383} catch (error) {
384  let err = error as BusinessError;
385  console.error(`Failed to query Asset from user space. Code is ${err.code}, message is ${err.message}`);
386}
387```
388
389## asset.postQueryAsUser
390
391postQueryAsUser(userId: number, handle: AssetMap): Promise\<void>
392
393Performs 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.
394
395**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
396
397**System capability**: SystemCapability.Security.Asset
398
399**Parameters**
400
401| Name| Type    | Mandatory| Description                                                        |
402| ------ | -------- | ---- | ------------------------------------------------------------ |
403| userId | number                                | Yes  | User ID.                                                                    |
404| handle | [AssetMap](js-apis-asset.md#assetmap) | Yes  | Handle of the query operation, including the challenge value returned by [asset.preQueryAsUser](#assetprequeryasuser).|
405
406**Return value**
407
408| Type         | Description                   |
409| ------------- | ----------------------- |
410| Promise\<void> | Promise that returns no value.|
411
412**Error codes**
413
414For details about the error codes, see [Asset Store Service Error Codes](errorcode-asset.md).
415
416| ID| Error Message                                                  |
417| -------- | ---------------------------------------------------------- |
418| 201      | The caller doesn't have the permission.                    |
419| 202      | Non-system applications use system APIs.                   |
420| 401      | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified. <br> 2. Incorrect parameter types. <br> 3. Parameter verification failed.           |
421| 24000001 | The ASSET service is unavailable.                          |
422| 24000006 | Insufficient memory.                                       |
423| 24000010 | IPC failed.                                |
424| 24000011 | Calling the Bundle Manager service failed. |
425| 24000012 | Calling the OS Account service failed.     |
426| 24000013 | Calling the Access Token service failed.   |
427
428**Example**
429
430```typescript
431import { asset } from '@kit.AssetStoreKit';
432import { BusinessError } from '@kit.BasicServicesKit';
433
434let userId: number = 100;
435let handle: asset.AssetMap = new Map();
436// The new Uint8Array(32) is only an example. Pass in the challenge value returned by asset.preQueryAsUser.
437handle.set(asset.Tag.AUTH_CHALLENGE, new Uint8Array(32));
438try {
439  asset.postQueryAsUser(userId, handle).then(() => {
440    console.info(`Succeeded in post-querying Asset from user space.`);
441  }).catch ((err: BusinessError) => {
442    console.error(`Failed to post-query Asset from user space. Code is ${err.code}, message is ${err.message}`);
443  });
444} catch (error) {
445  let err = error as BusinessError;
446  console.error(`Failed to post-query Asset from user space. Code is ${err.code}, message is ${err.message}`);
447}
448```
449