未验证 提交 15d48c92 编写于 作者: O openharmony_ci 提交者: Gitee

!3212 媒体、安全、dfx英文开发指南同步

Merge pull request !3212 from zengyawen/OpenHarmony-3.1-Release
......@@ -8,69 +8,21 @@ The event logging function helps applications log various information generated
JS application event logging APIs are provided by the **hiAppEvent** module.
**APIs for event logging:**
**APIs for Event Logging**
| API | Return Value | Description |
| ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ |
| write(string eventName, EventType type, object keyValues, AsyncCallback\<void> callback): void | void | Logs application events in asynchronous mode. This method uses an asynchronous callback to return the result. |
| write(string eventName, EventType type, object keyValues): Promise\<void> | Promise\<void> | Logs application events in asynchronous mode. This method uses a promise to return the result. |
- **eventName**: event name you customized. The event name can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter.
- **type**: event type enumerated by **EventType**.
| Type | Description |
| --------- | ----------------- |
| FAULT | Fault event |
| STATISTIC | Statistical event |
| SECURITY | Security event |
| BEHAVIOR | Behavior event |
- **keyValues**: event parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.
- A parameter name must be a string, and a parameter value must be a string, number, boolean, or array (which is a basic element).
- The number of event parameters must be less than or equal to 32.
- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).
- A string value can contain a maximum of 8*1024 characters.
- An array value can contain a maximum of 100 elements. Excess elements will be truncated.
- **callback**: callback function used to process the received return value. The value **0** indicates that the event parameter verification is successful, and the event will be written to the event file asynchronously. A value greater than **0** indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored. A value smaller than **0** indicates that the event parameter verification fails, and the event will not be written to the event file asynchronously.
When an asynchronous callback is used, the return value can be processed directly in the callback. When a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Event Verification Result Codes](hiappevent-overview.md#Event Verification Result Codes).
**APIs for event logging configuration:**
**APIs for Event Logging Configuration**
| API | Return Value | Description |
| ------------------------------ | ------------ | ------------------------------------------------------------ |
| configure(ConfigOption config) | boolean | Sets the configuration options for application event logging.<br/>The value **true** indicates that the operation is successful, and value **false** indicates the opposite. |
- **config**: configuration options for application event logging.
Configuration options for application event logging (**ConfigOption**)
| Name | Type | Mandatory | Description |
| ---------- | ------- | --------- | ------------------------------------------------------------ |
| disable | boolean | No | Sets the application event logging switch. The value **true** means to disable the application event logging function, and value **false** means the opposite. |
| maxStorage | string | No | Specifies the maximum size of the event file storage directory. The default value is 10M. |
**Predefined event name constants (Event)**:
| Constant | Type | Description |
| ------------------------- | ------ | ---------------------------------------------- |
| USER_LOGIN | string | Name of the user login event. |
| USER_LOGOUT | string | Name of the user logout event. |
| DISTRIBUTED_SERVICE_START | string | Name of the distributed service startup event. |
**Predefined parameter name constants (Param):**
| Constant | Type | Description |
| ------------------------------- | ------ | -------------------------------- |
| USER_ID | string | Custom user ID. |
| DISTRIBUTED_SERVICE_NAME | string | Distributed service name. |
| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Distributed service instance ID. |
## How to Develop
In this example, an application event is logged after the application startup execution page is loaded.
......@@ -103,8 +55,7 @@ In this example, an application event is logged after the application startup ex
}).catch((err) => {
console.error(`failed to write event because ${err.code}`);
});
});
// 3. Set the application event logging switch.
hiAppEvent.configure({
disable: true
......@@ -118,6 +69,4 @@ In this example, an application event is logged after the application startup ex
}
```
2. Tap the run button on the application UI to run the project.
2. Tap the run button on the application UI to run the project.
\ No newline at end of file
......@@ -6,9 +6,7 @@ HiAppEvent provides event logging APIs for applications to log the fault, statis
The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data.
- **Logging**
Logs changes caused by user operations to provide service data for development, product, and O&M analysis.
**Logging**: Logs changes caused by user operations to provide service data for development, product, and O&M analysis.
## Event Verification Result Codes
......
......@@ -6,18 +6,14 @@
- [Audio Playback Development](audio-playback.md)
- [Audio Playback Development Using AudioRenderer](audio-renderer.md)
- [Audio Rendering Development](audio-renderer.md)
- [Audio Recording Development](audio-recorder.md)
- [Audio Recorder Development Using AudioCapturer](audio-capturer)
- [Audio Capture Development](audio-capturer)
- Video
- [Video Playback Development](video-playback.md)
- [Video Recording Development](video-recorder.md)
- Image
- [Image Development](image.md)
# Audio Recorder Development Using AudioCapturer
# Audio Capture Development
---
## ***Note***:
......@@ -41,7 +41,7 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
2. (Optional) Subscribe to audio capturer state change events using the **on('stateChange')** API.
If an application wants to take some action based on the state updates in capturer, the application can subscribe to the state change event.
There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) for more details.
There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [Audio](../reference/apis/js-apis-audio.md) for more details.
```
audioCapturer.on('stateChange',(state) => {
console.info('AudioCapturerLog: Changed State to : ' + state)
......@@ -149,4 +149,4 @@ That is, the AudioCapturer has an internal state that the application must alway
The system may throw an error/exception or generate other undefined behaviour if the application performs an operation while capturer is in an improper state.
## **Other APIs**
See [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**.
See [AudioCapturer in the Audio API](../reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**.
......@@ -16,7 +16,7 @@ You can use audio playback APIs to convert audio data into audible analog signal
## How to Develop
For details about the APIs used for audio playback, see [js-apis-media.md](../reference/apis/js-apis-media.md).
For details about the APIs used for audio playback, see [AudioPlayer in the Media API](../reference/apis/js-apis-media.md).
### Full-Process Scenario
......
......@@ -16,7 +16,7 @@ During audio recording, audio signals are captured, encoded, and saved to files.
## How to Develop
For details about the APIs used for audio recording, see [js-apis-media.md](../reference/apis/js-apis-media.md).
For details about the APIs, see [AudioRecorder in the Media API](../reference/apis/js-apis-media.md).
### Full-Process Scenario
......@@ -127,7 +127,7 @@ import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
function SetCallBack(audioPlayer) {
function SetCallBack(audioRecorder) {
audioRecorder.on('prepare', () => { // Set the 'prepare' event callback.
console.log('prepare success');
// The recording page is ready. You can click the Record button to start recording.
......
# Audio Playback Development Using AudioRenderer
# Audio Rendering Development
---
## ***Note***:
......@@ -17,7 +17,7 @@ When a higher priority stream wants to play, the AudioRenderer framework interru
For example, if a call is arrived when you listen to music, the music playback, which is the lower priority stream, is paused.\
With the sample code below, we'll look at how AudioInterrupt works in detail.\
<br/>
Please see [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType.
Please see [AudioRenderer in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType.
## **Usage**
......@@ -267,8 +267,8 @@ The system may throw an error/exception or generate other undefined behaviour if
## **Asynchronous Operations:**
Most of the AudioRenderer calls are asynchronous. As a result, the UI thread will not be blocked.\
For each API, the framework provides both callback and promises functions.\
In the example, promise functions are used for simplicity. [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md)
In the example, promise functions are used for simplicity. [AudioRender in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8)
provides reference for both callback and promise.
## **Other APIs:**
See [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize.
See [Audio](../reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize.
......@@ -6,7 +6,7 @@ You can use image development APIs to decode images into pixel maps and encode t
## Available APIs
For details about the APIs, see [js-apis-image.md](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-image.md).
For details about the APIs, see [Image Processing](../reference/apis/js-apis-image.md).
## How to Develop
......
......@@ -20,9 +20,22 @@ Note: Video playback requires hardware capabilities such as display, audio, and
2. The third-party application transfers the surface ID to the VideoPlayer JS.
3. The media service flushes the frame data to the surface buffer.
## Compatibility
You are advised to use the mainstream playback formats and resolutions, rather than custom or abnormal streams to avoid playback failure, frame freezing, and artifacts. The system is not affected by incompatibility issues. If such an error occurs, you can exit stream playback mode.
The table below lists the mainstream playback formats and resolutions.
| Video Container Specification| Specification Description | Resolution |
| :----------: | :-----------------------------------------------: | :--------------------------------: |
| mp4 | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p|
| mkv | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p|
| ts | Video format: H.264/MPEG-2/MPEG-4; audio format: AAC/MP3 | Mainstream resolutions, such as 1080p, 720p, 480p, and 270p|
| webm | Video format: VP8; audio format: VORBIS | Mainstream resolutions, such as 1080p, 720p, 480p, and 270p|
## How to Develop
For details about the APIs used for video playback, see [js-apis-media.md](../reference/apis/js-apis-media.md).
For details about the APIs, see [VideoPlayer in the Media API](../reference/apis/js-apis-media.md).
### Full-Process Scenario
......
# Video Recording Development
## When to Use
During video recording, audio and video signals are captured, encoded, and saved to files. You can specify parameters such as the encoding format, encapsulation format, and file path for video recording.
**Figure 1** Video recording state transition
![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png)
**Figure 2** Layer 0 diagram of video recording
![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png)
## How to Develop
For details about the APIs used for video recording, see [js-apis-media.md](../reference/apis/js-apis-media.md).
### Full-Process Scenario
The full video recording process includes creating an instance, setting recording parameters, recording video, pausing, resuming, and stopping recording, and releasing resources.
```js
import media from '@ohos.multimedia.media'
import mediaLibrary from '@ohos.multimedia.mediaLibrary'
let testFdNumber;
// pathName indicates the passed recording file name, for example, 01.mp4. The generated file address is /storage/media/100/local/files/Movies/01.mp4.
// To use the media library, declare the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA.
async function getFd(pathName) {
let displayName = pathName;
const mediaTest = mediaLibrary.getMediaLibrary();
let fileKeyObj = mediaLibrary.FileKey;
let mediaType = mediaLibrary.MediaType.VIDEO;
let publicPath = await mediaTest.getPublicDirectory(mediaLibrary.DirectoryType.DIR_VIDEO);
let dataUri = await mediaTest.createAsset(mediaType, displayName, publicPath);
if (dataUri != undefined) {
let args = dataUri.id.toString();
let fetchOp = {
selections : fileKeyObj.ID + "=?",
selectionArgs : [args],
}
let fetchFileResult = await mediaTest.getFileAssets(fetchOp);
let fileAsset = await fetchFileResult.getAllObject();
let fdNumber = await fileAsset[0].open('Rw');
fdNumber = "fd://" + fdNumber.toString();
testFdNumber = fdNumber;
}
}
await getFd('01.mp4');
let videoProfile = {
audioBitrate : 48000,
audioChannels : 2,
audioCodec : 'audio/mp4a-latm',
audioSampleRate : 48000,
fileFormat : 'mp4',
videoBitrate : 48000,
videoCodec : 'video/mp4v-es',
videoFrameWidth : 640,
videoFrameHeight : 480,
videoFrameRate : 30
}
let videoConfig = {
audioSourceType : 1,
videoSourceType : 0,
profile : videoProfile,
url: testFdNumber, // testFdNumber is generated by getFd.
orientationHint : 0,
location : { latitude : 30, longitude : 130 },
}
// Error callback triggered in the case of an error
function failureCallback(error) {
console.info('error happened, error name is ' + error.name);
console.info('error happened, error code is ' + error.code);
console.info('error happened, error message is ' + error.message);
}
// Error callback triggered in the case of an exception
function catchCallback(error) {
console.info('catch error happened, error name is ' + error.name);
console.info('catch error happened, error code is ' + error.code);
console.info('catch error happened, error message is ' + error.message);
}
let videoRecorder = null; // videoRecorder is an empty object and assigned with a value after createVideoRecorder is successfully called.
let surfaceID = null; // Used to save the surface ID returned by getInputSurface.
// Create a VideoRecorder object.
await media.createVideoRecorder().then((recorder) => {
console.info('case createVideoRecorder called');
if (typeof (recorder) != 'undefined') {
videoRecorder = recorder;
console.info('createVideoRecorder success');
} else {
console.info('createVideoRecorder failed');
}
}, failureCallback).catch(catchCallback);
// Obtain the surface ID, save it, and pass it to camera-related interfaces.
await videoRecorder.getInputSurface().then((surface) => {
console.info('getInputSurface success');
surfaceID = surface;
}, failureCallback).catch(catchCallback);
// Video recording depends on camera-related interfaces. The following operations can be performed only after the video output start interface is invoked.
// Start video recording.
await videoRecorder.start().then(() => {
console.info('start success');
}, failureCallback).catch(catchCallback);
// Pause video playback before the video output stop interface is invoked.
await videoRecorder.pause().then(() => {
console.info('pause success');
}, failureCallback).catch(catchCallback);
// Resume video playback after the video output start interface is invoked.
await videoRecorder.resume().then(() => {
console.info('resume success');
}, failureCallback).catch(catchCallback);
// Stop video recording after the video output stop interface is invoked.
await videoRecorder.stop().then(() => {
console.info('stop success');
}, failureCallback).catch(catchCallback);
// Reset the recording configuration.
await videoRecorder.reset().then(() => {
console.info('reset success');
}, failureCallback).catch(catchCallback);
// Release the video recording resources and camera object resources.
await videoRecorder.release().then(() => {
console.info('release success');
}, failureCallback).catch(catchCallback);
// Set the related object to null.
videoRecorder = null;
surfaceID = null;
```
......@@ -3,5 +3,14 @@
- User Authentication
- [User Authentication Overview](userauth-overview.md)
- [User Authentication Development](userauth-guidelines.md)
- hapsigner
- [hapsigner Guide](hapsigntool-guidelines.md)
\ No newline at end of file
- Key Management
- [HUKS Overview](huks-overview.md)
- [HUKS Development](huks-guidelines.md)
- hapsigntool
- [hapsigntool Guide](hapsigntool-guidelines.md)
- Access Control
- [Access Control Overview](accesstoken-overview.md)
- [Access Control Development](accesstoken-guidelines.md)
\ No newline at end of file
# Access Control Development
## Scenario
In this example, the app requires the **ohos.permission.PERMISSION1** and **ohos.permission.PERMISSION2** permissions to implement core functions.
- The ability privilege level (APL) of the app is normal.
- The level of **ohos.permission.PERMISSION1** is normal, and the authorization mode is system_grant.
- The level of **ohos.permission.PERMISSION2** is system_basic, and the authorization mode is user_grant.
> **Precautions**
>
> In this scenario, the required permissions include a user_grant permission. You can check whether the caller has the required permission through permission verification.
>
> If the permission verification result indicates that the app has not obtained that permission, dynamic user authorization is required.
>
## Available APIs
The table below lists only the API used in this guide. For more information, see the [API Reference](../reference/apis/js-apis-abilityAccessCtrl.md).
| API | Description |
| ------------------------------------------------------------ | --------------------------------------------------- |
| verifyAccessToken(tokenID: number, permissionName: string): Promise&lt;GrantStatus&gt; | Verifies whether an app has the specified permission. This API uses a promise to return the result.|
## Declaring Permissions
### config.json
Declare the permissions required by the app one by one in the **config.json** file. The app cannot obtain a permission if it is not declared in the **config.json** file.
**Description of config.json**
| Field | Description |
| --------- | ------------------------------------------------------------ |
| name | Name of the permission. |
| reason | Reason for requesting the permission. This field is mandatory for a user_grant permission.|
| usedScene | Scenario of the permission. This field is mandatory for a user_grant permission.|
| abilities | Abilities that use the permission. The value is an array. |
| when | Time when the permission is used. The value can be **inuse** (the permission can be used only in the foreground) or **always** (the permission can be used in foreground and background).|
**Example**
```json
{
"module" : {
"requesetPermissions":[
{
"name" : "ohos.permission.PERMISSION1",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"inuse"
}
},
{
"name" : "ohos.permission.PERMISSION2",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"FormAbility"
],
"when":"always"
}
}
],
}
}
```
## Declaring the ACL
The permission level of **ohos.permission.PERMISSION2** is system_basic, which is higher than the app's APL. In this case, use the ACL.
In addition to declaring all the permissions in the **config.json** file, you must declare the permissions whose levels are higher than the app's APL in the app's profile. In this example, declare the permission under the **acls** field:
```json
{
"version-name": "1.0.0",
"version-code": 1,
"app-distribution-type": "os_integration",
"uuid": "5027b99e-5f9e-465d-9508-a9e0134ffe18",
"validity": {
"not-before": 1594865258,
"not-after": 1689473258
},
"type": "release",
"bundle-info": {
"developer-id": "OpenHarmony",
"distribution-certificate": "-----BEGIN CERTIFICATE-----\nMIICMzCCAbegAwIBAgIEaOC/zDAMBggqhkjOPQQDAwUAMGMxCzAJBgNVBAYTAkNO\nMRQwEgYDVQQKEwtPcGVuSGFybW9ueTEZMBcGA1UECxMQT3Blbkhhcm1vbnkgVGVh\nbTEjMCEGA1UEAxMaT3Blbkhhcm1vbnkgQXBwbGljYXRpb24gQ0EwHhcNMjEwMjAy\nMTIxOTMxWhcNNDkxMjMxMTIxOTMxWjBoMQswCQYDVQQGEwJDTjEUMBIGA1UEChML\nT3Blbkhhcm1vbnkxGTAXBgNVBAsTEE9wZW5IYXJtb255IFRlYW0xKDAmBgNVBAMT\nH09wZW5IYXJtb255IEFwcGxpY2F0aW9uIFJlbGVhc2UwWTATBgcqhkjOPQIBBggq\nhkjOPQMBBwNCAATbYOCQQpW5fdkYHN45v0X3AHax12jPBdEDosFRIZ1eXmxOYzSG\nJwMfsHhUU90E8lI0TXYZnNmgM1sovubeQqATo1IwUDAfBgNVHSMEGDAWgBTbhrci\nFtULoUu33SV7ufEFfaItRzAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0OBBYEFPtxruhl\ncRBQsJdwcZqLu9oNUVgaMAwGCCqGSM49BAMDBQADaAAwZQIxAJta0PQ2p4DIu/ps\nLMdLCDgQ5UH1l0B4PGhBlMgdi2zf8nk9spazEQI/0XNwpft8QAIwHSuA2WelVi/o\nzAlF08DnbJrOOtOnQq5wHOPlDYB4OtUzOYJk9scotrEnJxJzGsh/\n-----END CERTIFICATE-----\n",
"bundle-name": "com.ohos.permissionmanager",
"apl": "system_core",
"app-feature": "hos_system_app"
},
"acls": {
"allowed-acls": [
"ohos.permission.PERMISSION2"
]
},
"permissions": {
"restricted-permissions": []
},
"issuer": "pki_internal"
}
```
## Applying for the user_grant Permission
After the permissions are declared, the system grants the system_grant permission during the installation of the app. The user_grant permission must be authorized by the user.
Therefore, before invoking the API protected by the **ohos.permission.PERMISSION2 permission**, the app needs to verify whether it has the permission.
If the verification result indicates that the app has the permission, the app can access the target API. Otherwise, the app needs to request user authorization and then proceeds based on the authorization result. For details, see [Access Control Overview](accesstoken-overview.md).
> **Precautions**
>
> The permissions authorized by user are not permanent, because the user may revoke the authorization at any time. Therefore, even if the user has granted the requested permission to an app, the app's permission must be verified before the app calls an API protected by the permission.
## Example
The procedure is as follows:
1. Obtain the caller's identity tokenId.
2. Determine the permission to be verified. In this example, the permission is **permissionNameUser**.
3. Call **verifyAccessToken** to verify the permissions of the caller.
4. Proceed based on the permission verification result.
```js
import {describe, beforeEach, afterEach, it, expect} from 'deccjsunit/index'
import abilityAccessCtrl from '@ohos.abilityAccessCtrl'
import bundle from '@ohos.bundle'
async requestPermission() {
var permissionNameUser = "ohos.permission.PERMISSION2";
var bundleFlag = 0;
var tokenID = undefined;
var userID = 100;
var appInfo = await bundle.getApplicationInfo('ohos.acts.security.access_token.normal', bundleFlag, userID);
tokenID = appInfo.accessTokenId;
console.log("AccessTokenTest accessTokenId:" + appInfo.accessTokenId + ", name:" + appInfo.name
+ ", bundleName:" + appInfo.bundleName)
var atManager = abilityAccessCtrl.createAtManager();
var result = await atManager.verifyAccessToken(tokenID, permissionNameUser);
if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
// Execute the operation.
} else {
// Apply for dynamic user authorization using requestPermissionsFromUser.
}
}
```
> ![icon-note.gif](../public_sys-resources/icon-note.gif)**NOTE**<br/>
> For details about how to use **requestPermissionsFromUser**, see [API Reference] (../reference/apis/js-apis-ability-context.md).
此差异已折叠。
# HUKS Development
## When to Use
Openharmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. HUKS also provides APIs for applications to import or generate keys.
## Available APIs
| API | Description |
| ------------------------------------------------------------ | ---------------- |
| function generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback<HksResult>) : void; | Generates a private key. This method uses an asynchronous callback to return the result. |
| function generateKey(keyAlias: string, options: HuksOptions) : Promise<HuksResult>; | Generates a private key. This method uses a promise to return the result. |
| function exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback<HuksResult>) : void; | Exports the public key. This method uses an asynchronous callback to return the result. |
| function exportKey(keyAlias: string, options: HuksOptions) : Promise<HuksResult>; | Exports the public key. This method uses a promise to return the result. |
| function isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback<boolean>) : void; | Check whether a key exists. This method uses an asynchronous callback to return the result.|
| function isKeyExist(keyAlias: string, options: HuksOptions) : Promise<boolean>; | Check whether a key exists. This method uses a promise to return the result.|
| function deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback<HuksResult>) : void; | Deletes a key. This method uses an asynchronous callback to return the result. |
| function deleteKey(keyAlias: string, options: HuksOptions) : Promise<HuksResult>; | Deletes a key. This method uses a promise to return the result. |
## How to Develop
1. Import the HUKS module.
```js
import huks from '@ohos.security.huks'
```
2. Call **generateKey()** to generate a private key.
**keyAlias** indicates the alias of the key generated. **options** indicates the parameters used for generating the key. Set **options** based on the actual situation.
The value returned indicates whether the key is successfully generated.
```js
var alias = 'testAlias';
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_224
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
};
var options = {
properties: properties
}
var resultA = huks.generateKey(alias, options);
```
3. Call **Init()** to initialize the key.
**Alias** indicates the alias of the key to initialize, and **options** indicates the parameters used for initializing the key.
The value returned indicates whether the **Init** operation is successful.
```js
var alias = 'test001'
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HksKeyAlg.HKS_ALG_DH
};
properties[1] = {
tag: huks.HksTag.HKS_TAG_PURPOSE,
value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HksTag.HKS_TAG_KEY_SIZE,
value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
huks.init(alias, options, function(err, data) {
if (err.code !== 0) {
console.log("test init err information: " + JSON.stringify(err));
} else {
console.log(`test init data: ${JSON.stringify(data)}`);
}
})
```
4. Call **update()** to update the key.
**handle** indicates the session ID for updating the key. **options** indicates the parameters used for updating the key.
The value returned indicates whether the **Update** operation is successful.
```js
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HksKeyAlg.HKS_ALG_DH
};
properties[1] = {
tag: huks.HksTag.HKS_TAG_PURPOSE,
value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HksTag.HKS_TAG_KEY_SIZE,
value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
var result = huks.update(handle, options)
```
5. Call **finish()** to complete the operation.
**handle** indicates the session ID of the **Finish** operation. **options** indicates the parameters used for this operation.
The value returned indicates whether the **Finish** operation is successful.
```js
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HksKeyAlg.HKS_ALG_DH
};
properties[1] = {
tag: huks.HksTag.HKS_TAG_PURPOSE,
value: huks.HksKeyPurpose.HKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HksTag.HKS_TAG_KEY_SIZE,
value: huks.HksKeySize.HKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
var result = huks.finish(handle, options)
```
# HUKS Overview
### Introduction
Openharmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. HUKS also provides APIs for applications to import or generate keys.
### Basic Concepts
- HUKS provides key management functions, including encryption and decryption, signing and signature verification, key agreement and derivation, and Hash-based Message Authentication Code (HMAC) calculation.
- HUKS supports the following algorithms: AES and RSA in encryption and decryption, RSA, ECC, DSA, and ED25519 in signing and signature verification, PBKDF2 in key derivation, and DH, ECDH, and X25519 in key agreement.
- HUKS uses the OpenSSL and Mbed TLS algorithm libraries.
### Working Principles
HUKS manages keys through the following operations:
- **Init**: reads the key, creates a session ID, and returns the session ID to the caller.
- **Update**: updates data by segment based on the session ID obtained.
- **Finish**: processes all data transferred to HUKS and then releases resources.
>![](../public_sys-resources/icon-notice.gif)**NOTICE**:<br/>If an error occurs in the **Init**, **Update**, or **Finish** operation, you must invoke the **Abort** operation to terminate the use of the key.
### Constraints
N/A
# User Authentication Development
> ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**<br/>
> This development guide applies to the SDK of API Version 8 or later.
## When to Use
OpenHarmony supports 2D and 3D facial recognition that can be used for identity authentication during device unlocking, application login, and payment.
2D and 3D facial recognition used in identity authentication scenarios such as device unlocking, application login, and payment
## Available APIs
The **userIAM\_userAuth** module provides methods for checking the support for biometric authentication, and performing and canceling authentication. You can perform authentication based on biometric features such as facial characteristics. Before performing biometric authentication, check whether your device supports this capability, including the authentication type, security level, and whether local authentication is used. If biometric authentication is not supported, consider using another authentication type. The following table lists methods in the APIs available for biometric authentication.
The userIAM_userAuth module provides methods for checking the support for user authentication, and performing and canceling authentication. You can perform authentication based on biometric features such as facial characteristics. For more details, see [API Reference](../reference/apis/js-apis-useriam-userauth.md).
**Table 1** Methods available for biometric authentication
Before performing authentication, check whether the device supports user authentication, including the authentication type and level. If user authentication is not supported, consider using another authentication type. The following table lists the APIs available for user authentication.
| Method | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| getAuthenticator(): Authenticator | Obtains an **Authenticator** object for user authentication. <sup>6+</sup><br>Obtains an **Authenticator** object to check the device's capability of user authentication, perform or cancel user authentication, and obtain the tips generated in the authentication process. <sup>7+</sup> |
| checkAvailability(type: AuthType, level: SecureLevel): number | Checks whether the device supports the specified authentication type and security level. |
| execute(type: AuthType, level: SecureLevel, callback: AsyncCallback\<number>): void | Performs user authentication and returns the authentication result using an asynchronous callback. |
| execute(type: AuthType, level: SecureLevel): Promise\<number> | Performs user authentication and returns the authentication result using a promise. |
| cancel(): void | Cancels the current authentication. |
| on(type: "tip", callback: Callback\<Tip>): void | Subscribes to the events of the specified type. |
| off(type: "tip", callback?: Callback\<Tip>): void | Unsubscribes from the events of the specified type. |
**Table 1** APIs of user authentication
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| getVersion() : number | Obtains the version information of an authentication object. |
| getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number | Checks whether the device supports the specified authentication type and level.|
| auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array | Performs user authentication. This method uses asynchronous callback to return the result. |
| cancelAuth(contextID : Uint8Array) : number | Cancels an authentication. |
## How to Develop
Before starting the development, make the following preparations:
1. Add the **ohos.permission.ACCESS\_BIOMETRIC** permission declaration to the application permission file.
2. Add **import userIAM\_userAuth from '@ohos.userIAM.userAuth'** to the code file that provides biometric recognition.
1. Add the ohos.permission.ACCESS_BIOMETRIC permission declaration to the application permission file.
2. Add **import userIAM_userAuth from '@ohos.userIAM.userAuth'** to the code file.
The development procedure is as follows:
1. Obtain an **Authenticator** singleton object. The sample code is as follows:
```
let auth = userIAM_userAuth.getAuthenticator();
```
2. Check whether the device provides the authentication capability of the specified level.
2D facial recognition supports authentication lower than S2, and 3D facial recognition supports authentication lower than S3. The sample code is as follows:
```
let authenticator = userIAM_userAuth.getAuthenticator();
let checkCode = authenticator.checkAvailability("FACE_ONLY", "S2");
if (checkCode == userIAM_userAuth.CheckAvailabilityResult.SUPPORTED) {
console.info("check auth support success");
} else {
console.error("check auth support fail, code = " + checkCode);
}
```
3. \(Optional\) Subscribe to tip information. The sample code is as follows:
```
let authenticator = userIAM_userAuth.getAuthenticator();
let tipCallback = (tip)=>{
console.info("receive tip: errorCode(" + tip.errorCode + ") code(" + tip.tipCode +") event(" +
tip.tipEvent + ") info(" + tip.tipInfo + ")");
};
authenticator.on("tip", tipCallback);
```
4. Perform the authentication. The sample code is as follows:
```
let authenticator = userIAM_userAuth.getAuthenticator();
authenticator.execute("FACE_ONLY", "S2").then((code)=>{
authenticator.off("tip", tipCallback);
console.info("auth success");
}).catch((code)=>{
authenticator.off("tip", tipCallback);
console.error("auth fail, code = " + code);
});
```
5. \(Optional\) Unsubscribe from tip information if you have subscribed to tip information you have subscribed to tip information.
```
let authenticator = userIAM_userAuth.getAuthenticator();
let tipCallback = (tip)=>{
console.info("receive tip: errorCode(" + tip.errorCode + ") code(" + tip.tipCode + ") event(" +
tip.tipEvent + ") info(" + tip.tipInfo + ")");
};
// Unsubscribe from a specified callback.
authenticator.off("tip", tipCallback);
// Unsubscribe from all callbacks.
authenticator.off("tip");
```
6. Cancel authentication. The sample code is as follows:
```
let authenticator = userIAM_userAuth.getAuthenticator();
let cancelCode = authenticator.cancel();
if (cancelCode == userIAM_userAuth.Result.SUCCESS) {
console.info("cancel auth success");
} else {
console.error("cancel auth fail");
}
```
1. Obtain an **Authenticator** singleton object. The sample code is as follows:
```js
let auth = new userIAM_userAuth.UserAuth();
```
2. (Optional) Obtain the version information of the authenticated object.
```js
let auth = new userIAM_userAuth.UserAuth();
let version = auth.getVersion();
console.info("auth version = " + version);
```
3. Check whether the device supports the authentication capabilities based on the specified authentication type and level.
```js
let auth = new userIAM_userAuth.UserAuth();
let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1);
if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) {
console.info("check auth support success");
// Add the logic to be executed if the specified authentication type is supported.
} else {
console.error("check auth support fail, code = " + checkCode);
// Add the logic to be executed if the specified authentication type is not supported.
}
```
4. Perform an authentication.
```js
let auth = new userIAM_userAuth.UserAuth();
auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
onResult: (result, extraInfo) => {
try {
console.info("auth onResult result = " + result);
console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo));
if (result == 'SUCCESS') {
// Add the logic to be executed when the authentication is successful.
} else {
// Add the logic to be executed when the authentication fails.
}
} catch (e) {
console.info("auth onResult error = " + e);
}
},
onAcquireInfo: (module, acquire, extraInfo) => {
try {
console.info("auth onAcquireInfo module = " + module);
console.info("auth onAcquireInfo acquire = " + acquire);
console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo));
} catch (e) {
console.info("auth onAcquireInfo error = " + e);
}
}
});
```
5. Cancel the authentication.
```js
let auth = new userIAM_userAuth.UserAuth();
// Obtain contextId using auth().
let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
onResult: (result, extraInfo) => {
console.info("auth onResult result = " + result);
},
onAcquireInfo: (module, acquire, extraInfo) => {
console.info("auth onAcquireInfo module = " + module);
}
});
let cancelCode = auth.cancel(contextId);
if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) {
console.info("cancel auth success");
} else {
console.error("cancel auth fail");
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册