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