diff --git a/CODEOWNERS b/CODEOWNERS index 1723d5288fa2d4fa89dff9a3c2999c31370b55fd..a57ea8f6e10f53e073eb37e4fe33e1fffea8b84d 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -129,11 +129,38 @@ zh-cn/device-dev/subsystems/subsys-toolchain-bytrace-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md @Austin23 zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 - +zh-cn/application-dev/quick-start/arkts-get-started.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-basic-syntax-overview.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-declarative-ui-description.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-create-custom-components.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-page-custom-components-lifecycle.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-builder.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-builderparam.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-style.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-extend.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-statestyles.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-state-management-overview.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-state.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-prop.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-link.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-provide-and-consume.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-application-state-management-overview.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-localstorage.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-appstorage.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-persiststorage.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-environment.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-other-state-mgmt-functions-overview.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-watch.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-two-way-sync.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-rendering-control-overview.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-rendering-control-ifelse.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-rendering-control-foreach.md @HelloCrease @tomatodevboy @s10021109 +zh-cn/application-dev/quick-start/arkts-rendering-control-lazyforeach.md @HelloCrease @tomatodevboy @s10021109 zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen zh-cn/application-dev/device-usage-statistics/ @chenmingJay @ningningW @tangtiantian2021 @nan-xiansen @iceice1001 -zh-cn/application-dev/ui/ @HelloCrease @huaweimaxuchu @tomatodevboy @niulihua +zh-cn/application-dev/ui/ @HelloCrease @tomatodevboy @niulihua zh-cn/application-dev/notification/ @RayShih @jayleehw @li-weifeng2 @currydavids zh-cn/application-dev/windowmanager/ @ge-yafang @zhangqiang183 @zhouyaoying @zxg-gitee @nobuggers zh-cn/application-dev/webgl/ @zengyawen @zhangqiang183 @wind_zj @zxg-gitee @@ -208,8 +235,8 @@ zh-cn/application-dev/device/vibrator-overview.md @ningningW @hellohyh001 @butte zh-cn/application-dev/device/vibrator-guidelines.md @ningningW @hellohyh001 @butterls @star-wind-snow-and-rain zh-cn/application-dev/device/sample-server-overview.md @ningningW @hughes802 @zhangzhengxue @mamba-ting zh-cn/application-dev/device/sample-server-guidelines.md @ningningW @hughes802 @zhangzhengxue @mamba-ting -zh-cn/application-dev/reference/arkui-js/ @HelloCrease @huaweimaxuchu @niulihua @tomatodevboy -zh-cn/application-dev/reference/arkui-ts/ @HelloCrease @huaweimaxuchu @niulihua @tomatodevboy +zh-cn/application-dev/reference/arkui-js/ @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/arkui-ts/ @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/native-lib @zengyawen @gongjunsong @liwentao_uiw @BlackStone zh-cn/application-dev/quick-start/start-overview.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets-stage.md @ge-yafang @@ -241,7 +268,7 @@ zh-cn/application-dev/quick-start/arkts-state-mgmt-application-level.md @gaoyong zh-cn/application-dev/quick-start/arkts-dynamic-ui-elememt-building.md @gaoyong @niejiteng @jumozhanjiang @HelloCrease zh-cn/application-dev/quick-start/arkts-rendering-control.md @gaoyong @niejiteng @jumozhanjiang @HelloCrease zh-cn/application-dev/quick-start/arkts-restrictions-and-extensions.md @gaoyong @niejiteng @jumozhanjiang @HelloCrease -zh-cn/application-dev/napi/napi-guidelines.md @RayShih @huaweimaxuchu @niulihua @tomatodevboy +zh-cn/application-dev/napi/napi-guidelines.md @RayShih @niulihua @tomatodevboy zh-cn/application-dev/napi/drawing-guidelines.md @zengyawen @zhangqiang183 @wind_zj @zxg-gitee zh-cn/application-dev/napi/rawfile-guidelines.md @ningningW @Buda-Liu @budda-wang @yangqing3 zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease @@ -258,7 +285,7 @@ zh-cn/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md @little zh-cn/application-dev/reference/apis/js-apis-abilityrunninginfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-abilitystagecontext.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md @mupceet @RayShih @mupceet @gaoxi785 -zh-cn/application-dev/reference/apis/js-apis-animator.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-animator.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-appAccount.md @nianCode @zengyawen @JiDong-CS @murphy1984 zh-cn/application-dev/reference/apis/js-apis-application-ability.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-application-abilityConstant.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen @@ -393,7 +420,7 @@ zh-cn/application-dev/reference/apis/js-apis-list.md @gongjunsong @ge-yafang @fl zh-cn/application-dev/reference/apis/js-apis-logs.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-media.md @liuyuehua1 @zengyawen @xxb-wzy @currydavids zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @panqinxu @zengyawen @bubble_mao @jinhaihw -zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-mediaquery.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-missionManager.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @yuanxinying @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-net-connection.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 @@ -412,13 +439,13 @@ zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @nianCode @zengya zh-cn/application-dev/reference/apis/js-apis-process.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-processrunninginformation.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen -zh-cn/application-dev/reference/apis/js-apis-prompt.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-prompt.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-queue.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-radio.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @nagexiucai @murphy1984 zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @mengjingzhimo @yangqing3 -zh-cn/application-dev/reference/apis/js-apis-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world zh-cn/application-dev/reference/apis/js-apis-runninglock.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-screen.md @zhangqiang183 @ge-yafang @zhouyaoying @zxg-gitee @nobuggers @@ -427,14 +454,14 @@ zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @panqinxu @zengyaw zh-cn/application-dev/reference/apis/js-apis-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-service-extension-ability.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md @littlejerry1 @RayShih @gwang2008 @chengxingzhen -zh-cn/application-dev/reference/apis/js-apis-settings.md @tetex @ge-yafang @cnzhaoxiaohu @anning7 +zh-cn/application-dev/reference/apis/js-apis-settings.md @xue-seu @ge-yafang zh-cn/application-dev/reference/apis/js-apis-sim.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-sms.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-socket.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-stack.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-statfs.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md @panqinxu @zengyawen @bubble_mao @jinhaihw -zh-cn/application-dev/reference/apis/js-apis-system-app.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-system-app.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-battery.md @aqxyjay @zengyawen @aqxyjay @alien0208 zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @aqxyjay @zengyawen @aqxyjay @alien0208 @@ -445,14 +472,14 @@ zh-cn/application-dev/reference/apis/js-apis-system-device.md @mupceet @zengyawe zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-system-file.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-system-location.md @cheng_guohong @RayShih @cheng_guohong @xiangkejin123 -zh-cn/application-dev/reference/apis/js-apis-system-mediaquery.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-system-mediaquery.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-network.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-system-notification.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-system-package.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @mupceet @zengyawen @handyohos @nan-xiansen -zh-cn/application-dev/reference/apis/js-apis-system-prompt.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-system-prompt.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-request.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 -zh-cn/application-dev/reference/apis/js-apis-system-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-system-router.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @hellohyh001 @ningningW @butterls @star-wind-snow-and-rain zh-cn/application-dev/reference/apis/js-apis-system-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 zh-cn/application-dev/reference/apis/js-apis-system-time.md @feng-aiwen @ningningW @illybyy @murphy1984 @@ -534,7 +561,7 @@ zh-cn/application-dev/reference/apis/js-apis-configPolicy.md @liuzuming @ningnin zh-cn/application-dev/reference/apis/js-apis-cooperate.md @yuanxinying @ningningW @cococoler @alien0208 zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @gaoyong @zengyawen @niejiteng @jumozhanjiang zh-cn/application-dev/reference/apis/js-apis-cert.md @gaoyong @zengyawen @niejiteng @jumozhanjiang -zh-cn/application-dev/reference/apis/js-apis-curve.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-curve.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-defaultAppManager.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-distributedKVStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42 @@ -555,11 +582,11 @@ zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @stone2050 zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @feng-aiwen @ningningW @SuperShrimp @murphy1984 zh-cn/application-dev/reference/apis/js-apis-installer.md @shuaytao @RayShih @wangzhen107 @inter515 zh-cn/application-dev/reference/apis/js-apis-launcherBundleManager.md @shuaytao @RayShih @wangzhen107 @inter515 -zh-cn/application-dev/reference/apis/js-apis-matrix4.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-matrix4.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-nfctech.md @cheng_guohong @RayShih @cheng_guohong @quanli125 -zh-cn/application-dev/reference/apis/js-apis-promptAction.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-promptAction.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-resourceschedule-deviceStandby.md @chenmingJay @ningningW @nan-xiansen @iceice1001 zh-cn/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @chenmingJay @ningningW @nan-xiansen @iceice1001 @@ -572,7 +599,12 @@ zh-cn/application-dev/reference/apis/js-apis-system-parameterV9.md @mupceet @zen zh-cn/application-dev/reference/apis/js-apis-tagSession.md @cheng_guohong @RayShih @cheng_guohong @quanli125 zh-cn/application-dev/reference/apis/js-apis-userFileManager.md @panqinxu @zengyawen @bubble_mao @jinhaihw zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @gaoyong @zengyawen @niejiteng @jumozhanjiang - +zh-cn/application-dev/reference/apis/js-apis-arkui-componentSnapshot.md @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-font.md @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-plugincomponent.md @HelloCrease @niulihua @tomatodevboy +zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/errorcodes/errorcode-ability.md @RayShih zh-cn/application-dev/reference/errorcodes/errorcode-access-token.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-accessibility.md @RayShih diff --git a/en/application-dev/application-models/arkts-ui-widget-update-by-status.md b/en/application-dev/application-models/arkts-ui-widget-update-by-status.md index b27958c66d3e174a66c80c90e46cdd71f5ecf668..5fb323813741a81e01b120507561e377995b7d90 100644 --- a/en/application-dev/application-models/arkts-ui-widget-update-by-status.md +++ b/en/application-dev/application-models/arkts-ui-widget-update-by-status.md @@ -1,7 +1,8 @@ # Updating Widget Content by State +There are cases where multiple copies of the same widget are added to the home screen to accommodate different needs. In these cases, the widget content needs to be dynamically updated based on the state. This topic exemplifies how this is implemented. -There are cases where multiple copies of the same widget are added to the home screen to accommodate different needs. In these cases, the widget content needs to be dynamically updated based on the state. This topic exemplifies how this is implemented. In the following example, two weather widgets are added to the home screen: one for displaying the weather of London, and the other Beijing, both configured to be updated at 07:00 every morning. The widget provider detects the target city, and then displays the city-specific weather information on the widgets. +In the following example, two copies of the weather widget are added to the home screen: one for displaying the weather of London, and the other Beijing, both configured to be updated at 07:00 every morning. The widget provider detects the target city, and then displays the city-specific weather information on the widgets. - Widget configuration file: Configure the widget to be updated at 07:00 every morning. @@ -94,7 +95,7 @@ There are cases where multiple copies of the same widget are added to the home s import formProvider from '@ohos.app.form.formProvider'; import formBindingData from '@ohos.app.form.formBindingData'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; - import dataStorage from '@ohos.data.storage' + import dataPreferences from '@ohos.data.preferences'; export default class EntryFormAbility extends FormExtensionAbility { onAddForm(want) { @@ -102,10 +103,10 @@ There are cases where multiple copies of the same widget are added to the home s let isTempCard: boolean = want.parameters[formInfo.FormParam.TEMPORARY_KEY]; if (isTempCard === false) {// If the widget is a normal one, the widget information is persisted. console.info('Not temp card, init db for:' + formId); - let storeDB = dataStorage.getStorageSync(this.context.filesDir + 'myStore') - storeDB.putSync('A' + formId, 'false'); - storeDB.putSync('B' + formId, 'false'); - storeDB.flushSync(); + let storeDB = dataPreferences.getPreferences(this.context, 'mystore') + storeDB.put('A' + formId, 'false'); + storeDB.put('B' + formId, 'false'); + storeDB.flush(); } let formData = {}; return formBindingData.createFormBindingData(formData); @@ -113,24 +114,24 @@ There are cases where multiple copies of the same widget are added to the home s onRemoveForm(formId) { console.info('onRemoveForm, formId:' + formId); - let storeDB = dataStorage.getStorageSync(this.context.filesDir + 'myStore') - storeDB.deleteSync('A' + formId); - storeDB.deleteSync('B' + formId); + let storeDB = dataPreferences.getPreferences(this.context, 'mystore') + storeDB.delete('A' + formId); + storeDB.delete('B' + formId); } // If the widget is a temporary one, it is recommended that the widget information be persisted when the widget is converted to a normal one. onCastToNormalForm(formId) { console.info('onCastToNormalForm, formId:' + formId); - let storeDB = dataStorage.getStorageSync(this.context.filesDir + 'myStore') - storeDB.putSync('A' + formId, 'false'); - storeDB.putSync('B' + formId, 'false'); - storeDB.flushSync(); + let storeDB = dataPreferences.getPreferences(this.context, 'myStore') + storeDB.put('A' + formId, 'false'); + storeDB.put('B' + formId, 'false'); + storeDB.flush(); } onUpdateForm(formId) { - let storeDB = dataStorage.getStorageSync(this.context.filesDir + 'myStore') - let stateA = storeDB.getSync('A' + formId, 'false').toString() - let stateB = storeDB.getSync('B' + formId, 'false').toString() + let storeDB = dataPreferences.getPreferences(this.context, 'myStore') + let stateA = storeDB.get('A' + formId, 'false').toString() + let stateB = storeDB.get('B' + formId, 'false').toString() // Update textA in state A. if (stateA === 'true') { let formInfo = formBindingData.createFormBindingData({ @@ -150,17 +151,17 @@ There are cases where multiple copies of the same widget are added to the home s onFormEvent(formId, message) { // Store the widget state. console.info('onFormEvent formId:' + formId + 'msg:' + message); - let storeDB = dataStorage.getStorageSync(this.context.filesDir + 'myStore') + let storeDB = dataPreferences.getPreferences(this.context, 'myStore') let msg = JSON.parse(message) if (msg.selectA != undefined) { console.info('onFormEvent selectA info:' + msg.selectA); - storeDB.putSync('A' + formId, msg.selectA); + storeDB.put('A' + formId, msg.selectA); } if (msg.selectB != undefined) { console.info('onFormEvent selectB info:' + msg.selectB); - storeDB.putSync('B' + formId, msg.selectB); + storeDB.put('B' + formId, msg.selectB); } - storeDB.flushSync(); + storeDB.flush(); } }; ``` @@ -168,4 +169,4 @@ There are cases where multiple copies of the same widget are added to the home s > **NOTE** > -> When the local database is used for widget information persistence, it is recommended that [TEMPORARY_KEY](../reference/apis/js-apis-app-form-formInfo.md#formparam) be used to determine whether the currently added widget is a normal one in the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) lifecycle callback. If the widget is a normal one, the widget information is directly persisted. If the widget is a temporary one, the widget information is persisted when the widget is converted to a normal one ([onCastToNormalForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#oncasttonormalform)). In addition, the persistent widget information needs to be deleted when the widget is destroyed ([onRemoveForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onremoveform)), preventing the database size from continuously increasing due to repeated widget addition and deletion. +> When the local database is used for widget information persistence, it is recommended that [TEMPORARY_KEY](../reference/apis/js-apis-app-form-formInfo.md#formparam) be used in the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) lifecycle callback to determine whether the currently added widget is a normal one. If the widget is a normal one, the widget information is directly persisted. If the widget is a temporary one, the widget information is persisted when the widget is converted to a normal one ([onCastToNormalForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#oncasttonormalform)). In addition, the persistent widget information needs to be deleted when the widget is destroyed ([onRemoveForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onremoveform)), preventing the database size from continuously increasing due to repeated widget addition and deletion. diff --git a/en/application-dev/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md index 5d67f4ab8aafba955da4a882b382f9df25896f3b..21effd689817299aabdaaab34724edd8349622dc 100644 --- a/en/application-dev/faqs/Readme-EN.md +++ b/en/application-dev/faqs/Readme-EN.md @@ -3,7 +3,7 @@ - [Full SDK Compilation](full-sdk-compile-guide.md) - [Switching to Full SDK](full-sdk-switch-guide.md) - [Application Model Development](faqs-ability.md) -- ArkUI Framework Development (ArkTS) +- ArkUI Development (ArkTS) - [ArkTS Syntax Usage](faqs-arkui-arkts.md) - [ArkUI Component Development (ArkTS)](faqs-arkui-component.md) - [ArkUI Layout Development (ArkTS)](faqs-arkui-layout.md) diff --git a/en/application-dev/file-management/app-sandbox-directory.md b/en/application-dev/file-management/app-sandbox-directory.md index 2da514469b80369d2660d14a0fd715e282e57adf..f9cfb0317c29bff58664ed894f585a5127943fa5 100644 --- a/en/application-dev/file-management/app-sandbox-directory.md +++ b/en/application-dev/file-management/app-sandbox-directory.md @@ -47,12 +47,12 @@ The following figure shows the application file directories. The path of a file 3. Level 3 directories **el1/** and **el2/**: indicate directories for files of different encryption levels (els). - **el1**: directory for the data that can be accessed once the device starts. This directory contains device-focused files. - **el2**: directory for the data that can be accessed only after at lease one successful unlocking operation (by PIN, fingerprint, or facial authentication, or password-free sign-in) upon the start of the device. This directory contains user-focused files.
- Unless otherwise required, application data is placed in the **el2** directory for security purposes. However, the data that needs to be accessed before the screen is unlocked (such as the clock, alarm, and wallpaper data) can be placed in the **el1** directory. For details about how to switch to and modify the **el** directories, see [Obtaining and Modifying el Directories](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-areas). + Unless otherwise required, application data is placed in the **el2** directory for security purposes. However, the data that needs to be accessed before the screen is unlocked (such as the clock, alarm, and wallpaper data) can be placed in the **el1** directory. For details about how to switch to and modify the **el** directories, see [Obtaining and Modifying el Directories](../application-models/application-context-stage.md#obtaining-and-modifying-encryption-levels). 4. Level 4 and level 5 directories: The application's global data is stored in the **files**, **cache**, **preferences**, **temp**, and **distributedfiles** folders in **base**. You can use **ApplicationContext** to obtain the application file paths of these folders. - You can use **UIAbilityContext**, **AbilityStageContext**, and **ExtensionContext** to obtain application file paths related to the OpenHarmoy Ability Package (HAP). When the HAP is uninstalled, the files stored in these directories are automatically deleted, without affecting the files in app-level directories. An application in the development state contains one or more HAPs. For details, see [Application Package Structure in Stage Mode](../quick-start/application-package-structure-stage.md). + You can use **UIAbilityContext**, **AbilityStageContext**, and **ExtensionContext** to obtain application file paths related to the OpenHarmony Ability Package (HAP). When the HAP is uninstalled, the files stored in these directories are automatically deleted, without affecting the files in app-level directories. An application in the development state contains one or more HAPs. For details, see [Application Package Structure in Stage Mode](../quick-start/application-package-structure-stage.md). For details about how to obtain the context and application file paths, see [Context (Stage Model)](../application-models/application-context-stage.md). diff --git a/en/application-dev/reference/apis/js-apis-cryptoFramework.md b/en/application-dev/reference/apis/js-apis-cryptoFramework.md index afb1bd3f8d80a74415c359af492492286364008c..422104663d3902e3d02488ca879e4089394a7f83 100644 --- a/en/application-dev/reference/apis/js-apis-cryptoFramework.md +++ b/en/application-dev/reference/apis/js-apis-cryptoFramework.md @@ -8,2250 +8,2346 @@ The **cryptoFramework** module shields underlying hardware and algorithm librari ## Modules to Import -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" ``` ## Result -Enumerates the error codes. + Enumerates the operation results. -**System capability**: SystemCapability.Security.CryptoFramework + **System capability**: SystemCapability.Security.CryptoFramework | Name | Value | Description | | ------------------------------------- | -------- | ---------------------------- | -| INVALID_PARAMS | 401 | Invalid parameters. | +| INVALID_PARAMS | 401 | Invalid parameters. | | NOT_SUPPORT | 801 | Unsupported operation. | | ERR_OUT_OF_MEMORY | 17620001 | Memory error. | | ERR_RUNTIME_ERROR | 17620002 | Runtime error. | -| ERR_CRYPTO_OPERATION | 17630001 | Cryptographic operation error. | +| ERR_CRYPTO_OPERATION | 17630001 | Failed to invoke the third-party cryptographic API. | ## DataBlob Defines a binary data array. -**System capability**: SystemCapability.Security.CryptoFramework + **System capability**: SystemCapability.Security.CryptoFramework | Name| Type | Readable| Writable| Description | | ---- | ---------- | ---- | ---- | ------ | | data | Uint8Array | Yes | Yes | Binary data array. | +## ParamsSpec -## cryptoFramework.createMac - -createMac(algName : string) : Mac +Defines the parameters used for encryption and decryption.
For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). If the IV is not required (for example, the ECB mode), pass in **null** in [init()](#init-2). -Creates a **Mac** instance for message authentication code (MAC) operations. +**System capability**: SystemCapability.Security.CryptoFramework -For details about the supported specifications, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications). +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Yes | Symmetric encryption and decryption parameters. Options:
- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode.| -**System capability**: SystemCapability.Security.CryptoFramework +> **NOTE** +> +> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class). However, a specific child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, you need to set **algName** for the parent class **ParamsSpec** to specify the child class object in **init()**. -**Parameters** +## IvParamsSpec -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications).| +Defines the child class of [ParamsSpec](#paramsspec). It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**IvParamsSpec** applies to the encryption and decryption modes such as CBC, CTR, OFB, and CFB, which use only the IV. -**Return value** +**System capability**: SystemCapability.Security.CryptoFramework -| Type| Description | -| ---- | --------------------------------------- | -| Mac | [Mac](#mac) instance created.| +| Name| Type | Readable| Writable| Description | +| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. Options:
- AES CBC, CTR, OFB, or CFB mode: 16-byte IV
- 3DES CBC, OFB, or CFB mode: 8-byte IV| -**Error codes** +> **NOTE** +> +> Before passing [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec). -| ID| Error Message | -| -------- | ------------------ | -| 17620001 | memory error. | +## GcmParamsSpec -**Example** +Defines the child class of [ParamsSpec](#paramsspec) for the GCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**GcmParamsSpec** applies to the GCM mode. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +**System capability**: SystemCapability.Security.CryptoFramework -var mac; -try { - // Set algName based on the algorithm supported. - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); -} -``` +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes. | +| aad | [DataBlob](#datablob) | Yes | Yes | Additional authentication data (AAD), which is of 8 bytes. | +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.
When the GCM mode is used for encryption, the last 16 bytes of the [DataBlob](#datablob) output by [doFinal()](#dofinal-2) are used as the **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2). | -## Mac +> **NOTE** +> +> Before passing [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec). -Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac). +## CcmParamsSpec -### Attributes +Defines the child class of [ParamsSpec](#paramsspec) for the CCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**CcmParamsSpec** applies to the CCM mode. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | -------------------- | -| algName | string | Yes | No | Digest algorithm to use.| +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. | +| aad | [DataBlob](#datablob) | Yes | Yes | Additional authentication data (AAD), which is of 8 bytes. | +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.
When the CCM mode is used for encryption, the last 12 bytes of the [DataBlob](#datablob) output by [doFinal()](#dofinal-2) are used as the **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).| -### init +> **NOTE** +> +> Before passing [init()](#init-2), specify **algName** for its parent class [ParamsSpec](#paramsspec). -init(key : SymKey, callback : AsyncCallback\) : void; +## CryptoMode -Initializes the MAC computation using a symmetric key. This API uses an asynchronous callback to return the result. +Enumerates the cryptographic operations. **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------ | -| key | [SymKey](#symkey) | Yes | Shared symmetric key.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Name | Value | Description | +| ------------ | ---- | ------------------ | +| ENCRYPT_MODE | 0 | Encryption.| +| DECRYPT_MODE | 1 | Decryption.| -**Error codes** +## AsyKeySpecItem10+ -| ID| Error Message | -| -------- | ---------------------- | -| 17630001 | crypto operation error. | +Enumerates the key parameters. -**Example** +**System capability**: SystemCapability.Security.CryptoFramework -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| DSA_P_BN | 101 | Prime modulus **p** in the DSA algorithm.| +| DSA_Q_BN | 102 | Parameter **q** (prime factor of p – 1) in the DSA algorithm.| +| DSA_G_BN | 103 | Parameter **g** in the DSA algorithm.| +| DSA_SK_BN | 104 | Private key **sk** in the DSA algorithm.| +| DSA_PK_BN | 105 | Public key **pk** in the DSA algorithm.| +| ECC_FP_P_BN | 201 | Prime number **p** in the **Fp** fields of the elliptic curve in the DSA algorithm.| +| ECC_A_BN | 202 | First coefficient **a** of the elliptic curve in the DSA algorithm.| +| ECC_B_BN | 203 | Second coefficient **b** of the elliptic curve in the DSA algorithm.| +| ECC_G_X_BN | 204 | X coordinate of the base point **g** in the ECC algorithm.| +| ECC_G_Y_BN | 205 | Y coordinate of the base point **g** in the ECC algorithm.| +| ECC_N_BN | 206 | Order **n** of the base point **g** in the ECC algorithm.| +| ECC_H_NUM | 207 | Cofactor **h** in the ECC algorithm.| +| ECC_SK_BN | 208 | Private key **sk** in the ECC algorithm.| +| ECC_PK_X_BN | 209 | X coordinate of the public key **pk** (a point on the elliptic curve) in the ECC algorithm.| +| ECC_PK_Y_BN | 210 | Y coordinate of the public key **pk** (a point on the elliptic curve) in the ECC algorithm.| +| ECC_FIELD_TYPE_STR | 211 | Elliptic curve field type in the ECC algorithm. Currently, only the **Fp** field is supported.| +| ECC_FIELD_SIZE_NUM | 212 | Size of the field in the ECC algorithm, in bits.
**NOTE**: For the **Fp** field, the field size is the length of the prime **p**, in bits. | +| ECC_CURVE_NAME_STR | 213 | SECG curve name in the ECC algorithm.| +| RSA_N_BN | 301 | Modulus **n** in the RSA algorithm.| +| RSA_SK_BN | 302 | Private key **sk** (private key exponent **d**) in the RSA algorithm.| +| RSA_PK_BN | 303 | Public key **pk** (public key exponent **e**) in the RSA algorithm.| + +## AsyKeySpecType10+ + +Enumerates the key parameter types. -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); -} -var KeyBlob; -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { - if (err) { - console.error("[Callback] err: " + err.code); - } - mac.init(symKey, (err1, ) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } - }); -}); -``` +**System capability**: SystemCapability.Security.CryptoFramework -### init +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| COMMON_PARAMS_SPEC | 0 | Common parameters contained in the public and private keys. You can use [generateKeyPair()](#generatekeypair-2) to randomly generate a key pair based on the parameters of this type.| +| PRIVATE_KEY_SPEC | 1 | Parameter contained in the private key. You can use [generatePriKey()](#generateprikey) to generate a private key based on the parameters of this type.| +| PUBLIC_KEY_SPEC | 2 | Parameter contained in the public key. You can use [generatePubKey()](#generatepubkey) to generate a public key based on the parameters of this type.| +| KEY_PAIR_SPEC | 3 | All parameters contained in the public and private keys. You can use [generateKeyPair](#generatekeypair-2) to generate a key pair based on the parameters of this type.| -init(key : SymKey) : Promise\; +## CipherSpecItem10+ -Initializes the MAC computation using a symmetric key. This API uses a promise to return the result. +Enumerates the cipher parameters. You can use [setCipherSpec](#setcipherspec10) to set cipher parameters, and use [getCipherSpec](#getcipherspec10) to obtain cipher parameters.
Currently, only the RSA is supported. For details, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| OAEP_MD_NAME_STR | 100 | Name of the message digest algorithm when the PKCS1_OAEP padding mode is used in the RSA.| +| OAEP_MGF_NAME_STR | 101 | Mask generation algorithm when the PKCS1_OAEP padding mode is used in the RSA. Currently, only MGF1 is supported.| +| OAEP_MGF1_MD_STR | 102 | Message digest algorithm for the MGF1 mask generation when the PKCS1_OAEP padding mode is used in the RSA.| +| OAEP_MGF1_PSRC_UINT8ARR | 103 | **pSource** byte stream when the PKCS1_OAEP padding mode is used in the RSA.| -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------ | -| key | [SymKey](#symkey) | Yes | Shared symmetric key.| +## SignSpecItem10+ -**Return value** +Enumerates the parameters for signing and signature verification. You can use [setSignSpec](#setsignspec10) and [setVerifySpec](#setverifyspec10) to set these parameters, and use [getSignSpec](#getsignspec10) and [getVerifySpec](#getverifyspec10) to obtain the parameters.
Currently, only the RSA is supported. For details, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +**System capability**: SystemCapability.Security.CryptoFramework -**Error codes** +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| PSS_MD_NAME_STR | 100 | Name of the message digest algorithm when the PSS padding mode is used in the RSA.| +| PSS_MGF_NAME_STR | 101 | Mask generation algorithm when the PSS padding mode is used in the RSA. Currently, only MGF1 is supported.| +| PSS_MGF1_MD_STR | 102 | Message digest parameters for the MGF1 mask generation when the PSS padding mode is used in the RSA.| +| PSS_SALT_LEN_NUM | 103 | Length of the salt in bytes when the PSS padding mode is used in the RSA.| +| PSS_TRAILER_FIELD_NUM | 104 | Integer used for encoding when the PSS padding mode is used in the RSA. The value is **1**.| -| ID| Error Message | -| -------- | ---------------------- | -| 17630001 | crypto operation error. | +## AsyKeySpec10+ -**Example** +Defines the asymmetric key parameters for creating a key generator. You need to construct a child class object and pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. All the parameters of the bigint type in the child class object must be integers in big-endian format. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +**System capability**: SystemCapability.Security.CryptoFramework -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Mac algName is: " + mac.algName); +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Yes | Algorithm of the asymmetric key pair, for example, **RSA**, **DSA**, or **ECC**.| +| specType | [AsyKeySpecType](#asykeyspectype10) | Yes | Yes| Key parameter type, which is used to distinguish public and private key parameters.| -var KeyBlob; -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); -promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); - return promiseMacInit; -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); +## DSACommonParamsSpec10+ -``` +Defines the common parameters contained in the public and private keys in the DSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10) and can be used to randomly generate public or private keys.
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -### update +**System capability**: SystemCapability.Security.CryptoFramework -update(input : DataBlob, callback : AsyncCallback\) : void; +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| p | bigint | Yes | Yes | Prime modulus **p** in the DSA algorithm.| +| q | bigint | Yes | Yes | Parameter **q** (prime factor of **p** – 1) in the DSA algorithm.| +| g | bigint | Yes | Yes | Parameter **g** in the DSA algorithm.| -Updates the MAC computation data. This API uses an asynchronous callback to return the result. +## DSAPubKeySpec10+ -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating a MAC](../../security/cryptoFramework-guidelines.md#generating-a-mac). +Defines the parameters contained in the public key in the DSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the DSA algorithm.| +| pk | bigint | Yes | Yes | Public key of the DSA algorithm.| -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| input | [DataBlob](#datablob)| Yes | Data to pass in.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +## DSAKeyPairSpec10+ -**Error codes** +Defines full parameters contained in the public and private keys in the DSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -| ID| Error Message | -| -------- | ---------------------- | -| 17630001 | crypto operation error. | +**System capability**: SystemCapability.Security.CryptoFramework -**Example** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [DSACommonParamsSpec](#dsacommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the DSA algorithm.| +| sk | bigint | Yes | Yes | Private key **sk** in the DSA algorithm.| +| pk | bigint | Yes | Yes | Public key **pk** in the DSA algorithm.| -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +## ECField10+ -var KeyBlob; -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { - if (err) { - console.error("[Callback] err: " + err.code); - } - mac.init(symKey, (err1, ) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } - let blob; - mac.update(blob, (err2, data) => { - if (err2) { - console.error("[Callback] err: " + err2.code); - } - }); - }); -}); -``` +Defines the elliptic curve field. Currently, only the **Fp** field is supported. -### update +**System capability**: SystemCapability.Security.CryptoFramework -update(input : DataBlob) : Promise\; +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| fieldType | string | Yes | Yes | Type of the elliptic curve field. Currently, only **Fp** is supported.| -Updates the MAC computation data. This API uses a promise to return the result. +## ECFieldFp10+ -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating a MAC](../../security/cryptoFramework-guidelines.md#generating-a-mac). +Defines the prime field of the elliptic curve. It is a child class of [ECField](#ecfield10). **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| p | bigint | Yes | Yes | Prime **p**.| -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| input | [DataBlob](#datablob) | Yes | Data to pass in.| +## Point10+ -**Return value** +Defines a point on the elliptic curve. -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +**System capability**: SystemCapability.Security.CryptoFramework -**Error codes** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| x | bigint | Yes | Yes | X coordinate of the point on an elliptic curve.| +| y | bigint | Yes | Yes | Y coordinate of the point on an elliptic curve.| -| ID| Error Message | -| -------- | ---------------------- | -| 17630001 | crypto operation error. | +## ECCCommonParamsSpec10+ -**Example** +Defines the common parameters contained in the public and private keys in the ECC algorithm. It is a child class of [AsyKeySpec](#asykeyspec10) and can be used to randomly generate public or private keys.
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +**System capability**: SystemCapability.Security.CryptoFramework -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Mac algName is: " + mac.algName); +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| field | [ECField](#ecfield10) | Yes | Yes | Field of the elliptic curve. Currently, only the **Fp** field is supported.| +| a | bigint | Yes | Yes | First coefficient **a** of the elliptic curve.| +| b | bigint | Yes | Yes | Second coefficient **b** of the elliptic curve.| +| g | [Point](#point10) | Yes | Yes | Base point g.| +| n | bigint | Yes | Yes | Order **n** of the base point **g**.| +| h | number | Yes | Yes | Cofactor **h**.| -var KeyBlob; -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); -promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); - return promiseMacInit; -}).then(() => { - let blob; - var promiseMacUpdate = mac.update(blob); - return promiseMacUpdate; -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); +## ECCPriKeySpec10+ -``` +Defines the parameters contained in the private key in the ECC algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -### doFinal +**System capability**: SystemCapability.Security.CryptoFramework -doFinal(callback : AsyncCallback\) : void; +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the ECC algorithm.| +| sk | bigint | Yes | Yes | Private key **sk** in the ECC algorithm.| -Finalizes the MAC computation. This API uses an asynchronous callback to return the result. +## ECCPubKeySpec10+ + +Defines the parameters contained in the public key in the ECC algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the ECC algorithm.| +| pk | [Point](#point10) | Yes | Yes | Public key **pk** in the ECC algorithm.| -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | -------- | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result.| +## ECCKeyPairSpec10+ -**Error codes** +Defines full parameters contained in the public and private keys in the ECC algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | +**System capability**: SystemCapability.Security.CryptoFramework -**Example** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [ECCCommonParamsSpec](#ecccommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the ECC algorithm.| +| sk | bigint | Yes | Yes | Private key **sk** in the ECC algorithm.| +| pk | [Point](#point10) | Yes | Yes | Public key **pk** in the ECC algorithm.| -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +## RSACommonParamsSpec10+ -var KeyBlob; -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { - if (err) { - console.error("[Callback] err: " + err.code); - } - mac.init(symKey, (err1, ) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } - let blob; - mac.update(blob, (err2, ) => { - if (err2) { - console.error("[Callback] err: " + err2.code); - } - mac.doFinal((err3, macOutput) => { - if (err3) { - console.error("[Callback] err: " + err3.code); - } else { - console.error("[Promise]: HMAC result: " + macOutput); - } - }); - }); - }); -}); -``` +Defines the common parameters contained in the public and private keys in the RSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10) and can be used to randomly generate public or private keys.
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -### doFinal +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| n | bigint | Yes | Yes | Modulus **n**.| -doFinal() : Promise\ +## RSAPubKeySpec10+ -Finalizes the MAC computation. This API uses a promise to return the result. +Defines the parameters contained in the public key in the RSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. **System capability**: SystemCapability.Security.CryptoFramework -**Return value** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the RSA algorithm.| +| pk | bigint | Yes | Yes | Public key **pk** in the RSA algorithm.| -| Type | Description | -| ------------------ | ----------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +## RSAKeyPairSpec10+ -**Error codes** +Defines full parameters contained in the public and private keys in the RSA algorithm. It is a child class of [AsyKeySpec](#asykeyspec10).
When key parameters are used to generate a key, you can pass it to [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create a key generator. -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | +**System capability**: SystemCapability.Security.CryptoFramework -**Example** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| params | [RSACommonParamsSpec](#rsacommonparamsspec10) | Yes | Yes | Common parameters contained in both public and private keys in the RSA algorithm.| +| sk | bigint | Yes | Yes | Private key **sk** in the RSA algorithm.| +| pk | bigint | Yes | Yes | Public key **pk** in the RSA algorithm.| -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +## Key -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Mac algName is: " + mac.algName); +Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance.
Keys can be generated by a key generator. -var KeyBlob; -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); -promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); - return promiseMacInit; -}).then(() => { - let blob; - var promiseMacUpdate = mac.update(blob); - return promiseMacUpdate; -}).then(() => { - var PromiseMacDoFinal = mac.doFinal(); - return PromiseMacDoFinal; -}).then(macOutput => { - console.error("[Promise]: HMAC result: " + macOutput.data); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); -``` +### Attributes -### getMacLength +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | +| algName | string | Yes | No | Algorithm name (including the key length).| -getMacLength() : number +### getEncoded -Obtains the MAC length, in bytes. +getEncoded(): DataBlob + +Obtains the byte stream of the key data synchronously. The key can be a symmetric key, public key, or private key. The public key must be in DER encoding format and comply with the ASN.1 syntax and X.509 specifications. The private key must be in DER encoding format and comply with the ASN.1 syntax and PKCS#8 specifications. + +> **NOTE** +> +> When key parameters are used to generate an RSA private key, the private key object does not support **getEncoded()**. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| ------ | ------------------------- | -| number | MAC length obtained.| +| Type | Description | +| --------------------- | ------------------------ | +| [DataBlob](#datablob) | Key obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 801 | this operation is not supported. | +| 17620001 | memory error. | | 17630001 | crypto operation error. | **Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" - -var mac; -try { - mac = cryptoFramework.createMac("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); } -console.error("Mac algName is: " + mac.algName); -var KeyBlob; -var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); -var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); -promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); - return promiseMacInit; -}).then(() => { - let blob; - var promiseMacUpdate = mac.update(blob); - return promiseMacUpdate; -}).then(() => { - var PromiseMacDoFinal = mac.doFinal(); - return PromiseMacDoFinal; -}).then(macOutput => { - console.error("[Promise]: HMAC result: " + macOutput.data); - let macLen = mac.getMacLength(); - console.error("MAC len: " + macLen); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); +let key; // The key is generated by a key generator. The generation process is omitted here. +let encodedKey = key.getEncoded(); +console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); ``` -## cryptoFramework.createMd - -createMd(algName : string) : Md - -Creates an **Md** instance for message digest operations. - -For details about the supported specifications, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications). - -**System capability**: SystemCapability.Security.CryptoFramework - -**Parameters** +## SymKey -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications).| +Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption.
Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). -**Return value** +### clearMem -| Type| Description | -| ---- | ------------------------------------- | -| Md | [Md](#md) instance created.| +clearMem(): void -**Error codes** +Clears the keys in the memory. This API returns the result synchronously. You are advised to use this API when symmetric key instances are no longer used. -| ID| Error Message | -| -------- | ------------------ | -| 17620001 | memory error. | +**System capability**: SystemCapability.Security.CryptoFramework **Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" - -var md; -try { - // Set algName based on the algorithm supported. - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); } + +let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. +let encodedKey = key.getEncoded(); +console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content. +key.clearMem(); +encodedKey = key.getEncoded(); +console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display all 0s. ``` -## Md +## PubKey -Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd). +Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
The public key can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | -------------------- | -| algName | string | Yes | No | Digest algorithm.| - -### update +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | +| algName | string | Yes | No | Algorithm name (including the key length).| -update(input : DataBlob, callback : AsyncCallback\) : void; +### getAsyKeySpec10+ -Updates the message digest data. This API uses an asynchronous callback to return the result. +getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating a Digest](../../security/cryptoFramework-guidelines.md#generating-a-digest). +Obtains a key parameter synchronously. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| input | [DataBlob](#datablob)| Yes | Data to pass in.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| item | [AsyKeySpecItem](#asykeyspecitem10) | Yes | Key parameter to obtain.| + +**Return value** + +| Type | Description | +| --------------------------- | --------------------------------- | +| bigint\|string\|number | Content of the key parameter obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | | 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +let key; // key is a public key object. The generation process is omitted here. +let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); +console.info("ecc item --- p: " + p.toString(16)); +``` -var md; -try { - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Md algName is: " + md.algName); +## PriKey -let blob; -md.update(blob, (err,) => { - if (err) { - console.error("[Callback] err: " + err.code); - } -}); -``` +Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signing, and key agreement.
The public key can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). -### update +### Attributes -update(input : DataBlob) : Promise\; +**System capability**: SystemCapability.Security.CryptoFramework -Updates the message digest data. This API uses a promise to return the result. +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | +| algName | string | Yes | No | Algorithm name (including the key length).| -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating a Digest](../../security/cryptoFramework-guidelines.md#generating-a-digest). +### clearMem + +clearMem(): void + +Clears the keys in the memory. This API returns the result synchronously. **System capability**: SystemCapability.Security.CryptoFramework -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| input | DataBlob | Yes | Data to pass in.| +**Example** + +```js +let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. +key.clearMem(); +``` + +### getAsyKeySpec10+ + +getAsyKeySpec(itemType: AsyKeySpecItem): bigint | string | number + +Obtains a key parameter synchronously. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| item | [AsyKeySpecItem](#asykeyspecitem10) | Yes | Key parameter to obtain.| **Return value** -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| --------------------------- | --------------------------------- | +| bigint\|string\|number | Content of the key parameter obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | | 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +let key; // key is a private key object. The generation process is omitted here. +let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); +console.info("ecc item --- p: " + p.toString(16)); +``` -var md; -try { - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Md algName is: " + md.algName); - -let blob; -var promiseMdUpdate = md.update(blob); -promiseMdUpdate.then(() => { - // do something -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); -``` +## KeyPair -### digest +Defines an asymmetric key pair, which includes a public key and a private key.
The asymmetric key pair can be generated by using the asymmetric key generator [AsyKeyGenerator](#asykeygenerator) or [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10). -digest(callback : AsyncCallback\) : void +> **NOTE** +> +> The **pubKey** and **priKey** objects in the **KeyPair** object exist as one parameter in the **KeyPair** object. When **KeyPair** leaves the scope, its internal objects can be destructed. +> +> The service must reference the **KeyPair** object instead of the internal **pubKey** or **priKey** object. -Generates a message digest. This API uses an asynchronous callback to return the result. +### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | -------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| - -**Error codes** - -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | - -**Example** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------ | +| priKey | [PriKey](#prikey) | Yes | No | Private key. | +| pubKey | [PubKey](#pubkey) | Yes | No | Public key. | -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" -var md; -try { - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Md algName is: " + md.algName); +## cryptoFramework.createSymKeyGenerator -let blob; -md.update(blob, (err,) => { - if (err) { - console.error("[Callback] err: " + err.code); - } - md.digest((err1, mdOutput) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } else { - console.error("[Callback]: MD result: " + mdOutput); - } - }); -}); -``` +createSymKeyGenerator(algName: string): SymKeyGenerator -### digest +Creates a **symKeyGenerator** instance based on the specified algorithm.
For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). -digest() : Promise\ +**System capability**: SystemCapability.Security.CryptoFramework -Generates a message digest. This API uses a promise to return the result. +**Parameters** -**System capability**: SystemCapability.Security.CryptoFramework +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.
For details, see "String Parameter" in [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications).| **Return value** -| Type | Description | -| ------------------ | ----------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| - -**Error codes** +| Type | Description | +| ----------------------------------- | -------------------------- | +| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.| | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); +``` -var md; -try { - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Md algName is: " + md.algName); +## SymKeyGenerator -let blob; -var promiseMdUpdate = md.update(blob); -promiseMdUpdate.then(() => { - var PromiseMdDigest = md.digest(); - return PromiseMdDigest; -}).then(mdOutput => { - console.error("[Promise]: MD result: " + mdOutput.data); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); -``` +Provides APIs for using the **symKeyGenerator**.
Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). -### getMdLength +### Attributes -getMdLength() : number +**System capability**: SystemCapability.Security.CryptoFramework -Obtains the message digest length, in bytes. +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------ | +| algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.| + +### generateSymKey + +generateSymKey(callback: AsyncCallback\): void + +Generates a key randomly. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework -**Return value** +**Parameters** -| Type | Description | -| ------ | ------------------------ | -| number | Message digest length obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | ------------- | +| 17620001 | memory error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -var md; -try { - md = cryptoFramework.createMd("SHA256"); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} -console.error("Md algName is: " + md.algName); - -let blob; -var promiseMdUpdate = md.update(blob); -promiseMdUpdate.then(() => { - var PromiseMdDigest = md.digest(); - return PromiseMdDigest; -}).then(mdOutput => { - console.error("[Promise]: MD result: " + mdOutput.data); - let mdLen = md.getMdLength(); - console.error("MD len: " + mdLen); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; +let symAlgName = '3DES192'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); +symKeyGenerator.generateSymKey((err, symKey) => { + if (err) { + console.error(`Generate symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Generate symKey success, algName: ${symKey.algName}`); + } +}) ``` -## cryptoFramework.createRandom +### generateSymKey -createRandom() : Random +generateSymKey(): Promise\ -Creates a **Random** instance for generating a random number and setting a seed. +Generates a key randomly. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| ------ | --------------------------------------------- | -| Random | [Random](#random) instance created.| +| Type | Description | +| --------------------------- | --------------------------------- | +| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| **Error codes** -| ID| Error Message | -| -------- | ------------ | +| ID| Error Message | +| -------- | ------------- | | 17620001 | memory error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -try { - var rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; +let symAlgName = 'AES128'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); +symKeyGenerator.generateSymKey() +.then(symKey => { + console.info(`Generate symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Generate symKey failed, ${error.code}, ${error.message}`); +}) ``` -## Random - -Provides APIs for computing random numbers and setting seeds. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). - -### generateRandom +### convertKey -generateRandom(len : number, callback: AsyncCallback\) : void; +convertKey(key: DataBlob, callback: AsyncCallback\): void -Generates a random number of the given length. This API uses an asynchronous callback to return the result. +Converts data into a symmetric key. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | -------------------- | -| len | number | Yes | Length of the random number to generate.| -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| key | [DataBlob](#datablob) | Yes | Data to convert. | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | --------------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -var rand; -try { - rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +function genKeyMaterialBlob() { + let arr = [ + 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, + 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, + 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) + let keyMaterial = new Uint8Array(arr); + return {data: keyMaterial}; } -rand.generateRandom(12, (err, randData) => { - if (err) { - console.error("[Callback] err: " + err.code); - } else { - console.error("[Callback]: generate random result: " + randData.data); - } -}); + +let symAlgName = '3DES192'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); +let keyMaterialBlob = genKeyMaterialBlob(); +symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { + if (err) { + console.error(`Convert symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Convert symKey success, algName: ${symKey.algName}`); + } +}) ``` -### generateRandom +### convertKey -generateRandom(len : number) : Promise\; +convertKey(key: DataBlob): Promise\ -Generates a random number of the given length. This API uses a promise to return the result. +Converts data into a symmetric key. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------- | -| len | number | Yes | Length of the random number to generate.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| key | [DataBlob](#datablob) | Yes | Data to convert.| **Return value** -| Type | Description | -| ------------------ | ----------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +| Type | Description | +| --------------------------- | --------------------------------- | +| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | --------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -var rand; -try { - rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +function genKeyMaterialBlob() { + let arr = [ + 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, + 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, + 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) + let keyMaterial = new Uint8Array(arr); + return {data: keyMaterial}; } -var promiseGenerateRand = rand.generateRandom(12); -promiseGenerateRand.then(randData => { - console.error("[Promise]: rand result: " + randData.data); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); +let symAlgName = '3DES192'; +let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); +let keyMaterialBlob = genKeyMaterialBlob(); +symKeyGenerator.convertKey(keyMaterialBlob) +.then(symKey => { + console.info(`Convert symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Convert symKey failed, ${error.code}, ${error.message}`); +}) ``` -### setSeed +## cryptoFramework.createAsyKeyGenerator -setSeed(seed : DataBlob) : void; +createAsyKeyGenerator(algName: string): AsyKeyGenerator -Sets a seed. This API uses an asynchronous callback to return the result. +Creates an **AsyKeyGenerator** instance based on the specified algorithm.
For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ---------- | -| seed | DataBlob | Yes | Seed to set.| +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | -------------------------------- | +| algName | string | Yes | Algorithm used to create the **symkeyGenerator**.| + +**Return value** + +| Type | Description | +| --------------- | ---------------------------- | +| [AsyKeyGenerator](#asykeygenerator) | **AsyKeyGenerator** instance created.| **Error codes** -| ID| Error Message | -| -------- | ----------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | **Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -var rand; -try { - rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} - -rand.generateRandom(12, (err, randData) => { - if (err) { - console.error("[Callback] err: " + err.code); - } else { - console.error("[Callback]: generate random result: " + randData.data); - try { - rand.setSeed(randData); - } catch (error) { - console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); - } - } -}); +let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); ``` -## ParamsSpec +## AsyKeyGenerator -Defines the parameters used for encryption and decryption. +Provides APIs for using the **AsKeyGenerator**. Before using any API of the **AsKeyGenerator** class, you must create an **AsyKeyGenerator** instance by using **createAsyKeyGenerator()**. -For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you must construct a child class object and pass it to [init()](#init-2). If no IV is required (for example, the ECB mode is used), pass in **null** in [init()](#init-2). +### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Yes | Symmetric encryption and decryption parameters. Options:
- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode.| - -> **NOTE**
-> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class), but a child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, set **algName** in the parent class **ParamsSpec** to let the algorithm library know the type of child class object to pass in in **init()**. +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------------- | +| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.| -## IvParamsSpec +### generateKeyPair -Defines the child class of [ParamsSpec](#paramsspec). It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. +generateKeyPair(callback: AsyncCallback\): void -**IvParamsSpec** applies to the encryption and decryption modes such as CBC, CTR, OFB, and CFB, which use only the IV. +Generates a key pair randomly. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name| Type | Readable| Writable| Description | -| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | -| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. Options:
- AES CBC, CTR, OFB, or CFB mode: 16-byte IV
- 3DES CBC, OFB, or CFB mode: 8-byte IV| - -> **NOTE**
-> Before passing **IvParamsSpec** to [init()](#init-2), specify **algName** in its parent class [ParamsSpec](#paramsspec). +**Parameters** -## GcmParamsSpec +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| -Defines the child class of [ParamsSpec](#paramsspec) for the GCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. +**Error codes** -**GcmParamsSpec** applies to the GCM mode. +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | -**System capability**: SystemCapability.Security.CryptoFramework +**Example** -| Name | Type | Readable| Writable| Description | -| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | -| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes. | -| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes. | -| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.
When the GCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 16 bytes of [DataBlob](#datablob) are used as as **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2). | +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -> **NOTE** -> Before passing **GcmParamsSpec** to [init()](#init-2), specify **algName** in its parent class [ParamsSpec](#paramsspec). +let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +asyKeyGenerator.generateKeyPair((err, keyPair) => { + if (err) { + console.error("generateKeyPair: error."); + return; + } + console.info("generateKeyPair: success."); +}) +``` -## CcmParamsSpec +### generateKeyPair -Defines the child class of [ParamsSpec](#paramsspec) for the CCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption. +generateKeyPair(): Promise\ -**CcmParamsSpec** applies to the CCM mode. +Generates a key pair randomly. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | -| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. | -| aad | [DataBlob](#datablob) | Yes | Yes | AAD, which is of 8 bytes. | -| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.
When the CCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 12 bytes of [DataBlob](#datablob) are used as as **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).| - -> **NOTE** -> Before passing **CcmParamsSpec** to [init()](#init-2), specify **algName** in its parent class [ParamsSpec](#paramsspec). - -## CryptoMode +**Return value** -Enumerates the cryptographic operations. +| Type | Description | +| ----------------- | --------------------------------- | +| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| -**System capability**: SystemCapability.Security.CryptoFramework +**Error codes** -| Name | Value | Description | -| ------------ | ---- | ---------------- | -| ENCRYPT_MODE | 0 | Encryption.| -| DECRYPT_MODE | 1 | Decryption.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | -## Key +**Example** -Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance.
Keys can be generated by a key generator. +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -### Attributes +let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +let keyGenPromise = asyKeyGenerator.generateKeyPair(); +keyGenPromise.then( keyPair => { + console.info("generateKeyPair success."); +}).catch(error => { + console.error("generateKeyPair error."); +}); +``` -**System capability**: SystemCapability.Security.CryptoFramework +### convertKey -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| format | string | Yes | No | Format of the key. | -| algName | string | Yes | No | Algorithm name (including the key length).| +convertKey(pubKey: DataBlob, priKey: DataBlob, callback: AsyncCallback\): void -### getEncoded +Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. -getEncoded() : DataBlob +**System capability**: SystemCapability.Security.CryptoFramework -Obtains a key in hexadecimal format. This API returns the result synchronously. +**Parameters** -**System capability**: SystemCapability.Security.CryptoFramework +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------ | +| pubKey | [DataBlob](#datablob) | Yes | Public key material to convert. If no public key is required, set this parameter to **null**. | +| priKey | [DataBlob](#datablob) | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. | +| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| -**Return value** +**Error codes** -| Type | Description | -| --------------------- | ------------------------ | -| [DataBlob](#datablob) | Key obtained.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js import cryptoFramework from "@ohos.security.cryptoFramework" -function uint8ArrayToShowStr(uint8Array) { - return Array.prototype.map - .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) - .join(''); -} -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. -let encodedKey = key.getEncoded(); -console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); +let pubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,83,96,142,9,86,214,126,106,247,233,92,125,4,128,138,105,246,162,215,71,81,58,202,121,26,105,211,55,130,45,236,143,55,16,248,75,167,160,167,106,2,152,243,44,68,66,0,167,99,92,235,215,159,239,28,106,124,171,34,145,124,174,57,92]); +let priKeyArray = new Uint8Array([48,49,2,1,1,4,32,115,56,137,35,207,0,60,191,90,61,136,105,210,16,27,4,171,57,10,61,123,40,189,28,34,207,236,22,45,223,10,189,160,10,6,8,42,134,72,206,61,3,1,7]); +let pubKeyBlob = {data: pubKeyArray}; // Data of the public key. +let priKeyBlob = {data: priKeyArray}; // Data of the private key. +let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob, (err, keyPair) => { + if (err) { + console.error("convertKey: error."); + return; + } + console.info("convertKey: success."); +}) ``` -## SymKey +### convertKey -Provides APIs for symmetric key operations. **SymKey** is a child class of [Key](#key), and its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption. +convertKey(pubKey: DataBlob, priKey: DataBlob): Promise\ -Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). +Converts data into an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. -### clearMem +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** -clearMem() : void +| Name | Type | Mandatory| Description | +| ------ | -------- | ---- | ---------------- | +| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| +| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**.| -Clears the keys in the memory. This API returns the result synchronously. You are advised to use this API when symmetric key instances are no longer used. +**Return value** -**System capability**: SystemCapability.Security.CryptoFramework +| Type | Description | +| ----------------- | --------------------------------- | +| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js import cryptoFramework from "@ohos.security.cryptoFramework" -function uint8ArrayToShowStr(uint8Array) { - return Array.prototype.map - .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) - .join(''); -} -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. -let encodedKey = key.getEncoded(); -console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Key content is displayed. -key.clearMem(); -encodedKey = key.getEncoded(); -console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // All 0s are displayed. +let pubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,83,96,142,9,86,214,126,106,247,233,92,125,4,128,138,105,246,162,215,71,81,58,202,121,26,105,211,55,130,45,236,143,55,16,248,75,167,160,167,106,2,152,243,44,68,66,0,167,99,92,235,215,159,239,28,106,124,171,34,145,124,174,57,92]); +let priKeyArray = new Uint8Array([48,49,2,1,1,4,32,115,56,137,35,207,0,60,191,90,61,136,105,210,16,27,4,171,57,10,61,123,40,189,28,34,207,236,22,45,223,10,189,160,10,6,8,42,134,72,206,61,3,1,7]); +let pubKeyBlob = {data: pubKeyArray}; // Data of the public key. +let priKeyBlob = {data: priKeyArray}; // Data of the private key. +let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +let keyGenPromise = asyKeyGenerator.convertKey(pubKeyBlob, priKeyBlob); +keyGenPromise.then( keyPair => { + console.info("convertKey success."); +}).catch(error => { + console.error("convertKey error."); +}); ``` -## PubKey - -Provides APIs for public key operations. **PubKey** is a child class of [Key](#key), and its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. +**Key Conversion** -Public keys can be generated by an **AsyKeyGenerator**. +1. After **getEncoded()** is called for the asymmetric (RSA, ECC, or DSA) public and private keys, binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The binary data can be used for cross-application transfer or persistent storage. +2. The public key returned by **convertKey()** must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. +3. In **convertKey()**, you can pass in either **pubKey** or **priKey**, or both of them. If one of them is passed in, the returned **KeyPair** instance contains only the key converted from the data you passed in. -### Attributes +## cryptoFramework.createAsyKeyGeneratorBySpec10+ -**System capability**: SystemCapability.Security.CryptoFramework +createAsyKeyGeneratorBySpec(asyKeySpec: AsyKeySpec): AsyKeyGeneratorBySpec -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| format | string | Yes | No | Format of the key. | -| algName | string | Yes | No | Algorithm name (including the key length).| +Creates an **AsyKeyGenerator** instance based on the key parameters.
For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). +**System capability**: SystemCapability.Security.CryptoFramework -### getEncoded +**Parameters** -getEncoded() : DataBlob +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | -------------------------------- | +| asyKeySpec | [AsyKeySpec](#asykeyspec10) | Yes | Key parameters. The **AsyKeyGenerator** generates the public/private key based on the specified parameters.| -Obtains a key in binary format. This API returns the result synchronously. The public key format must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format. +**Return value** -**System capability**: SystemCapability.Security.CryptoFramework +| Type | Description | +| ----------------------------------------------- | -------------------------- | +| [AsyKeyGeneratorBySpec](#asykeygeneratorbyspec10) | Returns the **AsyKeyGenerator** instance created.| -**Return value** +**Error codes** -| Type | Description | -| --------------------- | ------------------------ | -| [DataBlob](#datablob) | Key obtained.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | **Example** ```js -function uint8ArrayToShowStr(uint8Array) { - return Array.prototype.map - .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) - .join(''); +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Set the common parameters contained in both the DSA1024 public and private keys. +function genDsa1024CommonSpecBigE() { + let dsaCommonSpec = { + algName : "DSA", + specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC, + p : BigInt("0xed1501551b8ab3547f6355ffdc2913856ddeca198833dbd04f020e5f25e47c50e0b3894f7690a0d2ea5ed3a7be25c54292a698e1f086eb3a97deb4dbf04fcad2dafd94a9f35c3ae338ab35477e16981ded6a5b13d5ff20bf55f1b262303ad3a80af71aa6aa2354d20e9c82647664bdb6b333b7bea0a5f49d55ca40bc312a1729"), + q : BigInt("0xd23304044019d5d382cfeabf351636c7ab219694ac845051f60b047b"), + g : BigInt("0x2cc266d8bd33c3009bd67f285a257ba74f0c3a7e12b722864632a0ac3f2c17c91c2f3f67eb2d57071ef47aaa8f8e17a21ad2c1072ee1ce281362aad01dcbcd3876455cd17e1dd55d4ed36fa011db40f0bbb8cba01d066f392b5eaa9404bfcb775f2196a6bc20eeec3db32d54e94d87ecdb7a0310a5a017c5cdb8ac78597778bd"), + } + return dsaCommonSpec; +} +// Set full parameters contained in the DSA1024 public and private keys. +function genDsa1024KeyPairSpecBigE() { + let dsaCommonSpec = genDsa1024CommonSpecBigE(); + let dsaKeyPairSpec = { + algName : "DSA", + specType : cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC, + params : dsaCommonSpec, + sk : BigInt("0xa2dd2adb2d11392c2541930f61f1165c370aabd2d78d00342e0a2fd9"), + pk : BigInt("0xae6b5d5042e758f3fc9a02d009d896df115811a75b5f7b382d8526270dbb3c029403fafb8573ba4ef0314ea86f09d01e82a14d1ebb67b0c331f41049bd6b1842658b0592e706a5e4d20c14b67977e17df7bdd464cce14b5f13bae6607760fcdf394e0b73ac70aaf141fa4dafd736bd0364b1d6e6c0d7683a5de6b9221e7f2d6b"), + } + return dsaKeyPairSpec; } -let key; // The key is a public key generated by the asymmetric key generator. The generation process is omitted here. -console.info("key format:" + key.format); -console.info("key algName:" + key.algName); -var encodedKey = key.getEncoded(); -console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); +let asyKeyPairSpec = genDsa1024KeyPairSpecBigE(); // The JS input must be a positive number in big-endian format. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); ``` -## PriKey - -Provides APIs for private key operations. **PriKey** is a child class of [Key](#key), and its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. +## AsyKeyGeneratorBySpec10+ -Private keys can be generated by an **AsyKeyGenerator**. +Provides APIs for using the **AsKeyGenerator**. Before using the APIs of this class, you need to use [createAsyKeyGeneratorBySpec()](#cryptoframeworkcreateasykeygeneratorbyspec10) to create an **AsyKeyGeneratorBySpec** instance. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| format | string | Yes | No | Format of the key. | -| algName | string | Yes | No | Algorithm name (including the key length).| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------- | +| algName | string | Yes | No | Algorithm used by the asymmetric key generator.| -### getEncoded +### generateKeyPair -getEncoded() : DataBlob +generateKeyPair(callback: AsyncCallback\): void -Obtains a key in binary format. This API returns the result synchronously. The private key format must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding mode. +Generates an asymmetric key pair. This API uses an asynchronous callback to return the result. When you use key parameters of the **COMMON_PARAMS_SPEC** type to create the key generator, you can obtain a key pair randomly generated. When you use **KEY_PAIR_SPEC** to create the key generator, you can obtain a key pair that matches the key parameters. **System capability**: SystemCapability.Security.CryptoFramework -**Return value** +**Parameters** -| Type | Description | -| --------------------- | ------------------------ | -| [DataBlob](#datablob) | Key obtained.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js -function uint8ArrayToShowStr(uint8Array) { - return Array.prototype.map - .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) - .join(''); -} +import cryptoFramework from "@ohos.security.cryptoFramework" -let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. -console.info("key format:" + key.format); -console.info("key algName:" + key.algName); -var encodedKey = key.getEncoded(); -console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +asyKeyGeneratorBySpec.generateKeyPair((err, keyPair) => { + if (err) { + console.error("generateKeyPair: error."); + return; + } + console.info("generateKeyPair: success."); +}) ``` -### clearMem +### generateKeyPair -clearMem() : void +generateKeyPair(): Promise\ -Clears the keys in the memory. This API returns the result synchronously. +Generates an asymmetric key pair. This API uses a promise to return the result. When you use key parameters of the **COMMON_PARAMS_SPEC** type to create the key generator, you can obtain a key pair randomly generated. When you use **KEY_PAIR_SPEC** to create the key generator, you can obtain a key pair that matches the key parameters. **System capability**: SystemCapability.Security.CryptoFramework -**Example** - -```js -let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. -key.clearMem(); -``` - -## KeyPair - -Defines an asymmetric key pair, which includes a public key and a private key. - -Asymmetric key pairs can be generated by an **AsyKeyGenerator**. +**Return value** -> **NOTE** -> -> The **pubKey** and **priKey** objects in the **KeyPair** object are defined as one parameter in **KeyPair**. When **KeyPair** leaves the scope, its internal objects may be destructed.
The service must reference the **KeyPair** object instead of the **pubKey** or **priKey** object. +| Type | Description | +| ----------------- | --------------------------------- | +| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| -### Attributes +**Error codes** -**System capability**: SystemCapability.Security.CryptoFramework +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ------------ | -| priKey | [PriKey](#prikey) | Yes | No | Private key. | -| pubKey | [PubKey](#pubkey) | Yes | No | Public key. | +**Example** +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -## cryptoFramework.createSymKeyGenerator +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +let keyGenPromise = asyKeyGeneratorBySpec.generateKeyPair(); +keyGenPromise.then( keyPair => { + console.info("generateKeyPair success."); +}).catch(error => { + console.error("generateKeyPair error."); +}); +``` -createSymKeyGenerator(algName : string) : SymKeyGenerator +### generatePriKey -Creates a **symKeyGenerator** instance based on the specified algorithm. +generatePriKey(callback: AsyncCallback\): void -For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). +Generates a private key. This API uses an asynchronous callback to return the result. If you use key parameters of the **PRIVATE_KEY_SPEC** type to create the key generator, you can obtain the specified private key. If you use **KEY_PAIR_SPEC** to create the key generator, you can obtain the private key from the generated key pair. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.
For details, see "String Parameter" in [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\<[PriKey](#prikey)> | Yes | Callback invoked to return the key pair obtained.| -**Return value** +**Error codes** -| Type | Description | -| ----------------------------------- | -------------------------- | -| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); -``` +import cryptoFramework from "@ohos.security.cryptoFramework" -## SymKeyGenerator +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +asyKeyGeneratorBySpec.generatePriKey((err, prikey) => { + if (err) { + console.error("generatePriKey: error."); + return; + } + console.info("generatePriKey: success."); +}) +``` -Provides APIs for using the **symKeyGenerator**. +### generatePriKey -Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +generatePriKey(): Promise\ -### Attributes +Generates a private key. This API uses a promise to return the result. If you use key parameters of the **PRIVATE_KEY_SPEC** type to create the key generator, you can obtain the specified private key. If you use **KEY_PAIR_SPEC** to create the key generator, you can obtain the private key from the generated key pair. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ------------------------------ | -| algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.| +**Return value** -### generateSymKey +| Type | Description | +| ----------------- | --------------------------------- | +| Promise\<[PriKey](#prikey)> | Promise used to return the key generated.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | + +**Example** -generateSymKey(callback : AsyncCallback\) : void +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +let keyGenPromise = asyKeyGeneratorBySpec.generatePriKey(); +keyGenPromise.then( priKey => { + console.info("generatePriKey success."); +}).catch(error => { + console.error("generatePriKey error."); +}); +``` -Generates a symmetric key randomly. This API uses an asynchronous callback to return the result. +### generatePubKey -This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +generatePubKey(callback: AsyncCallback\): void -**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. +Generates a public key. This API uses an asynchronous callback to return the result. If you use key parameters of the **PUBLIC_KEY_SPEC** type to create the key generator, you can obtain the specified public key. If you use **KEY_PAIR_SPEC** to create the key generator, you can obtain the public key from the generated key pair. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\<[PubKey](#pubkey)> | Yes | Callback invoked to return the key pair obtained.| **Error codes** -| ID| Error Message | -| -------- | ------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; -let symAlgName = '3DES192'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); -symKeyGenerator.generateSymKey((err, symKey) => { +import cryptoFramework from "@ohos.security.cryptoFramework" + +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +asyKeyGeneratorBySpec.generateKeyPair((err, pubKey) => { if (err) { - console.error(`Generate symKey failed, ${err.code}, ${err.message}`); - } else { - console.info(`Generate symKey success, algName: ${symKey.algName}`); + console.error("generatePubKey: error."); + return; } + console.info("generatePubKey: success."); }) ``` -### generateSymKey - -generateSymKey() : Promise\ +### generatePubKey -Generates a symmetric key randomly. This API uses a promise to return the result. +generatePubKey(): Promise\ -This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). - -**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. +Generates a public key. This API uses a promise to return the result. If you use key parameters of the **PUBLIC_KEY_SPEC** type to create the key generator, you can obtain the specified public key. If you use **KEY_PAIR_SPEC** to create the key generator, you can obtain the public key from the generated key pair. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| --------------------------- | --------------------------------- | -| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +| Type | Description | +| ----------------- | --------------------------------- | +| Promise\<[PubKey](#pubkey)> | Promise used to return the key pair generated.| **Error codes** -| ID| Error Message | -| -------- | ------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; -let symAlgName = 'AES128'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); -symKeyGenerator.generateSymKey() -.then(symKey => { - console.info(`Generate symKey success, algName: ${symKey.algName}`); -}, error => { - console.error(`Generate symKey failed, ${error.code}, ${error.message}`); -}) +import cryptoFramework from "@ohos.security.cryptoFramework" + +let asyKeyPairSpec; // asyKeyPairSpec specifies full parameters contained in the private and public keys. The generation process is omitted here. +let asyKeyGeneratorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(asyKeyPairSpec); +let keyGenPromise = asyKeyGeneratorBySpec.generatePubKey(); +keyGenPromise.then( pubKey => { + console.info("generatePubKey success."); +}).catch(error => { + console.error("generatePubKey error."); +}); ``` -### convertKey +## cryptoFramework.createCipher -convertKey(key : DataBlob, callback : AsyncCallback\) : void +createCipher(transformation: string): Cipher -Converts data into a symmetric key. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +Creates a [Cipher](#cipher) instance based on the specified algorithm.
For details about the supported specifications, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| key | [DataBlob](#datablob) | Yes | Data to convert. | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------------------------------ | +| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.
For details, see **String Parameter** in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications).| + +> **NOTE** +> +> 1. In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed.
You need to understand the differences between different block cipher modes and use the correct parameter specifications. For example, padding is required for ECB and CBC. Otherwise, ensure that the plaintext length is an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length. +> 2. If RSA is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. For symmetric encryption and decryption, one **cipher** object can be used to perform both encryption and decryption as long as the algorithm specifications are the same. + +**Return value** + +| Type | Description | +| ----------------- | ------------------------ | +| [Cipher](#cipher) | [Cipher](#cipher) instance created.| **Error codes** -| ID| Error Message | -| -------- | --------------------------------------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | **Example** ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; +import cryptoFramework from "@ohos.security.cryptoFramework" -function genKeyMaterialBlob() { - let arr = [ - 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, - 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, - 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) - let keyMaterial = new Uint8Array(arr); - return {data : keyMaterial}; +let cipherAlgName = '3DES192|ECB|PKCS7'; +var cipher; +try { + cipher = cryptoFramework.createCipher(cipherAlgName); + console.info(`cipher algName: ${cipher.algName}`); +} catch (error) { + console.error(`createCipher failed, ${error.code}, ${error.message}`); } - -let symAlgName = '3DES192'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); -let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { - if (err) { - console.error(`Convert symKey failed, ${err.code}, ${err.message}`); - } else { - console.info(`Convert symKey success, algName: ${symKey.algName}`); - } -}) ``` -### convertKey +## Cipher -convertKey(key : DataBlob) : Promise\ +Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption.
For details about the complete encryption and decryption process, see [Encryption and Decryption](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). -Converts data into a symmetric key. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process. + +- Symmetric encryption and decryption: **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data. After **doFinal()** is called to complete an encryption or decryption operation, **init()** can be called to start a new encryption or decryption operation. +- RSA asymmetric encryption and decryption: **init()** and **doFinal()** are mandatory, and **update()** is not supported. **doFinal()** can be called multiple times to encrypt or decrypt big data. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created. + +### Attributes **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** -| Name| Type | Mandatory| Description | -| ---- | --------------------- | ---- | -------------------- | -| key | [DataBlob](#datablob) | Yes | Data to convert.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm.| -**Return value** +### init -| Type | Description | -| --------------------------- | --------------------------------- | -| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +init(opMode: CryptoMode, key: Key, params: ParamsSpec, callback: AsyncCallback\): void + +Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result.
This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the initialization is successful, **err** is **undefined**. Otherwise, **err** is an error object. | **Error codes** -| ID| Error Message | -| -------- | --------------------------------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | --------------------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| **Example** ```js import cryptoFramework from '@ohos.security.cryptoFramework'; +let symKey; // The process of generating the symmetric key is omitted here. +let cipher; // The process of creating a Cipher instance is omitted here. -function genKeyMaterialBlob() { - let arr = [ - 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, - 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, - 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) - let keyMaterial = new Uint8Array(arr); - return {data : keyMaterial}; -} - -let symAlgName = '3DES192'; -let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); -let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterialBlob) -.then(symKey => { - console.info(`Convert symKey success, algName: ${symKey.algName}`); -}, error => { - console.error(`Convert symKey failed, ${error.code}, ${error.message}`); +cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { + if (err) { + console.error(`Failed to init cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Init cipher success`); + // Perform subsequent operations such as update. + } }) ``` -## cryptoFramework.createAsyKeyGenerator - -createAsyKeyGenerator(algName : string) : AsyKeyGenerator +### init -Creates an **AsyKeyGenerator** instance based on the specified algorithm. +init(opMode: CryptoMode, key: Key, params: ParamsSpec): Promise\ -For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). +Initializes a [cipher](#cipher) instance. This API uses a promise to return the result.
This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | -------------------------------- | -| algName | string | Yes | Algorithm used to create the **symkeyGenerator**.| +| Name | Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| **Return value** -| Type | Description | -| --------------- | ---------------------------- | -| [AsyKeyGenerator](#asykeygenerator) | **AsyKeyGenerator** instance created.| - -**Example** - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); -``` +| Type | Description | +| -------------- | -------------------------------------- | +| Promise\ | Promise that returns no value.| -## AsyKeyGenerator +**Error codes** -Provides APIs for using the **AsKeyGenerator**. Before using any API of the **AsKeyGenerator** class, you must create an **AsyKeyGenerator** instance by using **createAsyKeyGenerator()**. +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| -### Attributes +**Example** -**System capability**: SystemCapability.Security.CryptoFramework +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; +let symKey; // The process of generating the symmetric key is omitted here. +let cipher; // The process of creating a Cipher instance is omitted here. +cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null) +.then(() => { + console.info(`Init cipher success`); + // Perform subsequent operations such as update. +}, error => { + console.error(`Failed to init cipher, ${error.code}, ${error.message}`); +}) +``` -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | -------------------------------- | -| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.| +### update -### generateKeyPair +update(data: DataBlob, callback: AsyncCallback\): void -generateKeyPair(callback : AsyncCallback\) : void; +Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). -Generates a key pair randomly. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> 1. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> 2. **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt. +> The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> For details about the sample code for calling **update()** multiple times in AES, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). +> 3. RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------------ | -| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (empty)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**, and **data** is **DataBlob** (containing the encrypted or decrypted data). Otherwise, **err** is an error object.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); -asyKeyGenerator.generateKeyPair((err, keyPair) => { +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + +let cipher; // The process of creating a Cipher instance is omitted here. +// The init() process is omitted here. +let plainText = {data: stringToUint8Array('this is test!')}; +cipher.update(plainText, (err, output) => { // Example of the encryption process. if (err) { - console.error("generateKeyPair: error."); - return; + console.error(`Failed to update cipher`); + } else { + console.info(`Update cipher success`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). } - console.info("generateKeyPair: success."); }) ``` +### update -### generateKeyPair +update(data: DataBlob): Promise\ -generateKeyPair() : Promise\ +Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data. -Generates a key pair randomly. This API uses a promise to return the result. +This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). + +> **NOTE** +> +> 1. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> 2. **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt. +> The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> For details about the sample code for calling **update()** multiple times in AES, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). +> 3. RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (empty)}.| + **Return value** -| Type | Description | -| ----------------- | --------------------------------- | -| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair generated.| +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob** (containing the encrypted or decrypted data).| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); -let keyGenPromise = asyKeyGenerator.generateKeyPair(); -keyGenPromise.then( keyPair => { - console.info("generateKeyPair success."); -}).catch(error => { - console.error("generateKeyPair error."); -}); +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + +let cipher; // The process of creating a Cipher instance is omitted here. +// The init() process is omitted here. +let plainText = {data: stringToUint8Array('this is test!')}; +cipher.update(plainText) +.then((output) => { + console.info(`Update cipher success.`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). +}, error => { + console.info(`Update cipher failed.`); +}) ``` -### convertKey +### doFinal + +doFinal(data: DataBlob, callback: AsyncCallback\): void -convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void +(1) Encrypts or decrypts the remaining data (generated by the block cipher mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses an asynchronous callback to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. -Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For more information, see **Key Conversion**. +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. + +(2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses an asynchronous callback to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. + +> **NOTE** +> +> 1. In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> 2. If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. +> 3. The result of **doFinal()** may be **null**. To avoid exceptions, determine whether the result is **null** before using the **.data** field to access the **doFinal()** result. +> 4. For details about the sample code for calling **doFinal()** multiple times during RSA asymmetric encryption and decryption, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------- | ---- | ------------------------------ | -| pubKey | [DataBlob](#datablob) | Yes | Public key material to convert. If no public key is required, set this parameter to **null**. | -| priKey | [DataBlob](#datablob) | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. | -| callback | AsyncCallback\<[KeyPair](#keypair)> | Yes | Callback invoked to return the key pair obtained.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(empty)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the data is successfully encrypted or decrypted, **err** is **undefined**, and **data** is the **DataBlob** (encryption or decryption result of the remaining data). Otherwise, **err** is an error object.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ----------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" -let pubKey; // Public key data in DER format complying with X.509 specifications. The data is omitted here. -let priKey; // Private key data in DER format complying with PKCS#8 specifications. The data is omitted here. -let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); -asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; + +let cipher; // The process of creating a Cipher instance is omitted here. +let data; // The process of preparing the data to encrypt or decrypt is omitted here. +// The init() and update() processes are omitted here. +cipher.doFinal(data, (err, output) => { if (err) { - console.error("convertKey: error."); - return; + console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } } - console.info("convertKey: success."); }) ``` -### convertKey +### doFinal + +doFinal(data: DataBlob): Promise\ + +(1) Encrypts or decrypts the remaining data (generated by the block cipher mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. + +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. -convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ +(2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses a promise to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. -Converts data into an asymmetric key. This API uses a promise to return the result. For more information, see **Key Conversion**. +> **NOTE** +> +> 1. In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> 2. If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. +> 3. The result of **doFinal()** may be **null**. To avoid exceptions, determine whether the result is **null** before using the **.data** field to access the **doFinal()** result. +> 4. For details about the sample code for calling **doFinal()** multiple times during RSA asymmetric encryption and decryption, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------ | -------- | ---- | ---------------- | -| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| -| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(empty)}.| **Return value** -| Type | Description | -| ----------------- | --------------------------------- | -| Promise\<[KeyPair](#keypair)> | Promise used to return the key pair obtained. | +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | -------------------------------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); -let pubKey; // pubKey is a public key generated by the asymmetric key generator. The generation process is omitted here. -let priKey; // priKey is a private key generated by the asymmetric key generator. The generation process is omitted here. -let keyGenPromise = asyKeyGenerator.convertKey(pubKey, priKey); -keyGenPromise.then( keyPair => { - console.info("convertKey success."); -}).catch(error => { - console.error("convertKey error."); -}); -``` - -**Key Conversion** +let cipher; // The process of creating a Cipher instance is omitted here. +let data; // The process of preparing the data to encrypt or decrypt is omitted here. +// The init() and update() processes are omitted here. +cipher.doFinal(data) +.then(output => { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } +}, error => { + console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`); +}) +``` -- If **getEncoded()** is called to obtain a public key and a private key (RSA and ECC), binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The data can be used for cross-application transfer or persistent storage. -- When **convertKey()** is called to convert binary data into an asymmetric key pair, the public key material must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key material must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. -- In **convertKey()**, you can pass in either **pubKey** or **priKey**, or both of them. If one of them is passed in, the returned **KeyPair** instance contains only the key converted from the data you passed in. +**RSA encryption example (callback)** -## cryptoFramework.createCipher +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -createCipher(transformation : string) : Cipher +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} -Creates a [Cipher](#cipher) instance based on the specified algorithm. +let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); +let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); +rsaGenerator.generateKeyPair(function (err, keyPair) { + let pubKey = keyPair.pubKey; + cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) { + let plainText = "this is cipher text"; + let input = {data: stringToUint8Array(plainText) }; + cipher.doFinal(input, function (err, data) { + AlertDialog.show({ message: "EncryptOutPut is " + data.data} ); + }); + }); +}); +``` -For details about the supported specifications, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). +**RSA encryption example (promise)** -**System capability**: SystemCapability.Security.CryptoFramework +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -**Parameters** +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} -| Name | Type | Mandatory| Description | -| -------------- | ------ | ---- | ------------------------------------------------------------ | -| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.
For details, see **Algorithm String** in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). | +let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); +let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); +let keyGenPromise = rsaGenerator.generateKeyPair(); +keyGenPromise.then(rsaKeyPair => { + let pubKey = rsaKeyPair.pubKey; + return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode. +}).then(() => { + let plainText = "this is cipher text"; + let input = { data: stringToUint8Array(plainText) }; + return cipher.doFinal(input); +}).then(dataBlob => { + console.info("EncryptOutPut is " + dataBlob.data); +}); +``` > **NOTE** -> - In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed.
You need to understand the differences between different block cipher modes and set parameter correctly. For example, padding is required for ECB and CBC. Otherwise, the plaintext length must be an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length. -> - If RSA is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. For symmetric encryption and decryption, one **cipher** object can be used to perform both encryption and decryption as long as the algorithm specifications are the same. - -**Return value** - -| Type | Description | -| ----------------- | ------------------------ | -| [Cipher](#cipher) | [Cipher](#cipher) instance created.| - -**Example** - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +> +> For more encryption and decryption examples, see [Encryption and Decryption](../../security/cryptoFramework-guidelines.md#encryption-and-decryption). -let cipherAlgName = '3DES192|ECB|PKCS7'; -var cipher; -try { - cipher = cryptoFramework.createCipher(cipherAlgName); - console.info(`cipher algName: ${cipher.algName}`); -} catch (error) { - console.error(`createCipher failed, ${error.code}, ${error.message}`); -} -``` +### setCipherSpec10+ -## Cipher +setCipherSpec(itemType: CipherSpecItem, itemValue: Uint8Array): void -Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption/decryption and asymmetric encryption/decryption. +Sets cipher specifications. You can use this API to set cipher specifications that cannot be set by [createCipher](#cryptoframeworkcreatecipher). Currently, only the RSA is supported. -For details about the complete encryption and decryption process, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). +**System capability**: SystemCapability.Security.CryptoFramework -A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process. +**Parameters** -- In symmetric encryption and decryption, **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data by segment. After **doFinal()** is called to complete an encryption/decryption operation, **init()** can be called to start a new encryption/decryption operation. -- In RSA asymmetric encryption and decryption, **init()** and **doFinal()** are mandatory, and **update()** is not supported. **doFinal()** can be called multiple times to encrypt or decrypt big data by segment. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created. +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| itemType | [CipherSpecItem](#cipherspecitem10) | Yes | Cipher parameter to set.| +| itemValue | Uint8Array | Yes | Value of the parameter to set.| -### Attributes +**Error codes** -**System capability**: SystemCapability.Security.CryptoFramework +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | +**Example** -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| algName | string | Yes | No | Algorithm.| +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; -### init +let cipher; // The process of generating the Cipher instance is omitted here. +let pSource = new Uint8Array([1,2,3,4]); +cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); +``` -init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void +### getCipherSpec10+ -Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. +getCipherSpec(itemType: CipherSpecItem): string | Uint8Array -This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). +Obtains cipher specifications. Currently, only the RSA is supported. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption. | -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the initialization is successful, **err** is **undefined**. Otherwise, **err** is an error object. | +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------- | +| itemType | [CipherSpecItem](#cipherspecitem10) | Yes | Cipher parameter to obtain.| + +**Return value** + +| Type | Description | +| -------------- | ----------- | +| string\|Uint8Array | Returns the value of the cipher parameter obtained.| **Error codes** -| ID| Error Message | -| -------- | --------------------------------------------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** ```js import cryptoFramework from '@ohos.security.cryptoFramework'; -let symKey; // The process of generating the symmetric key is omitted here. -let cipher; // The process of creating a Cipher instance is omitted here. -cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { - if (err) { - console.error(`Failed to init cipher, ${err.code}, ${err.message}`); - } else { - console.info(`Init cipher success`); - // Perform subsequent operations such as update. - } -}) +let cipher; // The process of generating the Cipher instance is omitted here. +let mdName = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR); ``` -### init - -init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\ +## cryptoFramework.createSign -Initializes a [cipher](#cipher) instance. This API uses a promise to return the result. +createSign(algName: string): Sign -This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). +Creates a **Sign** instance. For details about the supported specifications, see [Signing and Signature Verification Specifications](../../security/cryptoFramework-overview.md#signing-and-signature-verification-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ------------------------- | ---- | ------------------------------------------------------------ | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption. | -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Signing algorithm, which can be RSA, ECC, or DSA.
If the RSA PKCS1 mode is used, you need to set the digest. If the RSA PSS mode is used, you need to set the digest and mask digest.| **Return value** -| Type | Description | -| -------------- | -------------------------------------- | -| Promise\ | Promise that returns no value.| +| Type| Description | +| ---- | ---------------------------------- | +| Sign | Returns the **Sign** instance created.| **Error codes** -| ID| Error Message | -| -------- | ------------------------------------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | **Example** ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; -let symKey; // The process of generating the symmetric key is omitted here. -let cipher; // The process of creating a Cipher instance is omitted here. -cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null) -.then(() => { - console.info(`Init cipher success`); - // Perform subsequent operations such as update. -}, error => { - console.error(`Failed to init cipher, ${error.code}, ${error.message}`); -}) +import cryptoFramework from "@ohos.security.cryptoFramework" + +let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + +let singer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256"); + +let singer3 = cryptoFramework.createSign("ECC224|SHA256"); + +let singer4 = cryptoFramework.createSign("DSA2048|SHA256"); ``` -### update +## Sign -update(data : DataBlob, callback : AsyncCallback\) : void +Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign(algName: string): Sign**. Invoke **init()**, **update()**, and **sign()** in this class in sequence to complete the signing operation. For details about the sample code, see [Signing and Signature Verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). -Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. +The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** object and call **init()** for initialization. -This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). +The signing mode is determined in **createSign()**, and the key is set by **init()**. -> **NOTE** -> - The **update()** and [doFinal()](#dofinal-2) results vary with the block mode you use. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, data is output by **update()** as long as the input data is of the block size. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. -> - **update()** can be called multiple times or not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment.
For details about the sample code for calling **update()** multiple times in AES, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). -> - RSA asymmetric encryption and decryption do not support **update()**. +If the data to be signed is short, you can directly call **sign()** to pass in the original data for signing after **init()**. That is, you do not need to use **update()**. + +If the data to be signed is long, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data. + +If **update()** is used to pass in data by segment, **data** of **sign()** can be **null**. + +### Attributes **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to use.| -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**, and **data** is **DataBlob** (containing the encrypted or decrypted data). Otherwise, **err** is an error object.| +### init -**Error codes** +init(priKey: PriKey, callback: AsyncCallback\): void -| ID| Error Message | -| -------- | ------------------------------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error. | +Initializes a **Sign** object using a private key. This API uses an asynchronous callback to return the result. The **Sign** class does not support repeated calling of **init()**. -**Example** +**System capability**: SystemCapability.Security.CryptoFramework -```js -import cryptoFramework from '@ohos.security.cryptoFramework'; +**Parameters** -function stringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | -let cipher; // The process of creating a Cipher instance is omitted here. -// The init() process is omitted here. -let plainText = {data : stringToUint8Array('this is test!')}; -cipher.update(plainText, (err, output) => { // Example of the encryption process. - if (err) { - console.error(`Failed to update cipher`); - } else { - console.info(`Update cipher success`); - if (output != null) { - // Concatenate output.data to the ciphertext. - } - // Perform subsequent operations such as doFinal(). - } -}) -``` +**Error codes** -### update +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -update(data : DataBlob) : Promise\ +### init -Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). +init(priKey: PriKey): Promise\ -> **NOTE** -> - The **update()** and [doFinal()](#dofinal-2) results vary with the block mode you use. If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, data is output as long as the data passed in by **update()** is of the block size. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. -> - **update()** can be called multiple times or not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. For details about the sample code for calling **update()** multiple times in AES, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). -> - RSA asymmetric encryption and decryption do not support **update()**. +Initializes a **Sign** object using a private key. This API uses a promise to return the result. The **Sign** class does not support repeated calling of **init()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | --------------------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | +| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| **Return value** -| Type | Description | -| ------------------------------- | ------------------------------------------------ | -| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob** (containing the encrypted or decrypted data).| +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** -| ID| Error Message | -| -------- | -------------------------------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -**Example** +### update -```js -import cryptoFramework from '@ohos.security.cryptoFramework'; +update(data: DataBlob, callback: AsyncCallback\): void -function stringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - return new Uint8Array(arr); -} +Updates the data to be signed. This API uses a callback to complete the update.
This API can be called only after the [Sign](#sign) instance is initialized by using [init()](init-2). -let cipher; // The process of creating a Cipher instance is omitted here. -// The init() process is omitted here. -let plainText = {data : stringToUint8Array('this is test!')}; -cipher.update(plainText) -.then((output) => { - console.info(`Update cipher success.`); - if (output != null) { - // Concatenate output.data to the ciphertext. - } - // Perform subsequent operations such as doFinal(). -}, error => { - console.info(`Update cipher failed.`); -}) -``` +> **NOTE** +> +> **update()** may be called multiple times or may not be called (call [sign](#sign-1) after [init](#init-2)), depending on the size of the data.
The algorithm library does not set a limit on the amount of data to be updated (once or accumulatively). If a large amount of data needs to be signed, you are advised to use **update()** multiple times to pass in data. This can prevent too much memory from being requested at a time.
For details about the sample code for calling **update()** multiple times, see [Signing and Signature verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). -### doFinal +**System capability**: SystemCapability.Security.CryptoFramework -doFinal(data : DataBlob, callback : AsyncCallback\) : void +**Parameters** -(1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses an asynchronous callback to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**. +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------ | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | -The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. +**Error codes** -- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. -- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -(2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses an asynchronous callback to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. +### update + +update(data: DataBlob): Promise\ -> **NOTE** -> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. -> - If a decryption operation fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. -> - The result of **doFinal()** may be **null**. To avoid exceptions, determine whether the result is **null** before using the **.data** field to access the **doFinal()** result. -> - For details about the sample code for calling **doFinal()** multiple times during RSA asymmetric encryption and decryption, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). +Updates the data to be signed. This API uses a promise to return the result.
This API can be called only after the [Sign](#sign) instance is initialized by using [init()](#init-3). + +> **NOTE** +> +> **update()** may be called multiple times or may not be called (call [sign](#sign-2) after [init](#init-3)), depending on the size of the data.
+> The algorithm library does not set a limit on the amount of data to be updated (once or accumulatively). If a large amount of data needs to be signed, you are advised to use **update()** multiple times to pass in data. This can prevent too much memory from being requested at a time.
+> For details about the sample code for calling **update()** multiple times, see [Signing and Signature verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(null)}. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the data is successfully encrypted or decrypted, **err** is **undefined**, and **data** is the **DataBlob** (encryption or decryption result of the remaining data). Otherwise, **err** is an error object.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------- | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** -| ID| Error Message | -| -------- | ----------------------- | -| 17620001 | memory error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | | 17620002 | runtime error. | | 17630001 | crypto operation error. | -**Example** +### sign -```js -import cryptoFramework from '@ohos.security.cryptoFramework'; +sign(data: DataBlob, callback: AsyncCallback\): void -let cipher; // The process of creating a Cipher instance is omitted here. -let data; // The process of preparing the data to encrypt or decrypt is omitted here. -// The init() and update() processes are omitted here. -cipher.doFinal(data, (err, output) => { - if (err) { - console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`); - } else { - console.info(`Finalize cipher success`); - if (output != null) { - // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). - } - } -}) -``` +Signs the data. This API uses an asynchronous callback to return the result. -### doFinal +**System capability**: SystemCapability.Security.CryptoFramework -doFinal(data : DataBlob) : Promise\ +**Parameters** -(1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**. +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| callback | AsyncCallback\<[DataBlob](#datablob) > | Yes | Callback invoked to return the result. | -The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. +**Error codes** -- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. -- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -(2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses a promise to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. +### sign -> **NOTE** -> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. -> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. -> - The result of **doFinal()** may be **null**. To avoid exceptions, determine whether the result is **null** before using the **.data** field to access the **doFinal()** result. -> - For details about the sample code for calling **doFinal()** multiple times during RSA asymmetric encryption and decryption, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). +sign(data: DataBlob): Promise\ + +Signs the data. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | --------------------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(null)}.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------- | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------------------------- | ------------------------------------------------ | -| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.| +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** -| ID| Error Message | -| -------- | -------------------------------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -**Example** +**Callback example**: ```js -import cryptoFramework from '@ohos.security.cryptoFramework'; - -let cipher; // The process of creating a Cipher instance is omitted here. -let data; // The process of preparing the data to encrypt or decrypt is omitted here. -// The init() and update() processes are omitted here. -cipher.doFinal(data) -.then(output => { - console.info(`Finalize cipher success`); - if (output != null) { - // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). - } -}, error => { - console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`); -}) -``` - -**RSA encryption example (callback)** - -```javascript import cryptoFramework from "@ohos.security.cryptoFramework" function stringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - return new Uint8Array(arr); + var tmpArray = new Uint8Array(arr); + return tmpArray; } -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); -rsaGenerator.generateKeyPair(function (err, keyPair) { - let pubKey = keyPair.pubKey; - cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) { - let plainText = "this is cipher text"; - let input = {data : stringToUint8Array(plainText) }; - cipher.doFinal(input, function (err, data) { - AlertDialog.show({ message : "EncryptOutPut is " + data.data} ); +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data: stringToUint8Array(plan1) }; +let input2 = { data: stringToUint8Array(plan2) }; + +function signMessageCallback() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + rsaGenerator.generateKeyPair(function (err, keyPair) { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + signer.init(priKey, function (err, data) { + signer.update(input1, function (err, data) { // Add the first segment of the data. + signer.sign(input2, function (err, data) { // Add the second segment of the data, and sign input1 and input2. + SignMessageBlob = data; + AlertDialog.show({message: "res" + SignMessageBlob.data}); + }); + }); }); }); -}); +} ``` -**RSA encryption example (promise)** +**Promise example**: -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" function stringToUint8Array(str) { - let arr = []; - for (let i = 0, j = str.length; i < j; ++i) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - return new Uint8Array(arr); + var tmpArray = new Uint8Array(arr); + return tmpArray; } -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); -let keyGenPromise = rsaGenerator.generateKeyPair(); -keyGenPromise.then(rsaKeyPair => { - let pubKey = rsaKeyPair.pubKey; - return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode. -}).then(() => { - let plainText = "this is cipher text"; - let input = { data : stringToUint8Array(plainText) }; - return cipher.doFinal(input); -}).then(dataBlob => { - console.info("EncryptOutPut is " + dataBlob.data); -}); -``` - -> **NOTE**
-> For more encryption and decryption examples, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting data). +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data: stringToUint8Array(plan1) }; +let input2 = { data: stringToUint8Array(plan2) }; -## cryptoFramework.createSign +function signMessagePromise() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + let keyGenPromise = rsaGenerator.generateKeyPair(); + keyGenPromise.then( keyPair => { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + return signer.init(priKey); + }).then(() => { + return signer.update(input1); // Add the first segment of the data. + }).then(() => { + return signer.sign(input2); // Add the second segment of the data, and sign input1 and input2. + }).then(dataBlob => { + SignMessageBlob = dataBlob; + console.info("sign output is " + SignMessageBlob.data); + AlertDialog.show({message: "output" + SignMessageBlob.data}); + }); +} +``` -createSign(algName : string) : Sign +### setSignSpec10+ -Creates a **Sign** instance. +setSignSpec(itemType: SignSpecItem, itemValue: number): void -For details about the supported specifications, see [Signing and Signature Verification Specifications](../../security/cryptoFramework-overview.md#signing-and-signature-verification-specifications). +Sets signing specifications. You can use this API to set signing parameters that cannot be set by [createSign](#cryptoframeworkcreatesign). Currently, only the RSA is supported. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Signing algorithm to use, which can be RSA or ECC. If RSA PKCS #1 is used, the digest must be set. If RSA PSS is used, the digest and mask digest must be set.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| itemType | [SignSpecItem](#signspecitem10) | Yes | Signing parameter to set.| +| itemValue | number | Yes | Value of the signing parameter to set.| -**Return value** +**Error codes** -| Type| Description | -| ---- | -------------------------------- | -| Sign | **Sign** instance created.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); - -let singer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256") +let signer; // The process of generating the Sign instance is omitted here. +let setN = 20; +signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); ``` -## Sign - -Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** object and call **init()** for initialization. - -The signing mode is determined in **createSign()**, and the key is set by **init()**. - -If the data to be signed is short, you can use **sign()** to pass in the data for signing after **init()**. - -If the data to be signed is long, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data. +### getSignSpec10+ -If **update()** is used to pass in data by segment, **data** of **sign()** can be **null**. +getSignSpec(itemType: SignSpecItem): string | number -### Attributes +Obtains signing specifications. Currently, only the RSA is supported. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| algName | string | Yes | No | Algorithm to use.| - -### init - -init(priKey : PriKey, callback : AsyncCallback\) : void - -Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. The **Sign** class does not support repeated calling of **init()**. +**Parameters** -**System capability**: SystemCapability.Security.CryptoFramework +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------- | +| itemType | [SignSpecItem](#signspecitem) | Yes | Signing parameter to obtain.| -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------- | -| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Type | Description | +| -------------- | ----------- | +| string\|number | Returns the value of the signing parameter obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | | 17620001 | memory error. | -| 17620002 | runtime error. | | 17630001 | crypto operation error. | -### init +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let signer; // The process of generating the Sign instance is omitted here. +let saltLen = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); +``` + +## cryptoFramework.createVerify -init(priKey : PriKey) : Promise\ +createVerify(algName: string): Verify -Initializes a **Sign** instance using a private key. This API uses a promise to return the result. The **Sign** class does not support repeated calling of **init()**. +Creates a **Verify** instance.
For details about the supported specifications, see [Signing and Signature Verification Specifications](../../security/cryptoFramework-overview.md#signing-and-signature-verification-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------- | -| priKey | [PriKey](#prikey) | Yes | Private key used for the initialization.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Signing algorithm, which can be RSA, ECC, or DSA.
If the RSA PKCS1 mode is used, you need to set the digest. If the RSA PSS mode is used, you need to set the digest and mask digest.| **Return value** -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| ------ | ------------------------------------ | +| Verify | Returns the **Verify** instance created.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | | 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error. | -### update +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); + +let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256") +``` + +## Verify + +Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify(algName: string): Verify**. Invoke **init()**, **update()**, and **sign()** in this class in sequence to complete the signature verification. For details about the sample code, see [Signing and Signature Verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). + +The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** object and call **init()** for initialization. + +The signature verification mode is determined in **createVerify()**, and key is set by **init()**. + +If the signed message is short, you can call **verify()** to pass in the signed message and signature (**signatureData**) for signature verification after **init()**. That is, you do not need to use **update()**. + +If the signed message is too long, you can call **update()** multiple times to pass in the signed message by segment, and then call **verify()** to verify the full text of the message. The **data** parameter of **verify()** can be null. The service can call **update()** multiple times in the loop. When the loop ends, the service calls **verify()** to pass in the signature (**signatureData**) for signature verification. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to be used for signature verification.| -update(data : DataBlob, callback : AsyncCallback\) : void +### init -Updates the data to be signed. This API uses an asynchronous callback to return the result. +init(pubKey: PubKey, callback: AsyncCallback\): void -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). +Initializes the **Verify** instance using a public key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| data | [DataBlob](#datablob)| Yes | Data to pass in.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------ | +| pubKey | [PubKey](#pubkey) | Yes | Public key used to initialize the **Verify** instance.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | | 17620001 | memory error. | | 17620002 | runtime error. | | 17630001 | crypto operation error. | -### update - -update(data : DataBlob) : Promise\; +### init -Updates the data to be signed. This API uses a promise to return the result. +init(pubKey: PubKey): Promise\ -> **NOTE**
-> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). +Initializes the **Verify** instance using a public key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------------------- | +| pubKey | [PubKey](#pubkey) | Yes | Public key used to initialize the **Verify** instance.| **Return value** -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | | 17620001 | memory error. | | 17620002 | runtime error. | | 17630001 | crypto operation error. | -### sign +### update -sign(data : DataBlob, callback : AsyncCallback\) : void +update(data: DataBlob, callback: AsyncCallback\): void -Signs the data. This API uses an asynchronous callback to return the result. +Updates the data for signature verification. This API uses an asynchronous callback to return the result.
This API can be called only after the [Verify](#verify) instance is initialized using [init()](#init-4). + +> **NOTE** +> +> **update()** may be called multiple times or may not be called (call [verify](#verify-1) after [init](#init-4)), depending on the size of the data.
+> The algorithm library does not set a limit on the amount of data to be updated (once or accumulatively). If a large amount of data is involved in signature verification, you are advised to use **update()** multiple times to pass in data. This can prevent too much memory from being requested at a time.
+> For details about the sample code for calling **update()** multiple times, see [Signing and Signature verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| data | [DataBlob](#datablob) | Yes | Data to pass in.| -| callback | AsyncCallback\<[DataBlob](#datablob) > | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------ | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | | 17620001 | memory error. | | 17620002 | runtime error. | | 17630001 | crypto operation error. | -### sign +### update -sign(data : DataBlob) : Promise\ +update(data: DataBlob): Promise\ -Signs the data. This API uses a promise to return the result. +Updates the data for signature verification. This API uses a promise to return the result.
This API can be called only after the [Verify](#verify) instance is initialized using [init()](#init-5). + +> **NOTE** +> +> **update()** may be called multiple times or may not be called (call [verify](#verify-2) after [init](#init-5)), depending on the size of the data.
+> The algorithm library does not set a limit on the amount of data to be updated (once or accumulatively). If a large amount of data is involved in signature verification, you are advised to use **update()** multiple times to pass in data. This can prevent too much memory from being requested at a time.
+> For details about the sample code for calling **update()** multiple times, see [Signing and Signature verification](../../security/cryptoFramework-guidelines.md#signing-and-signature-verification). **System capability**: SystemCapability.Security.CryptoFramework @@ -2263,237 +2359,833 @@ Signs the data. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | | 17620001 | memory error. | | 17620002 | runtime error. | | 17630001 | crypto operation error. | -**Callback example**: - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpArray = new Uint8Array(arr); - return tmpArray; -} +### verify -let globalKeyPair; -let SignMessageBlob; -let plan1 = "This is Sign test plan1"; // The first segment of the data. -let plan2 = "This is Sign test plan2"; // The second segment of the data. -let input1 = { data : stringToUint8Array(plan1) }; -let input2 = { data : stringToUint8Array(plan2) }; +verify(data: DataBlob, signatureData: DataBlob, callback: AsyncCallback\): void -function signMessageCallback() { - let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); - let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); - rsaGenerator.generateKeyPair(function (err, keyPair) { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - signer.init(priKey, function (err, data) { - signer.update(input1, function (err, data) { // Add the first segment of the data. - signer.sign(input2, function (err, data) { // Add the second segment of the data, and sign input1 and input2. - SignMessageBlob = data; - AlertDialog.show({message : "res" + SignMessageBlob.data}); - }); - }); - }); - }); -} -``` +Verifies the signature. This API uses an asynchronous callback to return the result. -**Promise example**: +**System capability**: SystemCapability.Security.CryptoFramework -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +**Parameters** -function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpArray = new Uint8Array(arr); - return tmpArray; -} +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ---------- | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| signatureData | [DataBlob](#datablob) | Yes | Signature data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | -let globalKeyPair; -let SignMessageBlob; -let plan1 = "This is Sign test plan1"; // The first segment of the data. -let plan2 = "This is Sign test plan2"; // The second segment of the data. -let input1 = { data : stringToUint8Array(plan1) }; -let input2 = { data : stringToUint8Array(plan2) }; +**Error codes** -function signMessagePromise() { - let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); - let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); - let keyGenPromise = rsaGenerator.generateKeyPair(); - keyGenPromise.then( keyPair => { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - return signer.init(priKey); - }).then(() => { - return signer.update(input1); // Add the first segment of the data. - }).then(() => { - return signer.sign(input2); // Add the second segment of the data, and sign input1 and input2. - }).then(dataBlob => { - SignMessageBlob = dataBlob; - console.info("sign output is " + SignMessageBlob.data); - AlertDialog.show({message : "output" + SignMessageBlob.data}); - }); -} -``` +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -## cryptoFramework.createVerify +### verify -createVerify(algName : string) : Verify +verify(data: DataBlob, signatureData: DataBlob): Promise\ -Creates a **Verify** instance. For details about the supported specifications, see [Signing and Signature Verification Specifications](../../security/cryptoFramework-overview.md#signing-and-signature-verification-specifications). +Verifies the signature. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Signing algorithm to use, which can be RSA or ECC. If RSA PKCS #1 is used, the digest must be set. If RSA PSS is used, the digest and mask digest must be set.| +| Name | Type | Mandatory| Description | +| ------------- | -------- | ---- | ---------- | +| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| signatureData | [DataBlob](#datablob) | Yes | Signature data. | **Return value** -| Type | Description | -| ------ | ---------------------------------- | -| Verify | **Verify** instance created.| - -**Example** - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); - -let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256") -``` - -## Verify - -Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify()**. - -The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** object and call **init()** for initialization. +| Type | Description | +| ----------------- | ------------------------------ | +| Promise\ | Promise used to return the result.| -The signature verification mode is determined in **createVerify()**, and key is set by **init()**. +**Error codes** -If the signature data to be verified is short, you can call **verify()** to pass in the signature data and original data after **init()**. +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | -If the signature data to be verified is long, you can use **update()** to pass in the data by segment, and then use **verify()** to verify the entire data. +**Callback example**: -If **update()** is used to pass in data by segment, **data** of **verify()** can be **null**. +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -### Attributes +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. +let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25"); +verifyer.init(globalKeyPair.pubKey, function (err, data) { + verifyer.update(input1, function(err, data) { + verifyer.verify(input2, signMessageBlob, function(err, data) { + console.info("verify result is " + data); + }) + }); +}) +``` -**System capability**: SystemCapability.Security.CryptoFramework +**Promise example**: -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| algName | string | Yes | No | Algorithm to be used for signature verification.| +```js +import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); +let verifyInitPromise = verifyer.init(globalKeyPair.pubKey); +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. +verifyInitPromise.then(() => { + return verifyer.update(input1); +}).then(() => { + return verifyer.verify(input2, signMessageBlob); +}).then(res => { + console.log("Verify result is " + res); +}); +``` +### setVerifySpec10+ -### init +setVerifySpec(itemType: SignSpecItem, itemValue: number): void -init(pubKey : PubKey, callback : AsyncCallback\) : void +Set signature verification specifications. You can use this API to set signature verification parameters that cannot be set by [createVerify](#cryptoframeworkcreateverify). Currently, only the RSA is supported. -Initializes the **Verify** instance using a public key. This API uses an asynchronous callback to return the result. +The parameters for signature verification must be the same as those for signing. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------------------- | -| pubKey | [PubKey](#pubkey) | Yes | Public key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| itemType | [SignSpecItem](#signspecitem10) | Yes | Signature verification parameter to set.| +| itemValue | number | Yes | Value of the signature verification parameter to set.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | | 17620001 | memory error. | -| 17620002 | runtime error. | | 17630001 | crypto operation error. | -### init +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -init(pubKey : PubKey) : Promise\ +let verifyer; //The process of generating the Verify instance is omitted here. +let setN = 20; +verifyer.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); +``` -Initializes the **Verify** instance using a public key. This API uses a promise to return the result. +### getVerifySpec10+ + +getVerifySpec(itemType: SignSpecItem): string | number + +Obtains signature verification specifications. Currently, only the RSA is supported. + +The parameters for signature verification must be the same as those for signing. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------------------- | -| pubKey | [PubKey](#pubkey) | Yes | Public key used for the initialization.| +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ---------- | +| itemType | [SignSpecItem](#signspecitem10) | Yes | Signature verification parameter to obtain.| **Return value** | Type | Description | | -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| string\|number | Returns the value of the parameter obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | | 17620001 | memory error. | -| 17620002 | runtime error. | | 17630001 | crypto operation error. | -### update +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -update(data : DataBlob, callback : AsyncCallback\) : void +let verifyer; //The process of generating the Verify instance is omitted here. +let saltLen = verifyer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); +``` -Updates the data for signature verification. This API uses an asynchronous callback to return the result. +## cryptoFramework.createKeyAgreement -> **NOTE** -> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). +createKeyAgreement(algName: string): KeyAgreement + +Creates a **KeyAgreement** instance.
For details about the supported specifications, see [Key Agreement Specifications](../../security/cryptoFramework-overview.md#key-agreement-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| data | [DataBlob](#datablob)| Yes | Data to pass in.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------------------- | +| algName | string | Yes | Key agreement algorithm to use. Currently, only the ECC is supported.| -**Error codes** +**Return value** + +| Type | Description | +| ------------ | ------------------------------------------ | +| KeyAgreement | Returns the **KeyAgreement** instance created.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 801 | this operation is not supported. | +| 17620001 | memory error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); + +``` + +## KeyAgreement + +Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement(algName: string): KeyAgreement**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm used for key agreement.| + +### generateSecret + +generateSecret(priKey: PriKey, pubKey: PubKey, callback: AsyncCallback\): void + +Generates a shared secret. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------------- | +| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| +| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the shared secret.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | + +### generateSecret + +generateSecret(priKey: PriKey, pubKey: PubKey): Promise\ + +Generates a shared secret. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| +| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| + +**Return value** + +| Type | Description | +| ------------------ | -------- | +| Promise\<[DataBlob](#datablob)> | Promise used to return the shared secret.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | + +**Callback example**: + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); +keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) { + if (err) { + console.error("keyAgreement error."); + return; + } + console.info("keyAgreement output is " + secret.data); +}); +``` + +**Promise example**: + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); +let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey); +keyAgreementPromise.then((secret) => { + console.info("keyAgreement output is " + secret.data); +}).catch((error) => { + console.error("keyAgreement error."); +}); +``` + +## cryptoFramework.createMd + +createMd(algName: string): Md + +Creates an **Md** instance for message digest operations.
For details about the supported specifications, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications). + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [MD Algorithm Specifications](../../security/cryptoFramework-overview.md#md-algorithm-specifications).| + +**Return value** + +| Type| Description | +| ---- | --------------------------------------- | +| Md | Returns the [Md](#md) instance created.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 401 | invalid parameters. | +| 17620001 | memory error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + // Set algName based on the algorithm supported. + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +``` + +## Md + +Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd). + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------- | +| algName | string | Yes | No | Digest algorithm.| + +### update + +update(input: DataBlob, callback: AsyncCallback\): void + +Updates the message digest data. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> For details about the sample code for calling **update()** multiple times, see [Generating a Digest](../../security/cryptoFramework-guidelines.md#generating-a-digest). + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------ | +| input | [DataBlob](#datablob) | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Md algName is: " + md.algName); + +let blob; +md.update(blob, (err,) => { + if (err) { + console.error("[Callback] err: " + err.code); + } +}); +``` + +### update + +update(input: DataBlob): Promise\ + +Updates the message digest data. This API uses a promise to return the result. + +> **NOTE** +> +> For details about the sample code for calling **update()** multiple times, see [Generating a Digest](../../security/cryptoFramework-guidelines.md#generating-a-digest). + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------ | +| input | DataBlob | Yes | Data to pass in.| + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Md algName is: " + md.algName); + +let blob; +var promiseMdUpdate = md.update(blob); +promiseMdUpdate.then(() => { + // do something +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` + +### digest + +digest(callback: AsyncCallback\): void + +Generates a message digest. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Md algName is: " + md.algName); + +let blob; +md.update(blob, (err,) => { + if (err) { + console.error("[Callback] err: " + err.code); + } + md.digest((err1, mdOutput) => { + if (err1) { + console.error("[Callback] err: " + err1.code); + } else { + console.error("[Callback]: MD result: " + mdOutput); + } + }); +}); +``` + +### digest + +digest(): Promise\ + +Generates a message digest. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Return value** + +| Type | Description | +| ------------------ | ----------- | +| Promise\<[DataBlob](#datablob)> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Md algName is: " + md.algName); + +let blob; +var promiseMdUpdate = md.update(blob); +promiseMdUpdate.then(() => { + var PromiseMdDigest = md.digest(); + return PromiseMdDigest; +}).then(mdOutput => { + console.error("[Promise]: MD result: " + mdOutput.data); +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` + +### getMdLength + +getMdLength(): number + +Obtains the message digest length, in bytes. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| number | Returns the length of the message digest obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var md; +try { + md = cryptoFramework.createMd("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Md algName is: " + md.algName); + +let blob; +var promiseMdUpdate = md.update(blob); +promiseMdUpdate.then(() => { + var PromiseMdDigest = md.digest(); + return PromiseMdDigest; +}).then(mdOutput => { + console.error("[Promise]: MD result: " + mdOutput.data); + let mdLen = md.getMdLength(); + console.error("MD len: " + mdLen); +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` + +## cryptoFramework.createMac + +createMac(algName: string): Mac + +Creates a **Mac** instance for message authentication code (MAC) operations. For details about the supported specifications, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications). + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Digest algorithm. For details about the supported algorithms, see [HMAC Algorithm Specifications](../../security/cryptoFramework-overview.md#hmac-algorithm-specifications).| + +**Return value** + +| Type| Description | +| ---- | ----------------------------------------- | +| Mac | Returns the [Mac](#mac) instance created.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 401 | invalid parameters. | +| 17620001 | memory error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var mac; +try { + // Set algName based on the algorithm supported. + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +``` + +## Mac + +Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac). + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------- | +| algName | string | Yes | No | Digest algorithm.| + +### init + +init(key: SymKey, callback: AsyncCallback\): void + +Initializes the MAC computation using a symmetric key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------- | +| key | [SymKey](#symkey) | Yes | Shared symmetric key.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +var KeyBlob; +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { + if (err) { + console.error("[Callback] err: " + err.code); + } + mac.init(symKey, (err1, ) => { + if (err1) { + console.error("[Callback] err: " + err1.code); + } + }); +}); +``` + +### init + +init(key: SymKey): Promise\ + +Initializes the MAC computation using a symmetric key. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| key | [SymKey](#symkey) | Yes | Shared symmetric key.| + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | +| 401 | invalid parameters. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Mac algName is: " + mac.algName); + +var KeyBlob; +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); +promiseConvertKey.then(symKey => { + var promiseMacInit = mac.init(symKey); + return promiseMacInit; +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); + +``` + +### update + +update(input: DataBlob, callback: AsyncCallback\): void + +Updates the MAC computation data. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> For details about the sample code for calling **update()** multiple times, see [Generating a MAC](../../security/cryptoFramework-guidelines.md#generating-a-mac). + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------ | +| input | [DataBlob](#datablob) | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | | 17630001 | crypto operation error. | +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var KeyBlob; +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { + if (err) { + console.error("[Callback] err: " + err.code); + } + mac.init(symKey, (err1, ) => { + if (err1) { + console.error("[Callback] err: " + err1.code); + } + let blob; + mac.update(blob, (err2, data) => { + if (err2) { + console.error("[Callback] err: " + err2.code); + } + }); + }); +}); +``` + ### update -update(data : DataBlob) : Promise\; +update(input: DataBlob): Promise\ -Updates the data for signature verification. This API uses a promise to return the result. +Updates the MAC computation data. This API uses a promise to return the result. > **NOTE** -> For details about the sample code for calling **update()** multiple times, see [Generating and Verifying a Signature](../../security/cryptoFramework-guidelines.md#generating-and-verifying-a-signature). +> +> For details about the sample code for calling **update()** multiple times, see [Generating a MAC](../../security/cryptoFramework-guidelines.md#generating-a-mac). **System capability**: SystemCapability.Security.CryptoFramework @@ -2501,237 +3193,445 @@ Updates the data for signature verification. This API uses a promise to return t | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | [DataBlob](#datablob) | Yes | Data to pass in.| +| input | [DataBlob](#datablob) | Yes | Data to pass in.| **Return value** -| Type | Description | -| -------------- | ----------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise that returns no value.| **Error codes** | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | +| 401 | invalid parameters. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Mac algName is: " + mac.algName); + +var KeyBlob; +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); +promiseConvertKey.then(symKey => { + var promiseMacInit = mac.init(symKey); + return promiseMacInit; +}).then(() => { + let blob; + var promiseMacUpdate = mac.update(blob); + return promiseMacUpdate; +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); + +``` + +### doFinal + +doFinal(callback: AsyncCallback\): void + +Finalizes the MAC computation. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------- | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | + +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var KeyBlob; +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { + if (err) { + console.error("[Callback] err: " + err.code); + } + mac.init(symKey, (err1, ) => { + if (err1) { + console.error("[Callback] err: " + err1.code); + } + let blob; + mac.update(blob, (err2, ) => { + if (err2) { + console.error("[Callback] err: " + err2.code); + } + mac.doFinal((err3, macOutput) => { + if (err3) { + console.error("[Callback] err: " + err3.code); + } else { + console.error("[Promise]: HMAC result: " + macOutput); + } + }); + }); + }); +}); +``` + +### doFinal + +doFinal(): Promise\ + +Finalizes the MAC computation. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.CryptoFramework + +**Return value** + +| Type | Description | +| ------------------ | ----------- | +| Promise\<[DataBlob](#datablob)> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error. | | 17630001 | crypto operation error. | -### verify +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Mac algName is: " + mac.algName); + +var KeyBlob; +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); +promiseConvertKey.then(symKey => { + var promiseMacInit = mac.init(symKey); + return promiseMacInit; +}).then(() => { + let blob; + var promiseMacUpdate = mac.update(blob); + return promiseMacUpdate; +}).then(() => { + var PromiseMacDoFinal = mac.doFinal(); + return PromiseMacDoFinal; +}).then(macOutput => { + console.error("[Promise]: HMAC result: " + macOutput.data); +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` + +### getMacLength -verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\) : void +getMacLength(): number -Verifies a signature. This API uses an asynchronous callback to return the result. +Obtains the MAC length, in bytes. **System capability**: SystemCapability.Security.CryptoFramework -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| ------------- | -------------------- | ---- | ---------- | -| data | [DataBlob](#datablob) | Yes | Data to pass in.| -| signatureData | [DataBlob](#datablob) | Yes | Signature data. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | +| Type | Description | +| ------ | --------------------------- | +| number | Returns the MAC length obtained.| **Error codes** | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | | 17630001 | crypto operation error. | -### verify +**Example** -verify(data : DataBlob, signatureData : DataBlob) : Promise\ +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -Verifies a signature. This API uses a promise to return the result. +var mac; +try { + mac = cryptoFramework.createMac("SHA256"); +} catch (error) { + console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); +} +console.error("Mac algName is: " + mac.algName); -**System capability**: SystemCapability.Security.CryptoFramework +var KeyBlob; +var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); +var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); +promiseConvertKey.then(symKey => { + var promiseMacInit = mac.init(symKey); + return promiseMacInit; +}).then(() => { + let blob; + var promiseMacUpdate = mac.update(blob); + return promiseMacUpdate; +}).then(() => { + var PromiseMacDoFinal = mac.doFinal(); + return PromiseMacDoFinal; +}).then(macOutput => { + console.error("[Promise]: HMAC result: " + macOutput.data); + let macLen = mac.getMacLength(); + console.error("MAC len: " + macLen); +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` -**Parameters** +## cryptoFramework.createRandom -| Name | Type | Mandatory| Description | -| ------------- | -------- | ---- | ---------- | -| data | [DataBlob](#datablob) | Yes | Data to pass in.| -| signatureData | [DataBlob](#datablob) | Yes | Signature data. | +createRandom(): Random + +Creates a **Random** instance for generating random numbers and setting seeds.
For details about the supported specifications, see [Random Number](../../security/cryptoFramework-overview.md#random-number). + +**System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| ----------------- | ---------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| ------ | ----------------------------------------------- | +| Random | Returns the [Random](#random) instance created.| **Error codes** -| ID| Error Message | -| -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | -| 17630001 | crypto operation error. | +| ID| Error Message | +| -------- | ------------ | +| 17620001 | memory error. | -**Callback example**: +**Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. -let input1 = null; -let input2 = null; -let signMessageBlob = null; // Signed data, which is omitted here. -let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25"); -verifyer.init(globalKeyPair.pubKey, function (err, data) { - verifyer.update(input1, function(err, data) { - verifyer.verify(input2, signMessageBlob, function(err, data) { - console.info("verify result is " + data); - }) - }); -}) +try { + var rand = cryptoFramework.createRandom(); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} ``` -**Promise example**: +## Random -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +Provides APIs for computing random numbers and setting seeds. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). -let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. -let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); -let verifyInitPromise = verifyer.init(globalKeyPair.pubKey); -let input1 = null; -let input2 = null; -let signMessageBlob = null; // Signed data, which is omitted here. -verifyInitPromise.then(() => { - return verifyer.update(input1); -}).then(() => { - return verifyer.verify(input2, signMessageBlob); -}).then(res => { - console.log("Verify result is " + res); -}); -``` +### Attributes -## cryptoFramework.createKeyAgreement +**System capability**: SystemCapability.Security.CryptoFramework -createKeyAgreement(algName : string) : KeyAgreement +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------- | +| algName10+ | string | Yes | No | Algorithm used to generate the random number. Currently, only **CTR_DRBG** is supported.| + +### generateRandom -Creates a **KeyAgreement** instance. +generateRandom(len: number, callback: AsyncCallback\): void -For details about the supported specifications, see [Key Agreement Specifications](../../security/cryptoFramework-overview.md#key-agreement-specifications). +Generates a random number of the specified length. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------- | -| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------- | +| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. | -**Return value** +**Error codes** -| Type | Description | -| ------------ | ---------------------------------------- | -| KeyAgreement | **KeyAgreement** instance created.| +| ID| Error Message | +| -------- | ---------------------- | +| 401 | invalid parameters. | +| 17620001 | memory error. | +| 17630001 | crypto operation error. | **Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); - +var rand; +try { + rand = cryptoFramework.createRandom(); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} +rand.generateRandom(12, (err, randData) => { + if (err) { + console.error("[Callback] err: " + err.code); + } else { + console.error("[Callback]: generate random result: " + randData.data); + } +}); ``` -## KeyAgreement +### generateRandom -Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**. +generateRandom(len: number): Promise\ -### Attributes +Generates a random number of the specified length. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | -| algName | string | Yes | No | Algorithm used for key agreement.| - -### generateSecret - -generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\) : void - -Generates a shared secret. This API uses an asynchronous callback to return the result. +**Parameters** -**System capability**: SystemCapability.Security.CryptoFramework +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------ | +| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ---------------------- | -| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| -| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the shared secret.| +| Type | Description | +| ------------------ | ----------- | +| Promise\<[DataBlob](#datablob)> | Promise that returns no value.| **Error codes** | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | +| 401 | invalid parameters. | +| 17620001 | memory error. | | 17630001 | crypto operation error. | -### generateSecret +**Example** + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" -generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\ +var rand; +try { + rand = cryptoFramework.createRandom(); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} -Generates a shared secret. This API uses a promise to return the result. +var promiseGenerateRand = rand.generateRandom(12); +promiseGenerateRand.then(randData => { + console.error("[Promise]: rand result: " + randData.data); +}).catch(error => { + console.error("[Promise]: error: " + error.message); +}); +``` + +### generateRandomSync10+ + +generateRandomSync(len: number): DataBlob + +Generates a random number of the specified length synchronously. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------- | -| priKey | [PriKey](#prikey) | Yes | Private key used for key agreement.| -| pubKey | [PubKey](#pubkey) | Yes | Public key used for key agreement.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| len | number | Yes | Length of the random number to generate, in bytes. The value range is [1, INT_MAX].| **Return value** -| Type | Description | -| ------------------ | -------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the shared secret.| +| Type | Description | +| ------------------ | ----------- | +|[DataBlob](#datablob) | Returns the generated random number.| **Error codes** | ID| Error Message | | -------- | ---------------------- | -| 17620001 | memory error. | -| 17620002 | runtime error. | +| 401 | invalid parameters. | +| 17620001 | memory error. | | 17630001 | crypto operation error. | -**Callback example**: +**Example** -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. -let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); -keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) { - if (err) { - console.error("keyAgreement error."); - return; +var rand; +try { + rand = cryptoFramework.createRandom(); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} + +try { + let randData = rand.generateRandomSync(12); + if (randData != null) { + console.info("[Sync]: rand result: " + randData.data); + } else { + console.error("[Sync]: get rand result fail!"); } - console.info("keyAgreement output is " + secret.data); -}); +} catch (error) { + console.error("[Sync]: error: " + error.message); +} ``` -**Promise example**: +### setSeed + +setSeed(seed: DataBlob): void + +Sets a seed. + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------ | +| seed | DataBlob | Yes | Seed to set.| + +**Error codes** -```javascript +| ID| Error Message | +| -------- | ----------------- | +| 17620001 | memory error. | + +**Example** + +```js import cryptoFramework from "@ohos.security.cryptoFramework" -let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. -let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); -let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey); -keyAgreementPromise.then((secret) => { - console.info("keyAgreement output is " + secret.data); -}).catch((error) => { - console.error("keyAgreement error."); +var rand; +try { + rand = cryptoFramework.createRandom(); +} catch (error) { + console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); +} + +rand.generateRandom(12, (err, randData) => { + if (err) { + console.error("[Callback] err: " + err.code); + } else { + console.error("[Callback]: generate random result: " + randData.data); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } }); ``` diff --git a/en/application-dev/reference/apis/js-apis-font.md b/en/application-dev/reference/apis/js-apis-font.md index 0b7d7fb3abcb1353d022e70ea785f6454cd422b4..dad280bb91d43d69f78f719cc8733fc212fec826 100644 --- a/en/application-dev/reference/apis/js-apis-font.md +++ b/en/application-dev/reference/apis/js-apis-font.md @@ -5,6 +5,8 @@ The **font** module provides APIs for registering custom fonts. > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. ## Modules to Import @@ -62,3 +64,104 @@ struct FontExample { } } ``` +## font.getSystemFontList + +getSystemFontList(): Array\ + +Obtains the list of supported fonts. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| -------------------- | ----------------- | +| Array\ | List of supported fonts. | + +## Example + +```ts +// xxx.ets +import font from '@ohos.font'; + +@Entry +@Component +struct FontExample { + fontList: Array; + build() { + Column() { + Button("getSystemFontList") + .width('60%') + .height('6%') + .onClick(()=>{ + this.fontList = font.getSystemFontList() + }) + }.width('100%') + } +} +``` + +## font.getFontByName + +getFontByName(fontName: string): FontInfo; + +Obtains information about a system font based on the font name. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | --------- | ------- | ------------ | +| fontName | string | Yes | System font name.| + +**Return value** + +| Type | Description | +| ---------------- | ---------------------------- | +| FontInfo | Information about the system font. | + +## FontInfo + +| Name | Type | Description | +| -------------- | ------- | ------------------------- | +| path | string | File path of the system font. | +| postScriptName | string | PostScript name of the system font.| +| fullName | string | Name of the system font. | +| family | string | Family of the system font. | +| subfamily | string | Subfamily of the system font. | +| weight | number | Weight of the system font. | +| width | number | Width of the system font. | +| italic | boolean | Whether the system font is italic. | +| monoSpace | boolean | Whether the system font is monospaced. | +| symbolic | boolean | Whether the system font supports symbols. | + +```ts +// xxx.ets +import font from '@ohos.font'; + +@Entry +@Component +struct FontExample { + fontList: Array; + fontInfo: font.FontInfo; + build() { + Column() { + Button("getFontByName") + .onClick(() => { + this.fontInfo = font.getFontByName('HarmonyOS Sans Italic') + console.log("getFontByName(): path = " + this.fontInfo.path) + console.log("getFontByName(): postScriptName = " + this.fontInfo.postScriptName) + console.log("getFontByName(): fullName = " + this.fontInfo.fullName) + console.log("getFontByName(): Family = " + this.fontInfo.family) + console.log("getFontByName(): Subfamily = " + this.fontInfo.subfamily) + console.log("getFontByName(): weight = " + this.fontInfo.weight) + console.log("getFontByName(): width = " + this.fontInfo.width) + console.log("getFontByName(): italic = " + this.fontInfo.italic) + console.log("getFontByName(): monoSpace = " + this.fontInfo.monoSpace) + console.log("getFontByName(): symbolic = " + this.fontInfo.symbolic) + }) + }.width('100%') + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 747e536b1a518b806f5df66f1efc2288d0c5bb80..aec61516c42598051c916d9314a842ca3deac5ae 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -41,8 +41,10 @@ Before developing applications related to tag read and write, you must declare N } ], "requestPermissions": [ - "name": "ohos.permission.NFC_TAG", - "reason": "tag", + { + "name": "ohos.permission.NFC_TAG", + "reason": "tag", + } ] } } diff --git a/en/application-dev/reference/apis/js-apis-plugincomponent.md b/en/application-dev/reference/apis/js-apis-plugincomponent.md index 618c2d3a50afd39131af6e914adc9e666eadc69e..0ae1baf6eebdadbbdc9d43de1e9c100ac73163db 100644 --- a/en/application-dev/reference/apis/js-apis-plugincomponent.md +++ b/en/application-dev/reference/apis/js-apis-plugincomponent.md @@ -4,7 +4,7 @@ The **PluginComponentManager** module provides APIs for the **PluginComponent** > **NOTE** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -18,10 +18,10 @@ Describes the **PluginComponent** template parameters. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | --------------------------- | -| source | string | Yes | Component template name. | -| bundleName | string | Yes | Bundle name of the provider ability.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ---------------------- | +| source | string | Yes | Component template name. | +| bundleName | string | Yes | Bundle name of the provider ability.| ## PluginComponentManager @@ -33,14 +33,14 @@ Stores information in key-value pairs in JSON format. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Value Range | Description | -| --------------------- | ---------------------------------------- | +| Value Range | Description | +| --------------------- | -------------------- | | [key: string] | Keyword. The value is a string and can be an empty string.| -| number | Key value of the number type. | +| number | Key value of the number type. | | string | Key value of the string type. The value can be an empty string.| -| boolean | Key value of the Boolean type. | -| [] | Key value. The value can be []. | -| [KVObject](#kvobject) | Key value of the KVObject type. | +| boolean | Key value of the Boolean type. | +| [] | Key value. The value can be []. | +| [KVObject](#kvobject) | Key value of the KVObject type. | ### PushParameters @@ -51,13 +51,13 @@ Sets the parameters to be passed in the **PluginManager.Push** API in the FA mod **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------- | ---- | -------------------------------------------------------------- | -| want | [Want](js-apis-application-want.md) | Yes | Ability information of the component user. | -| name | string | Yes | Component name. | -| data | [KVObject](#kvobject) | Yes | Component data value. | -| extraData | [KVObject](#kvobject) | Yes | Additional data value. | -| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path.| +| Name | Type | Mandatory | Description | +| --------- | ----------------------------------- | ---- | ---------------------------------------- | +| want | [Want](js-apis-application-want.md) | Yes | Ability information of the component user. | +| name | string | Yes | Component name. | +| data | [KVObject](#kvobject) | Yes | Component data value. | +| extraData | [KVObject](#kvobject) | Yes | Additional data value. | +| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path.| ### PushParameterForStage @@ -69,14 +69,14 @@ Sets the parameters to be passed in the **PluginManager.Push** API in the stage **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------- | ---- | ---------------------------------------------------------------- | -| owner | [Want](js-apis-application-want.md) | Yes | Ability information of the component provider. | -| target | [Want](js-apis-application-want.md) | Yes | Ability information of the component user. | -| name | string | Yes | Component name. | -| data | [KVObject](#kvobject) | Yes | Component data value. | -| extraData | [KVObject](#kvobject) | Yes | Additional data value. | -| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path.| +| Name | Type | Mandatory | Description | +| --------- | ----------------------------------- | ---- | ---------------------------------------- | +| owner | [Want](js-apis-application-want.md) | Yes | Ability information of the component provider. | +| target | [Want](js-apis-application-want.md) | Yes | Ability information of the component user. | +| name | string | Yes | Component name. | +| data | [KVObject](#kvobject) | Yes | Component data value. | +| extraData | [KVObject](#kvobject) | Yes | Additional data value. | +| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path.| ### RequestParameters @@ -86,12 +86,12 @@ Sets the parameters to be passed in the **PluginManager.Request** API in the FA **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | --------------------------------------------------------------------------------------------------------------------- | -| want | [Want](js-apis-application-want.md) | Yes | Ability information of the component provider. | -| name | string | Yes | Name of the requested component. | -| data | [KVObject](#kvobject) | Yes | Additional data. | -| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path. Request communication is not triggered when **jsonPath** is not empty or not set.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------------------- | +| want | [Want](js-apis-application-want.md) | Yes | Ability information of the component provider. | +| name | string | Yes | Name of the requested component. | +| data | [KVObject](#kvobject) | Yes | Additional data. | +| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path. Request communication is not triggered when **jsonPath** is not empty or not set.| ### RequestParameterForStage @@ -103,13 +103,13 @@ Sets the parameters to be passed in the **PluginManager.Request** API in the sta **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------- | ---- | --------------------------------------------------------------------------------------------------------------------- | -| owner | [Want](js-apis-application-want.md) | Yes | Ability information of the component user. | -| target | [Want](js-apis-application-want.md) | Yes | Ability information of the component provider. | -| name | string | Yes | Name of the requested component. | -| data | [KVObject](#kvobject) | Yes | Additional data. | -| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path. Request communication is not triggered when **jsonPath** is not empty or not set.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------------------- | +| owner | [Want](js-apis-application-want.md) | Yes | Ability information of the component user. | +| target | [Want](js-apis-application-want.md) | Yes | Ability information of the component provider. | +| name | string | Yes | Name of the requested component. | +| data | [KVObject](#kvobject) | Yes | Additional data. | +| jsonPath | string | No | Path to the [external.json](#about-the-externaljson-file) file that stores the template path. Request communication is not triggered when **jsonPath** is not empty or not set.| ### RequestCallbackParameters @@ -117,11 +117,11 @@ Provides the result returned after the **PluginManager.Request** API is called. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| ----------------- | --------------------------------------------------- | ---- | ---------- | -| componentTemplate | [PluginComponentTemplate](#plugincomponenttemplate) | Yes | Component template.| -| data | [KVObject](#kvobject) | Yes | Component data.| -| extraData | [KVObject](#kvobject) | Yes | Additional data.| +| Name | Type | Mandatory | Description | +| ----------------- | ---------------------------------------- | ---- | ----- | +| componentTemplate | [PluginComponentTemplate](#plugincomponenttemplate) | Yes | Component template.| +| data | [KVObject](#kvobject) | Yes | Component data.| +| extraData | [KVObject](#kvobject) | Yes | Additional data.| ### RequestEventResult @@ -129,11 +129,11 @@ Provides the result returned after the request listener is registered and the re **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory| Description | -| --------- | --------------------- | ---- | ---------- | -| template | string | No | Component template.| -| data | [KVObject](#kvobject) | No | Component data.| -| extraData | [KVObject](#kvobject) | No | Additional data.| +| Name | Type | Mandatory | Description | +| --------- | --------------------- | ---- | ----- | +| template | string | No | Component template.| +| data | [KVObject](#kvobject) | No | Component data.| +| extraData | [KVObject](#kvobject) | No | Additional data.| ### OnPushEventCallback @@ -144,12 +144,12 @@ Registers the listener for the push event. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | --------------------------------------------------- | ---- | ---------------------------------------- | -| source | [Want](js-apis-application-want.md) | Yes | Information about the push request sender. | -| template | [PluginComponentTemplate](#plugincomponenttemplate) | Yes | Name of the request component template for the push request sender.| -| data | [KVObject](#kvobject) | Yes | Data. | -| extraData | [KVObject](#kvobject) | Yes | Additional data. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | ---------------------- | +| source | [Want](js-apis-application-want.md) | Yes | Information about the push request sender. | +| template | [PluginComponentTemplate](#plugincomponenttemplate) | Yes | Name of the request component template for the push request sender.| +| data | [KVObject](#kvobject) | Yes | Data. | +| extraData | [KVObject](#kvobject) | Yes | Additional data. | **Example** @@ -172,11 +172,11 @@ Registers the listener for the request event. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------- | ---- | --------------------------- | -| source | [Want](js-apis-application-want.md) | Yes | Information about the request sender.| -| name | string | Yes | Template name. | -| extraData | [KVObject](#kvobject) | Yes | Additional data. | +| Name | Type | Mandatory | Description | +| --------- | ----------------------------------- | ---- | ----------------- | +| source | [Want](js-apis-application-want.md) | Yes | Information about the request sender.| +| name | string | Yes | Template name. | +| extraData | [KVObject](#kvobject) | Yes | Additional data. | **Example** @@ -200,10 +200,10 @@ Pushes the component and data to the component user. **Model restriction**: This API can be used only in the FA model. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ------------------------ | -| param | [PushParameters](#pushparameters) | Yes | Information about the component user. | -| callback | AsyncCallback<void> | Yes | Asynchronous callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------------- | ---- | ------------ | +| param | [PushParameters](#pushparameters) | Yes | Information about the component user. | +| callback | AsyncCallback<void> | Yes | Asynchronous callback used to return the result.| **Example** @@ -241,10 +241,10 @@ Pushes the component and data to the component user. **Model restriction**: This API can be used only in the stage model. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | ------------------------ | -| param | [PushParameterForStage](#pushparameterforstage) | Yes | Information about the component user. | -| callback | AsyncCallback<void> | Yes | Asynchronous callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------ | +| param | [PushParameterForStage](#pushparameterforstage) | Yes | Information about the component user. | +| callback | AsyncCallback<void> | Yes | Asynchronous callback used to return the result.| **Example** @@ -289,10 +289,10 @@ Requests the component from the component provider. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------------------- | -| param | [RequestParameters](#requestparameters) | Yes | Information about the component request. | -| callback | AsyncCallback<[RequestCallbackParameters](#requestcallbackparameters) \| void> | Yes | Asynchronous callback used to return the requested data.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------------- | +| param | [RequestParameters](#requestparameters) | Yes | Information about the component request. | +| callback | AsyncCallback<[RequestCallbackParameters](#requestcallbackparameters) \| void> | Yes | Asynchronous callback used to return the requested data.| **Example** @@ -332,10 +332,10 @@ Requests the component from the component provider. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------------------------------------------------------- | ---- | ---------------------------------------------------------------- | -| param | [RequestParameterForStage](#requestparameterforstage) | Yes | Information about the component request. | -| callback | AsyncCallback<[RequestCallbackParameters](#requestcallbackparameters) \| void> | Yes | Asynchronous callback used to return the requested data.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------------- | +| param | [RequestParameterForStage](#requestparameterforstage) | Yes | Information about the component request. | +| callback | AsyncCallback<[RequestCallbackParameters](#requestcallbackparameters) \| void> | Yes | Asynchronous callback used to return the requested data.| **Example** @@ -371,10 +371,10 @@ Listens for events of the request type and returns the requested data, or listen **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ---------------------------------------------------------------------------------------------------------- | ---- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| eventType | string | Yes | Type of the event to listen for. The options are as follows:
**"push"**: The component provider pushes data to the component consumer.
**"request"**: The component consumer proactively requests data from the component provider. | -| callback | [OnPushEventCallback](#onpusheventcallback) \| [OnRequestEventCallback](#onrequesteventcallback) | Yes | Callback used to return the result. The type is [OnPushEventCallback](#onpusheventcallback) for the push event and [OnRequestEventCallback](#onrequesteventcallback) for the request event.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | ---------------------------------------- | +| eventType | string | Yes | Type of the event to listen for. The options are as follows:
**"push"**: The component provider pushes data to the component consumer.
**"request"**: The component consumer proactively requests data from the component provider.| +| callback | [OnPushEventCallback](#onpusheventcallback) \| [OnRequestEventCallback](#onrequesteventcallback) | Yes | Callback used to return the result. The type is [OnPushEventCallback](#onpusheventcallback) for the push event and [OnRequestEventCallback](#onrequesteventcallback) for the request event.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index 956f922e5414eb058e15ac7f52daba1c8d8db8cf..a5334a26084d30eafb4f914ea3f7fe8d457267f7 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -63,42 +63,6 @@ struct WebComponent { Implements a **WebMessagePort** object to send and receive messages. -### close - -close(): void - -Closes this message port. - -**System capability**: SystemCapability.Web.Webview.Core - -**Example** - -```ts -// xxx.ets -import web_webview from '@ohos.web.webview' - -@Entry -@Component -struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - msgPort: web_webview.WebMessagePort[] = null; - - build() { - Column() { - Button('close') - .onClick(() => { - if (this.msgPort && this.msgPort[1]) { - this.msgPort[1].close(); - } else { - console.error("msgPort is null, Please initialize first"); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } -} -``` - ### postMessageEvent postMessageEvent(message: WebMessage): void @@ -364,6 +328,7 @@ struct WebComponent { } ``` +HTML file to be loaded: ```html @@ -448,6 +413,56 @@ function postStringToApp() { } ``` +### close + +close(): void + +Closes this message port. To use this API, a message port must first be created using [createWebMessagePorts](#createwebmessageports). + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + msgPort: web_webview.WebMessagePort[] = null; + + build() { + Column() { + // Use createWebMessagePorts to create a message port. + Button('createWebMessagePorts') + .onClick(() => { + try { + this.msgPort = this.controller.createWebMessagePorts(); + console.log("createWebMessagePorts size:" + this.msgPort.length) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Button('close') + .onClick(() => { + try { + if (this.msgPort && this.msgPort.length == 2) { + this.msgPort[1].close(); + } else { + console.error("msgPort is null, Please initialize first"); + } + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ## WebviewController Implements a **WebviewController** to control the behavior of the **\** component. A **WebviewController** can control only one **\** component, and the APIs (except static APIs) in the **WebviewController** can be invoked only after it has been bound to the target **\** component. @@ -473,7 +488,6 @@ export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { console.log("EntryAbility onCreate") web_webview.WebviewController.initializeWebEngine() - globalThis.abilityWant = want console.log("EntryAbility onCreate done") } } @@ -516,30 +530,11 @@ export default class EntryAbility extends UIAbility { } ``` -### Creating an Object - -```ts -// xxx.ets -import web_webview from '@ohos.web.webview'; - -@Entry -@Component -struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - - build() { - Column() { - Web({ src: 'www.example.com', controller: this.controller }) - } - } -} -``` - ### setWebDebuggingAccess static setWebDebuggingAccess(webDebuggingAccess: boolean): void -Sets whether to enable web debugging. +Sets whether to enable web debugging. For details, see [Debugging Frontend Pages by Using DevTools](../../web/web-debugging-with-devtools.md). **System capability**: SystemCapability.Web.Webview.Core @@ -656,70 +651,73 @@ struct WebComponent { ``` There are three methods for loading local resource files: -1. Using $rawfile -```ts -// xxx.ets -import web_webview from '@ohos.web.webview' -@Entry -@Component -struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); +1. Using $rawfile + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // Load a local resource file through $rawfile. + this.controller.loadUrl($rawfile('index.html')); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` - build() { - Column() { - Button('loadUrl') - .onClick(() => { - try { - // Load a local resource file through $rawfile. - this.controller.loadUrl($rawfile('xxx.html')); - } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } -} -``` 2. Using the resources protocol -```ts -// xxx.ets -import web_webview from '@ohos.web.webview' - -@Entry -@Component -struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController(); - - build() { - Column() { - Button('loadUrl') - .onClick(() => { - try { - // Load a local resource file through the resource protocol. - this.controller.loadUrl("resource://rawfile/xxx.html"); - } catch (error) { - console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); - } - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } -} -``` + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // Load a local resource file through the resource protocol. + this.controller.loadUrl("resource://rawfile/index.html"); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` 3. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](../arkui-ts/ts-basic-components-web.md#web). -```html - - - - -

Hello World

- - -``` + HTML file to be loaded: + ```html + + + + +

Hello World

+ + + ``` ### loadData @@ -1343,6 +1341,24 @@ struct Index { } ``` +HTML file to be loaded: +```html + + + + + + Hello world! + + + +``` + ### runJavaScript runJavaScript(script: string, callback : AsyncCallback\): void @@ -1406,6 +1422,24 @@ struct WebComponent { } ``` +HTML file to be loaded: +```html + + + + + + Hello world! + + + +``` + ### runJavaScript runJavaScript(script: string): Promise\ @@ -1444,11 +1478,9 @@ import web_webview from '@ohos.web.webview' @Component struct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController(); - @State webResult: string = ''; build() { Column() { - Text(this.webResult).fontSize(20) Web({ src: $rawfile('index.html'), controller: this.controller }) .javaScriptAccess(true) .onPageEnd(e => { @@ -1470,6 +1502,23 @@ struct WebComponent { } ``` +HTML file to be loaded: +```html + + + + + + Hello world! + + + +``` ### runJavaScriptExt10+ @@ -1569,8 +1618,11 @@ struct WebComponent { } } } +``` -//index.html +HTML file to be loaded: +```html + @@ -1681,8 +1733,11 @@ struct WebComponent { } } } +``` -//index.html +HTML file to be loaded: +```html + @@ -2178,14 +2233,15 @@ struct WebComponent { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } }) - Web({ src: $rawfile('xxx.html'), controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` +HTML file to be loaded: ```html - + @@ -2973,14 +3029,15 @@ struct WebComponent { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } }) - Web({ src: 'www.example.com', controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` +HTML file to be loaded: ```html - + @@ -3045,14 +3102,15 @@ struct WebComponent { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } }) - Web({ src: 'www.example.com', controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` +HTML file to be loaded: ```html - + @@ -3117,14 +3175,15 @@ struct WebComponent { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } }) - Web({ src: 'www.example.com', controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` +HTML file to be loaded: ```html - + @@ -3640,7 +3699,7 @@ struct WebComponent { .onClick(() => { try { let state = this.controller.serializeWebState(); - // Obtain the value of globalThis.cacheDir from MainAbility.ts. + // globalThis.cacheDir is obtained from EntryAbility.ts. let path = globalThis.cacheDir; path += '/WebState'; // Synchronously open a file. @@ -3657,14 +3716,14 @@ struct WebComponent { } ``` -2. Modify **MainAbility.ts**. +2. Modify the **EntryAbility.ts** file. Obtain the path of the application cache file. ```ts // xxx.ts import UIAbility from '@ohos.app.ability.UIAbility'; import web_webview from '@ohos.web.webview'; -export default class MainAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { // Bind cacheDir to the globalThis object to implement data synchronization between the UIAbility component and the page. globalThis.cacheDir = this.context.cacheDir; @@ -3712,7 +3771,7 @@ struct WebComponent { Button('RestoreWebState') .onClick(() => { try { - // Obtain the value of globalThis.cacheDir from MainAbility.ts. + // globalThis.cacheDir is obtained from EntryAbility.ts. let path = globalThis.cacheDir; path += '/WebState'; // Synchronously open a file. @@ -3739,14 +3798,14 @@ struct WebComponent { } ``` -2. Modify **MainAbility.ts**. +2. Modify the **EntryAbility.ts** file. Obtain the path of the application cache file. ```ts // xxx.ts import UIAbility from '@ohos.app.ability.UIAbility'; import web_webview from '@ohos.web.webview'; -export default class MainAbility extends UIAbility { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { // Bind cacheDir to the globalThis object to implement data synchronization between the UIAbility component and the page. globalThis.cacheDir = this.context.cacheDir; @@ -6230,6 +6289,9 @@ Describes the mode in which the **\** component uses HTTPDNS. | Name | Value| Description | | ------------- | -- |----------------------------------------- | -| Off | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.| -| Auto | 1 |HTTPDNS is used in automatic mode. When the specified HTTPDNS server is unavailable for resolution, the component will fall back to the system DNS server.| -| SecureOnly | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.| +| Off(deprecated) | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.
This API is deprecated since API version 10. You are advised to use **OFF** instead.| +| Auto(deprecated) | 1 |HTTPDNS is used in automatic mode. When the specified HTTPDNS server is unavailable for resolution, the component will fall back to the system DNS server.
This API is deprecated since API version 10. You are advised to use **AUTO** instead.| +| SecureOnly(deprecated) | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.
This API is deprecated since API version 10. You are advised to use **SECURE_ONLY** instead.| +| OFF | 0 |HTTPDNS is not used. This value can be used to revoke the previously used HTTPDNS configuration.| +| AUTO | 1 |HTTPDNS is used in automatic mode. When the specified HTTPDNS server is unavailable for resolution, the component will fall back to the system DNS server.| +| SECURE_ONLY | 2 |The specified HTTPDNS server is forcibly used for DNS resolution.| diff --git a/en/application-dev/reference/arkui-ts/Readme-EN.md b/en/application-dev/reference/arkui-ts/Readme-EN.md index bb367dd6c32061334312afe76f0acee149f06bee..a1408eba5cdd14511f6f1be10288e9c641bd8522 100644 --- a/en/application-dev/reference/arkui-ts/Readme-EN.md +++ b/en/application-dev/reference/arkui-ts/Readme-EN.md @@ -12,7 +12,7 @@ - [Mouse Event](ts-universal-mouse-key.md) - [Component Area Change Event](ts-universal-component-area-change-event.md) - [Visible Area Change Event](ts-universal-component-visible-area-change-event.md) - - [Custom Keyboard Shortcuts](ts-universal-events-keyboardshortcut.md) + - [Component Keyboard Shortcut Event](ts-universal-events-keyboardshortcut.md) - Universal Attributes - [Size](ts-universal-attributes-size.md) - [Location](ts-universal-attributes-location.md) @@ -43,7 +43,7 @@ - Touch Interactions - [Touch Target](ts-universal-attributes-touch-target.md) - [Hit Test Control](ts-universal-attributes-hit-test-behavior.md) - - Touch Interactions + - Transition - [Modal Transition](ts-universal-attributes-modal-transition.md) - [Sheet Transition](ts-universal-attributes-sheet-transition.md) - [Obscuring](ts-universal-attributes-obscured.md) diff --git a/en/application-dev/reference/arkui-ts/figures/arkts-progress.png b/en/application-dev/reference/arkui-ts/figures/arkts-progress.png new file mode 100644 index 0000000000000000000000000000000000000000..8e16510ddae266f037cce57857c3dc2ecc14ce2e Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/arkts-progress.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/deleteListItem.gif b/en/application-dev/reference/arkui-ts/figures/deleteListItem.gif new file mode 100644 index 0000000000000000000000000000000000000000..5c2c529ef670b83df2e4bd261bbddfe6bca7e7ef Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/deleteListItem.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352468.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352468.gif deleted file mode 100644 index 58feeb2988e8d9a643234691ae4d5cf5ccef6d4f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001194352468.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_1501929990650.jpg b/en/application-dev/reference/arkui-ts/figures/en-us_image_1501929990650.jpg deleted file mode 100644 index ca0ec86c6c71b6c6daa60bf3ee43795f33568c64..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_1501929990650.jpg and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/progress.png b/en/application-dev/reference/arkui-ts/figures/progress.png deleted file mode 100644 index d50f4b47628b425b09f93bc9a44853ad79e12631..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/progress.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md index 35b8c458af2de6981fb47703039e07ee47b3a6b1..0753b4ab4dc8028e3747f8905b1032f2a099bcfc 100644 --- a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md +++ b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md @@ -557,3 +557,10 @@ This API is supported in ArkTS widgets. | LIGHT | Small area (light)| Spring effect, with stiffness of 410, damping of 38, and initial velocity of 1.| 90% | | MIDDLE | Medium area (stable)| Spring effect, with stiffness of 350, damping of 35, and initial velocity of 0.5.| 95% | | HEAVY | Large area (heavy)| Spring effect, with stiffness of 240, damping of 28, and initial velocity of 0.| 95% | + +## TextContentStyle10+ + +| Name | Description | +| ------- | ------------------------------------------------------------ | +| DEFAULT | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text.| +| INLINE | Inline input style. The background height of the selected text is the same as the height of the text box. | diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index ad23abd051a1cae666be7b4038e86fba30147fcc..2a0e870a9d2be12b1202e3ed36d53f7e22480a49 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -21,7 +21,7 @@ Not supported Image(src: PixelMap | ResourceStr | DrawableDescriptor) -Obtains an image from the specified source for subsequent rendering and display. +Obtains an image from the specified source for subsequent rendering and display. If the **\** component fails to obtain the image or the obtained image size is 0, the **\** component is automatically resized to 0 and does not follow the layout constraints of its parent component. Since API version 9, this API is supported in ArkTS widgets. @@ -29,7 +29,7 @@ Since API version 9, this API is supported in ArkTS widgets. | Name | Type | Mandatory | Description | | ---- | ---------------------------------------- | ---- | ---------------------------------------- | -| src | [PixelMap](../apis/js-apis-image.md#pixelmap7) \| ResourceStr\| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://** prefix are supported, which are used to access the image path provided by a Data ability.
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the current application. Ensure that the application has the read permission to the files in the specified path.
\- [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) objects are supported.
- For details, see [Displaying Images](../../ui/arkts-graphics-display.md).
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http://**, **datashare://**, or **file:///data/storage** prefix.
- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.| +| src | [PixelMap](../apis/js-apis-image.md#pixelmap7) \|ResourceStr\| [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use **\$r** to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.
\- Strings with the **datashare://** prefix are supported, which are used to access the image path provided by a Data ability.
\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the current application. Ensure that the application has the read permission to the files in the specified path.
\- [DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) objects are supported.
- For details, see [Displaying Images](../../ui/arkts-graphics-display.md).
**NOTE**
- ArkTS widgets support GIF animations, but the animations only play once on display.
- ArkTS widgets do not support the strings with the **http://**, **datashare://**, or **file:///data/storage** prefix.
- ArkTS widgets do not support the [PixelMap](../apis/js-apis-image.md#pixelmap7) type.| ## Attributes @@ -50,7 +50,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | syncLoad8+ | boolean | Whether to load the image synchronously. By default, the image is loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed.
Default value: **false**
Since API version 9, this API is supported in ArkTS widgets.| | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether the image can be copied. (SVG images cannot be copied.)
When **copyOption** is set to a value other than **CopyOptions.None**, the image can be copied in various manners, such as long pressing, right-clicking, or pressing Ctrl+C.
Default value: **CopyOptions.None**
This API is supported in ArkTS widgets.| | colorFilter9+ | [ColorFilter](ts-types.md#colorfilter9) | Color filter of the image.
This API is supported in ArkTS widgets. | -| draggable9+ | boolean | Whether the image is draggable. This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**
This API is supported in ArkTS widgets.| +| draggable(deprecated) | boolean | Whether the image is draggable. This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
Default value: **false**
This API is supported in ArkTS widgets.
**NOTE**
This API is supported since API version 8 and deprecated since API version 10. You are advised to use the universal attribute [draggable](ts-universal-events-drag-drop.md) instead.| > **NOTE** > diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md index 459984f79d30f81c7d9d276077038972f743a201..ef810a8be61e6dc14a8ccba62714a3f8bbe1b06e 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-progress.md @@ -1,6 +1,6 @@ # Progress -The **\** component is used to provide a progress indicator that displays the progress of content loading or an operation. +The **\** component represents a progress indicator that displays the progress of content loading or an operation. > **NOTE** > @@ -22,47 +22,77 @@ Since API version 9, this API is supported in ArkTS widgets. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | number | Yes| Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used.
Since API version 9, this API is supported in ArkTS widgets.| -| total | number | No| Total progress.
Default value: **100**
Since API version 9, this API is supported in ArkTS widgets.| -| type8+ | [ProgressType](#progresstype) | No| Style the progress indicator.
Default value: **ProgressType.Linear**
Since API version 9, this API is supported in ArkTS widgets.| -| styledeprecated | [ProgressStyle](#progressstyle) | No| Type of the progress indicator.
This parameter is deprecated since API version 8. You are advised to use **type** instead.
Default value: **ProgressStyle.Linear**| +| Name | Type | Mandatory | Description | +| -------------------------- | ----------------------------------- | ---- | ---------------------------------------- | +| value | number | Yes | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used.
Since API version 9, this API is supported in ArkTS widgets.| +| total | number | No | Total progress.
Default value: **100**
Since API version 9, this API is supported in ArkTS widgets.| +| type8+ | [ProgressType](#progresstype) | No | Style of the progress indicator.
Default value: **ProgressType.Linear**
Since API version 9, this API is supported in ArkTS widgets.| +| styledeprecated | [ProgressStyle](#progressstyle) | No | Style of the progress indicator.
This parameter is deprecated since API version 8. You are advised to use **type** instead.
Default value: **ProgressStyle.Linear**| ## ProgressType Since API version 9, this API is supported in ArkTS widgets. -| Name| Description| -| -------- | -------- | -| Linear | Linear type. Since API version 9, the progress indicator adaptively switches to vertical layout if the height is greater than the width.| -| Ring8+ | Indeterminate ring type. The ring fills up as the progress increases.| -| Eclipse8+ | Eclipse type, which visualizes the progress in a way similar to the moon waxing from new to full.| -| ScaleRing8+ | Determinate ring type, which is similar to the clock scale. Since API version 9, when the outer circles of scales overlap, the progress indicator is automatically converted to the **Ring** type.| -| Capsule8+ | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.| +| Name | Description | +| ---------------------- | ---------------------------------------- | +| Linear | Linear style. Since API version 9, the progress indicator adaptively switches to vertical layout if the height is greater than the width. | +| Ring8+ | Indeterminate ring style. The ring fills up as the progress increases. | +| Eclipse8+ | Eclipse style, which visualizes the progress in a way similar to the moon waxing from new to full. | +| ScaleRing8+ | Determinate ring style, which is similar to the clock scale. Since API version 9, when the outer circles of scales overlap, the progress indicator is automatically converted to the **Ring** style.| +| Capsule8+ | Capsule style. At both ends, the progress indicator works in a same manner as the eclipse style. In the middle part of the capsule, the progress indicator works in a same manner as the linear style. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.| ## ProgressStyle Since API version 9, this API is supported in ArkTS widgets. -| Name | Description | -| --------- | ------------------------------------------------------------ | -| Linear | Linear type.| -| Ring | Indeterminate ring type. The ring fills up as the progress increases.| -| Eclipse | Eclipse type, which visualizes the progress in a way similar to the moon waxing from new to full.| -| ScaleRing | Determinate ring type, which is similar to the clock scale.| -| Capsule | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.| +| Name | Description | +| --------- | ---------------------------------------- | +| Linear | Linear style. | +| Ring | Indeterminate ring style. The ring fills up as the progress increases. | +| Eclipse | Eclipse style, which visualizes the progress in a way similar to the moon waxing from new to full. | +| ScaleRing | Determinate ring style, which is similar to the clock scale. | +| Capsule | Capsule style. At both ends, the progress indicator works in a same manner as the eclipse style. In the middle part of the capsule, the progress indicator works in a same manner as the linear style. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Description| -| -------- | -------- | -------- | -| value | number | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used. Invalid values do not take effect.
Since API version 9, this API is supported in ArkTS widgets.| -| color | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.
Default value: **'\#ff007dff'**
Since API version 9, this API is supported in ArkTS widgets.| -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.
Default value: **'\#19182431'**

Since API version 9, this API is supported in ArkTS widgets.| -| style8+ | {
strokeWidth?: [Length](ts-types.md#length),
scaleCount?: number,
scaleWidth?: [Length](ts-types.md#length)
} | Component style.
- **strokeWidth**: stroke width of the progress indicator. It cannot be set in percentage. Since API version 9, if the stroke width of the ring progress bar is greater than or equal to the radius, the width is changed to half of the radius.
Default value: **4.0Vp**
- **scaleCount**: number of divisions on the determinate ring-type process indicator.
Default value: **120**
- **scaleWidth**: scale width of the ring progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.
Default value: **2.0Vp**
Since API version 9, this API is supported in ArkTS widgets.| +| Name | Type | Description | +| ------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| value | number | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used. Invalid values do not take effect.
Since API version 9, this API is supported in ArkTS widgets.| +| color | [ResourceColor](ts-types.md#resourcecolor) \| [LinearGradient10+](ts-basic-components-datapanel.md#lineargradient10) | Background color of the progress indicator. Since API version 10, this attribute can be set to **LinearGradient** for the **Ring** style.
Default value (API version 9): **'\#ff007dff'**
Default value (API version 10):
- Capsule: **'\#33006cde'**
- Ring: starting point: **'\#ff3b61f7'**, ending point: **'\#ff6591bf'**
- Other styles: **'\#ff007dff'**
Since API version 9, this API is supported in ArkTS widgets, except that **LinearGradient** is not supported.| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.
Default value (API version 9): **'\#19182431'**
Default value (API version 10):
- Capsule: **'\#33ffffff'**
- Ring: **'\#08182431'**
- Other styles: **'\#19182431'**
Since API version 9, this API is supported in ArkTS widgets.
**NOTE**
The settings of the universal attribute [backgroundColor](./ts-universal-attributes-background.md) applies to the progress indicator instead of the entire **\** component.| +| style8+ | [ProgressStyleOptions](#progressstyleoptions) \| [CapsuleStyleOptions10+](#capsulestyleoptions10) \| [RingStyleOptions10+](#ringstyleoptions10) | Component style. Since API version 10, this attribute can be set to **CapsuleStyleOptions** or **RingStyleOptions**.
- **CapsuleStyleOptions** is available for the **Capsule** style.
- **RingStyleOptions** is available for the **Ring** style.
- **ProgressStyleOptions** is available for other styles.
Since API version 9, this API is supported in ArkTS widgets, except that **CapsuleStyleOptions** and **RingStyleOptions** are not supported.| + +## ProgressStyleOptions +| Name | Type | Mandatory| Description | +| ------------ | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | +| strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage.
Default value: **4.0Vp** | +| scaleCount | number | No | Number of divisions on the ring-style process indicator.
Default value: **120** | +| scaleWidth | [Length](ts-types.md#length) | No | Scale width of the ring-style progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.
Default value: **2.0Vp**| + +## CapsuleStyleOptions10+ +| Name | Type| Mandatory| Description| +| ------------- | ------- | ---- | -------- | +| borderColor | [ResourceColor](ts-types.md#resourcecolor) | No| Border color.
Default value: **'\#33006cde'**| +| borderWidth | [Length](ts-types.md#length) | No| Border width. It cannot be set in percentage.
Default value: **1 Vp**| +| content | string | No| Text content, which can be customized .| +| font | [Font](ts-types.md#font) | No| Text style.
Default value:
- Font size (cannot be set in percentage): **12Fp**
- Other attributes: following the settings of the **\** component.| +| fontColor | [ResourceColor](ts-types.md#resourcecolor) | No| Font color.
Default value: **'\#ff182431'**| +| enableScanEffect | boolean | No| Whether to enable the scan effect.
Default value: **false**| + +## RingStyleOptions10+ +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------- | ---- | ------------------------------------------------------------------------------------------ | +| strokeWidth | [Length](ts-types.md#length) | No | Stroke width of the progress indicator. It cannot be set in percentage. A value greater than or equal to the radius evaluates to half of the radius.
Default value: **4Vp**| +| shadow | boolean | No | Whether to enable the shadow effect.
Default value: **false** | +| status | [ProgressStatus10+](#progressstatus10) | No| Status of the progress indicator. When this parameter is set to **LOADING**, the **value** settings do not take effect.
Default value: **ProgressStatus.PROGRESSING**| + +## ProgressStatus10+ +| Name | Description | +| ----------------------- | ---------------- | +| LOADING10+ | Loading.| +| PROGRESSING10+ | The progress is being updated.| ## Events @@ -111,7 +141,7 @@ struct ProgressExample { Progress({ value: 10, type: ProgressType.Ring }).width(100) Progress({ value: 20, total: 150, type: ProgressType.Ring }) .color(Color.Grey).value(50).width(100) - .style({ strokeWidth: 20, scaleCount: 30, scaleWidth: 20 }) + .style({ strokeWidth: 20 }) } Text('Capsule Progress').fontSize(9).fontColor(0xCCCCCC).width('90%') @@ -128,4 +158,4 @@ struct ProgressExample { } ``` -![progress](figures/progress.png) +![progress](figures/arkts-progress.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-select.md b/en/application-dev/reference/arkui-ts/ts-basic-components-select.md index 06ea2a8cfc12b54048c6a91c70313fcc48c876f9..834d98d902de5e5bc0244201cae0b2455ccbcb15 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-select.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-select.md @@ -28,17 +28,18 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | ----------------------- | ------------------------------------- | --------------------------------------------- | | selected | number | Index of the initial selected option in the drop-down list box. The index of the first option is **0**.
If this attribute is not set, the default value **-1** is used, indicating that no option is selected.
Since API version 10, this attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| -| value | string | Text of the drop-down button. By default, it will be replaced by the content of the selected option.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| -| font | [Font](ts-types.md#font) | Text font of the drop-down button.
Default value:
{
size: '16fp',
weight: FontWeight.Medium
} | +| value | string | Text of the drop-down button. By default, it will be replaced by the content of the selected option.
Since API version 10, this attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables. | +| font | [Font](ts-types.md#font) | Text font of the drop-down button.
Default value:
{
size: '16fp',
weight: FontWeight.Medium
} | | fontColor | [ResourceColor](ts-types.md#resourcecolor) | Text color of the drop-down button.
Default value: **'\#E6FFFFFF'**| | selectedOptionBgColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected option in the drop-down list box.
Default value: **'\#33007DFF'**| -| selectedOptionFont | [Font](ts-types.md#font) | Text font of the selected option in the drop-down list box.
Default value:
{
size: '16fp',
weight: FontWeight.Regular
} | +| selectedOptionFont | [Font](ts-types.md#font) | Text font of the selected option in the drop-down list box.
Default value:
{
size: '16fp',
weight: FontWeight.Regular
} | | selectedOptionFontColor | [ResourceColor](ts-types.md#resourcecolor) | Text color of the selected option in the drop-down list box.
Default value: **'\#ff007dff'**| | optionBgColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of an option in the drop-down list box.
Default value: **'\#ffffffff'**| -| optionFont | [Font](ts-types.md#font) | Text font of an option in the drop-down list box.
Default value:
{
size: '16fp',
weight: FontWeight.Regular
} | +| optionFont | [Font](ts-types.md#font) | Text font of an option in the drop-down list box.
Default value:
{
size: '16fp',
weight: FontWeight.Regular
} | | optionFontColor | [ResourceColor](ts-types.md#resourcecolor) | Text color of an option in the drop-down list box.
Default value: **'\#ff182431'**| | space10+ | [Length](ts-types.md#length) | Spacing between the text and arrow of an option.
**NOTE**
This attribute cannot be set in percentage.| | arrowPosition10+ | [ArrowPosition](#arrowposition10) | Alignment between the text and arrow of an option.
Default value: **ArrowPosition.END**| +| menuAlign10+ | alignType: [MenuAlignType](#menualigntype10),
offset?: [Offset](ts-types.md#offset) | Alignment between the drop-down button and the drop-down menu.
- **alignType**: alignment type. Mandatory.
- **offset**: offset of the drop-down menu relative to the drop-down button after alignment based on the specified alignment type.
Default value: **{dx: 0, dy: 0}**| ## ArrowPosition10+ @@ -47,11 +48,20 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | END10+ | The text is in front of the arrow.| | START10+ | The arrow is in front of the text.| + +## MenuAlignType10+ + +| Name | Description | +| ------------------- | ------------------ | +| START | Aligned with the start edge in the same direction as the language in use.| +| CENTER | Aligned with the center.| +| END | Aligned with the end edge in the same direction as the language in use.| + ## Events | Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| onSelect(callback: (index: number, value?: string) => void) | Invoked when an option in the drop-down list box is selected.
**index**: index of the selected option.
**value**: value of the selected option.| +| onSelect(callback: (index: number, value?: string) => void) | Invoked when an option in the drop-down list box is selected.
**index**: index of the selected option.
**value**: value of the selected option.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md index f3af7b67cb3eb17ada3be85777566ce874b1a72e..f9b6aa5f9194f41300fd0229c191eca891e5a435 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textarea.md @@ -20,29 +20,32 @@ TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Tex | Name | Type | Mandatory | Description | | ----------------------- | ---------------------------------------- | ---- | -------------- | -| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when there is no input. It is not displayed once there is any input. | +| placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when no text input is set.
When only the **placeholder** attribute is set, the text selection handle is still available; and the caret moves back to the beginning of the placeholder text when the handle is released. | | text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event,
so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| | controller8+ | [TextAreaController](#textareacontroller8) | No | Text area controller.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. - -| Name | Type | Description | -| ------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. | -| placeholderFont | [Font](ts-types.md#font) | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported.| -| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**| -| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | -| inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but the copy and cut operations are not.| +Among the [universal attributes](ts-universal-attributes-size.md) and [universal text attributes](ts-universal-attributes-text-style.md), **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are supported. In addition, the following attributes are supported. + +| Name | Type | Description | +| ------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.
The default value follows the theme. | +| placeholderFont | [Font](ts-types.md#font) | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported.| +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**
**NOTE**
Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.
To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text.| +| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box.
Default value: **'#007DFF'** | +| inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.LocalDevice**
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but the copy and cut operations are not.| +| maxLength10+ | number | Maximum number of characters in the text input.
By default, there is no maximum number of characters.| +| showCounter10+ | boolean | Whether to show the number of entered characters when **maxLength** is set.
Default value: **false** | +| style10+ | [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Style of the component.
Default value: **TextContentStyle.DEFAULT** | +| enableKeyboardOnFocus10+ | boolean | Whether to enable the input method when the component obtains focus.
Default value: **true** | > **NOTE** > > The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:
{
top: 8 vp,
right: 16 vp,
bottom: 8 vp,
left: 16 vp
} - ## Events In addition to the [universal events](ts-universal-events-click.md), the following events are supported. diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md index 588f88057abe66a553dd25dc8337503b8786e65a..671ce23c08205a55ccd244fbe098efda7394e6f9 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textinput.md @@ -21,30 +21,35 @@ TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: Te | Name | Type | Mandatory | Description | | ----------------------- | ---------------------------------------- | ---- | --------------- | | placeholder | [ResourceStr](ts-types.md#resourcestr) | No | Placeholder text displayed when there is no input. | -| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event,
so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| +| text | [ResourceStr](ts-types.md#resourcestr) | No | Current text input.
If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event, so as to prevent display errors when the component is updated.
Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables. | | controller8+ | [TextInputController](#textinputcontroller8) | No | Text input controller.| ## Attributes -In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. +Among the [universal attributes](ts-universal-attributes-size.md) and [universal text attributes](ts-universal-attributes-text-style.md), **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are supported. In addition, the following attributes are supported. | Name | Type | Description | | ------------------------ | ---------------------------------------- | ---------------------------------------- | | type | [InputType](#inputtype) | Input box type.
Default value: **InputType.Normal** | -| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.| +| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.
The default value follows the theme. | | placeholderFont | [Font](ts-types.md#font) | Placeholder text font.| | enterKeyType | [EnterKeyType](#enterkeytype) | Type of the Enter key. Currently, only the default value is supported.
Default value: **EnterKeyType.Done**| -| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box. | +| caretColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the caret in the text box.
Default value: **'#007DFF'** | | maxLength | number | Maximum number of characters in the text input. | | inputFilter8+ | {
value: [ResourceStr](ts-types.md#resourcestr),
error?: (value: string) => void
} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The regular expression can match single characters, but not strings.
- **value**: regular expression to set.
- **error**: filtered-out content to return when regular expression matching fails.| -| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.| -| showPasswordIcon9+ | boolean | Whether to display the show password icon at the end of the password text box.
Default value: **true**| -| style9+ | [TextInputStyle](#textinputstyle9) | Text input style.
Default value: **TextInputStyle.Default**| -| textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | Alignment mode of the text in the text box.
Default value: **TextAlign.Start** | +| copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.LocalDevice**
If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.| +| showPasswordIcon9+ | boolean | Whether to display the password icon at the end of the password text box.
Default value: **true**| +| style9+ | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Text input style.
Default value: **TextInputStyle.Default**| +| textAlign9+ | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.
Default value: **TextAlign.Start**
**NOTE**
Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.
To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. | | selectedBackgroundColor10+ | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected text.
If the opacity is not set, the color is opaque. For example, **0x80000000** indicates black with 50% opacity.| | caretStyle10+ | {
width: [Length](ts-types.md#length)
} | Caret style. | | caretPosition10+ | number | Caret position.| +| showUnit10+ | [CustomBuilder](ts-types.md#CustomBuilder8) | Unit for content in the component.
By default, there is no unit.| +| showError10+ | string \| undefined | Error text displayed when an error occurs.
By default, no error text is displayed.| +| showUnderline10+ | boolean | Whether to show an underline.
Default value: **false**| +| passwordIcon10+ | [PasswordIcon](#passwordicon10) | Password icon to display at the end of the password text box.
By default, the system-provided icon is used.| +| enableKeyboardOnFocus10+ | boolean | Whether to enable the input method when the component obtains focus.
Default value: **true** | > **NOTE** > @@ -77,6 +82,13 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Default | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text. | | Inline | Inline input style. The background height of the selected text is the same as the height of the text box. | +## PasswordIcon10+ + +| Name | Type | Mandatory| Description | +| ---------- | -------------------------------------------------- | ---- | -------------------------------------------------- | +| onIconSrc | string \|[Resource](ts-types.md#resource)| No | Icon that can be used to hide the password in password input mode.| +| offIconSrc | string \|[Resource](ts-types.md#resource)| No | Icon that can be used to show the password in password input mode.| + ## Events In addition to the [universal events](ts-universal-events-click.md), the following events are supported. diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md index 5e2e776bf3784794349d7b2a61db2171f7a00313..2d6b3bab8f6c8dfeef3c2b65b3068d1546d4b652 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -87,28 +87,28 @@ Web(options: { src: ResourceStr, controller: WebviewController | WebController}) Example of loading local resource files in the sandbox: - 1. Use [globalthis](../../application-models/uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) to obtain the path of the sandbox. - ```ts - // xxx.ets - import web_webview from '@ohos.web.webview' - let url = 'file://' + globalThis.filesDir + '/xxx.html' - - @Entry - @Component - struct WebComponent { - controller: web_webview.WebviewController = new web_webview.WebviewController() - build() { - Column() { - // Load the files in the sandbox. - Web({ src: url, controller: this.controller }) - } - } - } - ``` + 1. Use [globalthis](../../application-models/uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-ui-page) to obtain the path of the sandbox. + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + let url = 'file://' + globalThis.filesDir + '/index.html' - 2. Modify the **MainAbility.ts** file. - - The following uses **filesDir** as an example to describe how to obtain the path of the sandbox. For details about how to obtain other paths, see [Obtaining the Application Development Path](../../application-models/application-context-stage.md#obtaining-the-application-development-path). + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + // Load the files in the sandbox. + Web({ src: url, controller: this.controller }) + } + } + } + ``` + + 2. Modify the **EntryAbility.ts** file. + + The following uses **filesDir** as an example to describe how to obtain the path of the sandbox. For details about how to obtain other paths, see [Obtaining Application File Paths](../../application-models/application-context-stage.md#obtaining-application-file-paths). ```ts // xxx.ts import UIAbility from '@ohos.app.ability.UIAbility'; @@ -123,6 +123,7 @@ Web(options: { src: ResourceStr, controller: WebviewController | WebController}) } ``` + HTML file to be loaded: ```html @@ -587,15 +588,16 @@ Sets whether to display the horizontal scrollbar, including the default system s controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { - Web({ src: 'www.example.com', controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) .horizontalScrollBarAccess(true) } } } ``` + HTML file to be loaded: ```html - + @@ -640,15 +642,16 @@ Sets whether to display the vertical scrollbar, including the default system scr controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { - Web({ src: 'www.example.com', controller: this.controller }) + Web({ src: $rawfile('index.html'), controller: this.controller }) .verticalScrollBarAccess(true) } } } ``` + HTML file to be loaded: ```html - + @@ -669,6 +672,11 @@ Sets whether to display the vertical scrollbar, including the default system scr ``` +### password + +password(password: boolean) + +Sets whether the password should be saved. This API is a void API. ### cacheMode @@ -1236,6 +1244,18 @@ Sets whether to enable forcible dark mode for the web page. By default, this fea } ``` +### tableData + +tableData(tableData: boolean) + +Sets whether form data should be saved. This API is a void API. + +### wideViewModeAccess + +wideViewModeAccess(wideViewModeAccess: boolean) + +Sets whether to support the viewport attribute of the HTML **\** tag. This API is a void API. + ### pinchSmooth9+ pinchSmooth(isEnabled: boolean) @@ -1420,7 +1440,7 @@ Called when **alert()** is invoked to display an alert dialog box on the web pag controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { - Web({ src: $rawfile("xxx.html"), controller: this.controller }) + Web({ src: $rawfile("index.html"), controller: this.controller }) .onAlert((event) => { console.log("event.url:" + event.url) console.log("event.message:" + event.message) @@ -1450,8 +1470,9 @@ Called when **alert()** is invoked to display an alert dialog box on the web pag } ``` - ``` - + HTML file to be loaded: + ```html + @@ -1502,7 +1523,7 @@ Called when this page is about to exit after the user refreshes or closes the pa build() { Column() { - Web({ src: $rawfile("xxx.html"), controller: this.controller }) + Web({ src: $rawfile("index.html"), controller: this.controller }) .onBeforeUnload((event) => { console.log("event.url:" + event.url) console.log("event.message:" + event.message) @@ -1532,8 +1553,9 @@ Called when this page is about to exit after the user refreshes or closes the pa } ``` - ``` - + HTML file to be loaded: + ```html + @@ -1584,7 +1606,7 @@ Called when **confirm()** is invoked by the web page. build() { Column() { - Web({ src: $rawfile("xxx.html"), controller: this.controller }) + Web({ src: $rawfile("index.html"), controller: this.controller }) .onConfirm((event) => { console.log("event.url:" + event.url) console.log("event.message:" + event.message) @@ -1614,8 +1636,9 @@ Called when **confirm()** is invoked by the web page. } ``` - ``` - + HTML file to be loaded: + ```html + @@ -1673,7 +1696,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul build() { Column() { - Web({ src: $rawfile("xxx.html"), controller: this.controller }) + Web({ src: $rawfile("index.html"), controller: this.controller }) .onPrompt((event) => { console.log("url:" + event.url) console.log("message:" + event.message) @@ -1704,8 +1727,9 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul } ``` - ``` - + HTML file to be loaded: + ```html + @@ -1776,6 +1800,8 @@ Called to notify the host application of a JavaScript console message. onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisposition: string, mimetype: string, contentLength: number }) => void) +Instructs the main application to start downloading a file. + **Parameters** | Name | Type | Description | @@ -2084,6 +2110,26 @@ Called when loading of the web page is complete. This API is used by an applicat } ``` +### onSslErrorReceive(deprecated) + +onSslErrorReceive(callback: (event?: { handler: Function, error: object }) => void) + +Called when an SSL error occurs during resource loading. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [onSslErrorEventReceive9+](#onsslerroreventreceive9) instead. + +### onFileSelectorShow(deprecated) + +onFileSelectorShow(callback: (event?: { callback: Function, fileSelector: object }) => void) + +Called to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [onShowFileSelector9+](#onshowfileselector9) instead. + ### onRenderExited9+ onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => void) @@ -3308,7 +3354,7 @@ Called when the **\** component is about to access a URL. This API is used | Name | Type | Description | | ------- | ---------------------------------------- | --------- | -| request | [Webresourcerequest](#webresourcerequest) | Information about the URL request.| +| request | [WebResourceRequest](#webresourcerequest) | Information about the URL request.| **Return value** @@ -4280,6 +4326,7 @@ Enumerates the error codes returned by **onSslErrorEventReceive** API. | Name | Description | Remarks | | --------- | ------------- | -------------------------- | | MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.| +| VIDEO_CAPTURE10+ | Video capture resource, such as a camera.| | ## WebDarkMode9+ | Name | Description | @@ -4933,6 +4980,7 @@ This API is deprecated since API version 9. You are advised to use [registerJava } ``` + HTML file to be loaded: ```html @@ -4993,7 +5041,7 @@ This API is deprecated since API version 9. You are advised to use [runJavaScrip } } ``` - + HTML file to be loaded: ```html @@ -5009,7 +5057,6 @@ This API is deprecated since API version 9. You are advised to use [runJavaScrip } - ``` ### stop(deprecated) @@ -5075,17 +5122,12 @@ This API is deprecated since API version 9. You are advised to use [clearHistory Manages behavior of cookies in **\** components. All **\** components in an application share a **WebCookie**. You can use the **getCookieManager** API in **controller** to obtain the **WebCookie** for subsequent cookie management. ### setCookie(deprecated) -setCookie(url: string, value: string): boolean -Sets the cookie. This API returns the result synchronously. Returns **true** if the operation is successful; returns **false** otherwise. -This API is deprecated since API version 9. You are advised to use [setCookie9+](../apis/js-apis-webview.md#setcookie) instead. +setCookie(): boolean -**Parameters** +Sets the cookie. This API returns the result synchronously. Returns **true** if the operation is successful; returns **false** otherwise. -| Name | Type | Mandatory | Default Value | Description | -| ----- | ------ | ---- | ---- | ----------------- | -| url | string | Yes | - | URL of the cookie to set. A complete URL is recommended.| -| value | string | Yes | - | Value of the cookie to set. | +This API is deprecated since API version 9. You are advised to use [setCookie9+](../apis/js-apis-webview.md#setcookie) instead. **Return value** @@ -5093,31 +5135,12 @@ This API is deprecated since API version 9. You are advised to use [setCookie { - let result = this.controller.getCookieManager().setCookie("https://www.example.com", "a=b") - console.log("result: " + result) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` ### saveCookie(deprecated) + saveCookie(): boolean Saves the cookies in the memory to the drive. This API returns the result synchronously. + This API is deprecated since API version 9. You are advised to use [saveCookieAsync9+](../apis/js-apis-webview.md#savecookieasync) instead. **Return value** @@ -5125,25 +5148,3 @@ This API is deprecated since API version 9. You are advised to use [saveCookieAs | Type | Description | | ------- | -------------------- | | boolean | Operation result.| - -**Example** - - ```ts - // xxx.ets - @Entry - @Component - struct WebComponent { - controller: WebController = new WebController() - - build() { - Column() { - Button('saveCookie') - .onClick(() => { - let result = this.controller.getCookieManager().saveCookie() - console.log("result: " + result) - }) - Web({ src: 'www.example.com', controller: this.controller }) - } - } - } - ``` diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md index f775992c63793b3f41e30d819fab405be931be90..13ec25f92964ea6f702626768a41df16498eadb2 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-xcomponent.md @@ -14,20 +14,39 @@ Since API version 9, child components are supported when **type** is set to **"c ## APIs -XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) +**API 1**: XComponent(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}) **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | ---------------------------------------- | -| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. | -| type | string | Yes | Type of the component. The options are as follows:
- **"surface"**: The content of the component is displayed individually, without being combined with that of other components. This option is used for displaying EGL/OpenGL ES and media data.
- **"component"**9+: The component becomes a container where non-UI logic can be executed to dynamically load the display content.| -| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. This parameter is valid only when the component type is **"surface"**.| -| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component. This parameter is valid only when the component type is **"surface"**.| +| Name | Type | Mandatory| Description | +| ----------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. | +| type | string | Yes | Type of the component. The options are as follows:
- **"surface"**: The custom content is displayed individually on the screen. This option is used for displaying EGL/OpenGL ES and media data.
- **"component"**9+: The component becomes a container where non-UI logic can be executed to dynamically load the display content.
Any other value evaluates to **"surface"**.| +| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. This parameter is valid only when **type** is **"surface"**.| +| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component. This parameter is valid only when the component type is **"surface"**.| + +**API 2**: XComponent(value: {id: string, type: XComponentType, libraryname?: string, controller?: XComponentController})10+ + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. | +| type | [XComponentType](#xcomponenttype10) | Yes | Type of the component. | +| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. This parameter is valid only when **type** is **SURFACE** or **TEXTURE**.| +| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component. This parameter is valid only when **type** is **SURFACE** or **TEXTURE**.| + +## XComponentType10+ + +| Name | Description | +| --------- | ------------------------------------------------------------ | +| SURFACE | The custom content is displayed individually on the screen. This option is used for displaying EGL/OpenGL ES and media data.| +| COMPONENT | The component becomes a container where non-UI logic can be executed to dynamically load the display content.| +| TEXTURE | The custom content of the component is grouped and displayed together with content of the component.| > **NOTE** > -> When **type** is set to **"component"**, the **\** functions as a container, where child components are laid out vertically. +> When **type** is set to **COMPONENT("component")**, the **\** functions as a container, where child components are laid out vertically. > > - Vertical alignment: [FlexAlign](ts-appendix-enums.md#flexalign).Start > - Horizontal alignment: [FlexAlign](ts-appendix-enums.md#flexalign).Center @@ -39,13 +58,14 @@ XComponent(value: {id: string, type: string, libraryname?: string, controller?: > The non-UI logic written internally needs to be encapsulated in one or more functions. ## Attributes -- You can customize the content displayed in the **\**. Among the universal attributes, the [background](./ts-universal-attributes-background.md), [opacity](./ts-universal-attributes-opacity.md), and [image effects](./ts-universal-attributes-image-effect.md) attributes are not supported. -- When **type** is set to **"surface"**, you are advised to use the APIs provided by the EGL/OpenGL ES to set the display content. -- When **type** is set to **"component"**, you are advised to mount child components to set the display content. +- You can customize the content displayed in the **\**. Depending on the **type** settings, the support for the universal attributes [background](./ts-universal-attributes-background.md), [opacity](./ts-universal-attributes-opacity.md), and [image effects](./ts-universal-attributes-image-effect.md) varies: +- When **type** is set to **SURFACE("surface")**, none of these attributes is supported. For configuration, you are advised to use the APIs provided by EGL/OpenGL ES instead. +- When **type** is set to **COMPONENT("component")**, none of these attributes is supported. For configuration, you are advised to mount child components. +- When **type** is set to **TEXTURE**, only [opacity](./ts-universal-attributes-opacity.md) and **backgroundColor** in [background](./ts-universal-attributes-background.md) are supported. For configuration of other attributes, you are advised to use the APIs provided by EGL/OpenGL ES instead. ## Events -The following events are supported only when **type** is set to **"surface"**. The [universal events](ts-universal-events-click.md) and [universal gestures](ts-gesture-settings.md) are not supported. +When **type** is set to **SURFACE("surface")** or **TEXTURE**, the following events are supported. The [universal events](ts-universal-events-click.md) and gestures (ts-gesture-settings.md) are not supported. ### onLoad @@ -79,7 +99,7 @@ xcomponentController: XComponentController = new XComponentController() getXComponentSurfaceId(): string -Obtains the ID of the surface held by the **\**. The ID can be used for @ohos interfaces. For details, see [Camera Management](../apis/js-apis-camera.md). This API works only when **type** of the **\** is set to **"surface"**. +Obtains the ID of the surface held by the **\**, which can then be used for @ohos APIs. For details, see [Camera Management](../apis/js-apis-camera.md). This API works only when **type** of the **\** is set to **SURFACE("surface")** or **TEXTURE**. **Return value** @@ -93,7 +113,7 @@ Obtains the ID of the surface held by the **\**. The ID can be used setXComponentSurfaceSize(value: {surfaceWidth: number, surfaceHeight: number}): void -Sets the width and height of the surface held by the **\**. This API works only when **type** of the **\** is set to **"surface"**. +Sets the width and height of the surface held by the **\**. This API works only when **type** of the **\** is set to **SURFACE("surface")** or **TEXTURE**. **Parameters** @@ -108,7 +128,7 @@ Sets the width and height of the surface held by the **\**. This API getXComponentContext(): Object -Obtains the context of an **\** object. This API works only when **type** of the **\** is set to **"surface"**. +Obtains the context of an **\** object. This API works only when **type** of the **\** is set to **SURFACE("surface")** or **TEXTURE**. **Return value** diff --git a/en/application-dev/reference/arkui-ts/ts-container-ability-component.md b/en/application-dev/reference/arkui-ts/ts-container-ability-component.md index b4bb994bf095875fc9fe39a0bdd0ff1b86117e67..97b7f95f9818531355166d46b0ca5f7f5988fd6e 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-ability-component.md +++ b/en/application-dev/reference/arkui-ts/ts-container-ability-component.md @@ -29,9 +29,9 @@ AbilityComponent(want: Want) **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](../apis/js-apis-app-ability-want.md) | Yes| Description of the default ability to load.| +| Name | Type | Mandatory | Description | +| ---- | ---------------------------------------- | ---- | --------------- | +| want | [Want](../apis/js-apis-app-ability-want.md) | Yes | Description of the default ability to load.| ## Events @@ -74,5 +74,3 @@ struct MyComponent { } } ``` - - \ No newline at end of file diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitem.md b/en/application-dev/reference/arkui-ts/ts-container-listitem.md index 97f1d9faf82279e83ed14f7388c6b495fa6e948a..c54b6e0ee78b9ee062639e1ba966e75566bda5e8 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitem.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitem.md @@ -11,13 +11,28 @@ The **\** component displays specific items in the list. It must be us This component can contain a single child component. - ## APIs -ListItem(value?: string) - Since API version 9, this API is supported in ArkTS widgets. +**API 1**: ListItem(value?: ListItemOptions)10+ + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| value | [ListItemOptions](#listitemoptions10) | No | Value of the list item, containing the **style** parameter of the **ListItemStyle**enum type.| + +**API 2**: ListItem(value?: string)(deprecated) + +This API is deprecated since API version 10. You are advised to use API 1 instead. + +**Parameters** + +| Name| Type | Mandatory| Description| +| ------ | ----------------------------- | ---- | -------- | +| value | string(deprecated) | No | N/A | + ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. @@ -27,7 +42,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | sticky(deprecated) | [Sticky](#stickydeprecated) | Sticky effect of the list item.
Default value: **Sticky.None**
This API is deprecated since API version 9. You are advised to use **sticky** of the [\](ts-container-list.md#attributes) component.| | editable(deprecated) | boolean \| [EditMode](#editmodedeprecated) | Whether to enter editing mode, where the list item can be deleted or moved.
This API is deprecated since API version 9.
Default value: **false**| | selectable8+ | boolean | Whether the current list item is selectable by mouse drag.
**NOTE**
This attribute takes effect only when mouse frame selection is enabled for the parent **\** container.
Default value: **true**| -| swipeAction9+ | {
start?: CustomBuilder,
end?:CustomBuilder,
edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),
} | Component displayed when the list item is swiped out from the screen edge.
- **start**: component on the left of the list item when the item is swiped to the right (in vertical list layout) or component above the list item when the item is swiped down (in horizontal list layout).
- **end**: component on the right of the list item when the item is swiped to the left (in vertical list layout) or component below the list item when the item is swiped up (in horizontal list layout).
- **edgeEffect**: scroll effect.
**NOTE**
The top level of the **@builder** function corresponding to **start** and **end** must be a single component and cannot be an **if/else**, **ForEach**, or **LazyForEach** statement.| +| swipeAction9+ | {
start?: CustomBuilder \| [SwipeActionItem](#swipeactionitem10),
end?:CustomBuilder \| [SwipeActionItem](#swipeactionitem10),
edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),
} | Swipe action displayed when the list item is swiped out from the screen edge.
- **start**: swipe action displayed on the left of the list item when the item is swiped right (in vertical list layout) or above the list item when the item is swiped down (in horizontal list layout).
- **end**: swipe action displayed on the right of the list item when the item is swiped left (in vertical list layout) or below the list item when the item is swiped up (in horizontal list layout).
- **edgeEffect**: scroll effect.
**NOTE**
- The top level of the **@builder** function corresponding to **start** and **end** must be a single component and cannot be an **if/else**, **ForEach**, or **LazyForEach** statement.
- The swipe gesture works only in the list item area. If a swipe causes a child component to extend beyond the list item area, the portion outside the area does not respond to the swipe. In light of this, avoid setting **swipeAction** to a component too wide in a multi-column list. | ## Sticky(deprecated) This API is deprecated since API version 9. You are advised to use [stickyStyle](ts-container-list.md#stickystyle9) of the **\** component. @@ -48,8 +63,36 @@ This API is deprecated since API version 9. ## SwipeEdgeEffect9+ | Name| Description| | -------- | -------- | -| Spring | When the list item scrolls to the edge of the list, it can continue to scroll for a distance and rebound after being released.| -| None | The list item cannot scroll beyond the edge of the list| +| Spring | When the list item scrolls to the edge of the list, it can continue to scroll for a distance. If the delete area is set, the list item can continue to scroll after the scroll distance reaches the delete threshold and, after being released, rebound following the spring curve.| +| None | The list item cannot scroll beyond the edge of the list. If the delete area is set, the list item cannot continue to scroll after the scroll distance reaches the delete threshold. If the delete callback is set, it is triggered when the delete threshold is reached and the list item is released.| + +## SwipeActionItem10+ +Describes the swipe action item. + +For a list in vertical layout, it refers to the delete item displayed on the left (or right) of the list item when the list item is swiped right (or left). + +For a list in horizontal layout, it refers to the delete item displayed below (or above) the list item when the list item is swiped up (or down). + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| deleteAreaDistance | [Length](ts-types.md#length) | No| Swipe distance threshold for deleting the list item.
Default value: **56vp**
**NOTE**
This parameter cannot be set in percentage.
If the value is greater than the list item width minus the width of **swipeAction**, or is less than or equal to 0, the delete area will not be set.| +| onDelete | () => void | No| Callback invoked when the list item is released while in the delete area.
**NOTE**
This callback is invoked only when the list item is released in a position that meets or goes beyond the specified swipe distance threshold (which must be valid) for deleting the list item.| +| onEntryDeleteArea | () => void | No| Callback invoked each time the list item enters the delete area.| +| onExitDeleteArea | () => void | No|Callback invoked each time the list item exits the delete area.| +| builder | CustomBuilder | No|Swipe action item displayed when the list item is swiped left or right (in vertical list layout) or up or down (in horizontal list layout).| +| useDefaultDeleteAnimation | boolean | No|Whether to use the default delete animation.
Default value: **true**| +## ListItemOptions10+ + +| Name | Type | Mandatory| Description | +| ----- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| style | [ListItemStyle](#listitemstyle10) | No | Style of the list item.
Default value: **ListItemStyle.NONE**
If this parameter is set to **ListItemStyle.NONE**, no style is applied.
If this parameter is set to **ListItemStyle.CARD**, the default card style is applied, but only when **ListItemGroupStyle.CARD** is set for [\](ts-container-listitemgroup.md).
In the default card style, the list item has a 48 vp height and 100% width. It can be in focus, hover, press, selected, or disable style depending on the state.
**NOTE**
In the default card style, the list has its **listDirection** attribute fixed at **Axis.Vertical** and **alignListItem** attribute at **ListItemAlign.Center**. | + +## ListItemStyle10+ + +| Name| Description | +| ---- | ------------------ | +| NONE | No style. | +| CARD | Default card style.| ## Events @@ -78,6 +121,7 @@ struct ListItemExample { } }, item => item) }.width('90%') + .scrollBar(BarState.Off) }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) } } @@ -85,45 +129,63 @@ struct ListItemExample { ![en-us_image_0000001219864159](figures/en-us_image_0000001219864159.gif) + ```ts // xxx.ets @Entry @Component struct ListItemExample2 { @State message: string = 'Hello World' + @State arr: number[] = [0, 1, 2, 3, 4] + @State enterEndDeleteAreaString: string = "not enterEndDeleteArea" + @State exitEndDeleteAreaString: string = "not exitEndDeleteArea" @Builder itemEnd() { - Row () { - Button("Del").margin("4vp") + Row() { + Button("Delete").margin("4vp") Button("Set").margin("4vp") }.padding("4vp").justifyContent(FlexAlign.SpaceEvenly) } build() { Column() { - List({space:10}) { - ListItem() { - Text(this.message) - .width('100%') - .height(100) - .fontSize(16) - .textAlign(TextAlign.Center) - .borderRadius(10) - .backgroundColor(0xFFFFFF) - } - .swipeAction({ end:this.itemEnd}) - - ListItem() { - Text(this.message) - .width('100%') - .height(100) - .fontSize(16) - .textAlign(TextAlign.Center) - .borderRadius(10) - .backgroundColor(0xFFFFFF) - } - .swipeAction({ start:this.itemEnd}) + List({ space: 10 }) { + ForEach(this.arr, (item) => { + ListItem() { + Text("item" + item) + .width('100%') + .height(100) + .fontSize(16) + .textAlign(TextAlign.Center) + .borderRadius(10) + .backgroundColor(0xFFFFFF) + } + .transition({ type: TransitionType.Delete, opacity: 0 }) + .swipeAction({ + end: { + builder: this.itemEnd.bind(this, item), + useDefaultDeleteAnimation: true, + onDelete: () => { + animateTo({ duration: 1000 }, () => { + let index = this.arr.indexOf(item) + this.arr.splice(index, 1) + }) + }, + deleteAreaDistance: 80, + onEnterDeleteArea: () => { + this.enterEndDeleteAreaString = "enterEndDeleteArea" + this.exitEndDeleteAreaString = "not exitEndDeleteArea" + }, + onExitDeleteArea: () => { + this.enterEndDeleteAreaString = "not enterEndDeleteArea" + this.exitEndDeleteAreaString = "exitEndDeleteArea" + } + } + }) + }, item => item) } + Text(this.enterEndDeleteAreaString).fontSize(20) + Text(this.exitEndDeleteAreaString).fontSize(20) } .padding(10) .backgroundColor(0xDCDCDC) @@ -132,4 +194,4 @@ struct ListItemExample2 { } } ``` -![en-us_image_1501929990650](figures/en-us_image_1501929990650.jpg) +![deleteListItem](figures/deleteListItem.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md b/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md index f0aab291ecf652bba774dcdaa7c567081dea69a6..48ed2249eb25c786c2bcd5f8cb900bd4e4b1589a 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md +++ b/en/application-dev/reference/arkui-ts/ts-container-listitemgroup.md @@ -19,15 +19,16 @@ This component supports the **[\](ts-container-listitem.md)** child co ## APIs -ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?: number | string}) +ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?: number | string, style?: ListItemGroupStyle}) **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| header | [CustomBuilder](ts-types.md#custombuilder8) | No| Header of the **\** component.| -| footer | [CustomBuilder](ts-types.md#custombuilder8) | No| Footer of the **\** component.| -| space | number \| string | No| Spacing between list items. This parameter is valid only between list items, but not between a header and list item or between a footer and list item.| +| Name | Type | Mandatory| Description | +| ------------------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| header | [CustomBuilder](ts-types.md#custombuilder8) | No | Header of the list item group. | +| footer | [CustomBuilder](ts-types.md#custombuilder8) | No | Footer of the list item group. | +| space | number \| string | No | Spacing between list items. This parameter is valid only between list items, but not between a header and list item or between a footer and list item.| +| style10+ | [ListItemGroupStyle](#listitemgroupstyle10) | No | Style of the list item group.
Default value: **ListItemGroupStyle.NONE**
If this parameter is set to **ListItemGroupStyle.NONE**, no style is applied.
If this parameter is set to **ListItemGroupStyle.CARD**, the default card style is applied, but only when **ListItemStyle.CARD** is set for [\](ts-container-listitem.md).
It can be in focus, hover, press, selected, or disable style depending on the state.
**NOTE**
In the default card style, the list has its **listDirection** attribute fixed at **Axis.Vertical** and **alignListItem** attribute at **ListItemAlign.Center**; the **header** and **footer** parameters cannot be set for the list item group. | ## Attributes @@ -35,6 +36,13 @@ ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?: | -------- | -------- | -------- | | divider | {
strokeWidth: [Length](ts-types.md#length),
color?: [ResourceColor](ts-types.md#resourcecolor),
startMargin?: [Length](ts-types.md#length),
endMargin?: [Length](ts-types.md#length)
} \| null | Style of the divider for the list items. By default, there is no divider.
- **strokeWidth**: stroke width of the divider.
- **color**: color of the divider.
- **startMargin**: distance between the divider and the start of the list.
- **endMargin**: distance between the divider and the end of the list.| +## ListItemGroupStyle10+ + +| Name| Description | +| ---- | ------------------ | +| NONE | No style. | +| CARD | Default card style.| + > **NOTE** > > The **\** component does not support the universal attribute **[aspectRatio](ts-universal-attributes-layout-constraints.md)**. @@ -99,12 +107,12 @@ struct ListItemGroupExample { } }, item => item) } - .borderRadius(20) .divider ({ strokeWidth: 1,color:Color.Blue }) // Divider between lines }) } .width('90%') .sticky(StickyStyle.Header|StickyStyle.Footer) + .scrollBar(BarState.Off) }.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 }) } } diff --git a/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md b/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md index 52fbd9e3d32589538b10f699b209a7f00c9dc5fb..9b195d49a0ed0a36bdf1675820d7fb2b8cadcbd9 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md +++ b/en/application-dev/reference/arkui-ts/ts-container-sidebarcontainer.md @@ -34,6 +34,7 @@ SideBarContainer( type?: SideBarContainerType ) | -------- | -------- | | Embed | The sidebar is embedded in the component and displayed side by side with the content area.| | Overlay | The sidebar is displayed overlaid on the content area.| +| AUTO | The sidebar is displayed in Embed mode when the component size is greater than or equal to the sum of **minSideBarWidth** and **minContentWidth**
and in Overlay mode otherwise.| ## Attributes @@ -50,6 +51,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | autoHide9+ | boolean | Whether to automatically hide the sidebar when it is dragged to be smaller than the minimum width.
Default value: **true**
**NOTE**
The value is subject to the **minSideBarWidth** attribute method. If it is not set in **minSideBarWidth**, the default value is used.
Whether the sidebar should be hidden is determined when it is being dragged. When its width is less than the minimum width, the damping effect is required to trigger hiding (a distance out of range).| | sideBarPosition9+ | [SideBarPosition](#sidebarposition9) | Position of the sidebar.
Default value: **SideBarPosition.Start**| | divider10+ | [DividerStyle](#dividerstyle10) \| null | Divider style.
- **DividerStyle** (default): The divider is displayed.
- **null**: The divider is not displayed.| +| minContentWidth10+ | Dimension | Minimum width of the content area of the sidebar container.
Default value: **360**
Unit: vp| ## ButtonStyle diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md index e72c5eb5c4eb4c0a9621d92feb10a5bd69082935..67d314759805d013bb678b47643e4646b62629b5 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -27,8 +27,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| tabBar | string \| Resource \| {
icon?: string \| Resource,
text?: string \| Resource
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
**NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.
If the content set exceeds the space provided by the tab bar, it will be clipped.| -| tabBar9+ | [SubTabBarStyle](#subtabbarstyle) \| [BottomTabBarStyle](#bottomtabbarstyle) | Content displayed on the tab bar.
**SubTabBarStyle**: subtab style. It takes text as its input parameter.
**BottomTabBarStyle**: bottom and side tab style. It takes text and images as its input parameters.
**NOTE**
The bottom tab style does not include an underline.
When an icon display error occurs, a gray blank block is displayed.| +| tabBar | string \| [Resource](ts-types.md#resource) \| {
icon?: string \| [Resource](ts-types.md#resource),
text?: string \| [Resource](ts-types.md#resource)
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
**NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.
If the content set exceeds the space provided by the tab bar, it will be clipped.| +| tabBar9+ | [SubTabBarStyle](#subtabbarstyle9) \| [BottomTabBarStyle](#bottomtabbarstyle9) | Content displayed on the tab bar.
**SubTabBarStyle**: subtab style. It takes text as its input parameter.
**BottomTabBarStyle**: bottom and side tab style. It takes text and images as its input parameters.
**NOTE**
The bottom tab style does not include an underline.
When an icon display error occurs, a gray blank block is displayed.| > **NOTE** > @@ -81,10 +81,10 @@ The following attributes are supported. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------------------------------- | | color | [ResourceColor](ts-types.md#resourcecolor) | No| Underline indicator color and board color.
Default value: **#FF007DFF**| -| height | [Length](ts-types.md#length) | No| Height of the underline indicator.
Default value: **2.0**
Unit: vp| -| width | [Length](ts-types.md#length) | No| Width of the underline indicator.
Default value: **0.0**
Unit: vp| -| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the underline indicator.
Default value: **0.0**
Unit: vp| -| marginTop | [Length](ts-types.md#length) | No| Spacing between the underline indicator and text.
Default value: **8.0**
Unit: vp| +| height | [Length](ts-types.md#length) | No| Height of the underline indicator. It cannot be set in percentage.
Default value: **2.0**
Unit: vp| +| width | [Length](ts-types.md#length) | No| Width of the underline indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp| +| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the underline indicator. It cannot be set in percentage.
Default value: **0.0**
Unit: vp| +| marginTop | [Length](ts-types.md#length) | No| Spacing between the underline indicator and text. It cannot be set in percentage.
Default value: **8.0**
Unit: vp| ## SelectedMode10+ | Name | Description | @@ -96,7 +96,7 @@ The following attributes are supported. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | ------------------------------------ | -| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the underline indicator.
Default value: **8.0**
Unit: vp| +| borderRadius | [Length](ts-types.md#length) | No| Radius of the rounded corner of the board. It cannot be set in percentage.
Default value: **8.0**
Unit: vp| ## LabelStyle10+ diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabs.md b/en/application-dev/reference/arkui-ts/ts-container-tabs.md index 99f26a37c690f220d5d1a0bdbc0be42e7c789372..5f5423416d93440e5ed52c75b6b49b6bec25e1f9 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabs.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabs.md @@ -41,7 +41,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | vertical | boolean | Whether to use vertical tabs. The value **true** means to use vertical tabs, and **false** means to use horizontal tabs.
Default value: **false**| | scrollable | boolean | Whether the tabs are scrollable. The value **true** means that the tabs are scrollable, and **false** means the opposite.
Default value: **true**| | barMode | BarMode | Tab bar layout mode. For details, see **BarMode**.
Default value: **BarMode.Fixed**| -| barWidth | number \| Length8+ | Width of the tab bar.
The default value varies.
If the tab bar has the **vertical** attribute set to **false** and does not have a style specified, the default value is the width of the **\** component.
If the tab bar has the **vertical** attribute set to **true** and does not have a style specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **false** and **SubTabbarStyle** specified, the default value is the width of the **\** component.
If the tab bar has the **vertical** attribute set to **true** and **SubTabbarStyle** specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **true** and **BottomTabbarStyle** specified, the default value is **96vp**.
If the tab bar has the **vertical** attribute set to **false** and **BottomTabbarStyle** specified, the default value is the width of the **\** component.
**NOTE**

A value less than 0 or greater than the width of the **\** component evaluates to the default value.| +| barWidth | number \| Length8+ | Width of the tab bar.
The default value varies.
If the tab bar has the **vertical** attribute set to **false** and does not have a style specified, the default value is the width of the **\** component.
If the tab bar has the **vertical** attribute set to **true** and does not have a style specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **false** and **SubTabbarStyle** specified, the default value is the width of the **\** component.
If the tab bar has the **vertical** attribute set to **true** and **SubTabbarStyle** specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **true** and **BottomTabbarStyle** specified, the default value is **96vp**.
If the tab bar has the **vertical** attribute set to **false** and **BottomTabbarStyle** specified, the default value is the width of the **\** component.
**NOTE**
A value less than 0 or greater than the width of the **\** component evaluates to the default value.| | barHeight | number \| Length8+ | Height of the tab bar.
The default value varies.
If the tab bar has the **vertical** attribute set to **false** and does not have a style specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **true** and does not have a style specified, the default value is the height of the **\** component.
If the tab bar has the **vertical** attribute set to **false** and **SubTabbarStyle** specified, the default value is **56vp**.
If the tab bar has the **vertical** attribute set to **true** and **SubTabbarStyle** specified, the default value is the height of the **\** component.
If the tab bar has the **vertical** attribute set to **true** and **BottomTabbarStyle** specified, the default value is the height of the **\** component.
If the tab bar has the **vertical** attribute set to **false** and **BottomTabbarStyle** specified, the default value is **56vp**.
**NOTE**
A value less than 0 or greater than the height of the **\** component evaluates to the default value. | | animationDuration | number | Duration of the slide animation for tab switching. If this parameter is set, the tab switching animation is played when the user switches between tabs by sliding or clicking. If this parameter is not set, the tab switching animation is played only when the user switches between tabs by sliding.
Default value: **300**
**NOTE**
A value less than 0 or in percentage evaluates to the default value. | | divider10+ | [DividerStyle](#dividerstyle10) \| null | Whether the divider is displayed for the **\** and **\** components and the divider style. By default, the divider is not displayed.
**DividerStyle**: divider style.
**null**: The divider is not displayed.| @@ -53,10 +53,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | ----------------------------------- | -| strokeWidth | [Length](ts-types.md#length) | Yes | Width of the divider. | +| strokeWidth | [Length](ts-types.md#length) | Yes | Width of the divider. It cannot be set in percentage. | | color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the divider.
Default value: **#33182431** | -| startMargin | [Length](ts-types.md#length) | No | Distance between the divider and the top of the sidebar.
Default value: **0.0**
Unit: vp| -| endMargin | [Length](ts-types.md#length) | No | Distance between the divider and the bottom of the sidebar.
Default value: **0.0**
Unit: vp| +| startMargin | [Length](ts-types.md#length) | No | Distance between the divider and the top of the sidebar. It cannot be set in percentage.
Default value: **0.0**
Unit: vp| +| endMargin | [Length](ts-types.md#length) | No | Distance between the divider and the bottom of the sidebar. It cannot be set in percentage.
Default value: **0.0**
Unit: vp| ## BarMode diff --git a/en/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md b/en/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md index 148129e651983ba9ba54a017cd6d30d79272571d..4726d5481822059bfc36acfc0481fe27e7656a5e 100644 --- a/en/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md +++ b/en/application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md @@ -1,12 +1,11 @@ # Custom Component Lifecycle - The lifecycle callbacks of a custom component are used to notify users of the lifecycle of the component. These callbacks are private and are invoked by the development framework at a specified time at runtime. They cannot be manually invoked from applications. - >**NOTE** > ->Promise and asynchronous callback functions can be used in lifecycle functions, for example, network resource getters and timer setters. +>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>- Promise and asynchronous callback functions can be used in lifecycle functions, for example, network resource getters and timer setters. ## aboutToAppear @@ -123,8 +122,8 @@ Since API version 10, this API is supported in ArkTS widgets. **Parameters** -| Name| Type | Description | -| ------ | -------------------------- | -------------------- | +| Name | Type | Description | +| ------ | -------------------------- | ---------- | | params | { [key: string]: unknown } | Parameters used for constructing the custom component.| diff --git a/en/application-dev/reference/arkui-ts/ts-pixel-units.md b/en/application-dev/reference/arkui-ts/ts-pixel-units.md index 8a820840da5c7a8d5ad232f16f548acd585ed262..26ae5a8713858fed4427021145353a500a35b8a7 100644 --- a/en/application-dev/reference/arkui-ts/ts-pixel-units.md +++ b/en/application-dev/reference/arkui-ts/ts-pixel-units.md @@ -1,13 +1,17 @@ # Pixel Units -The framework provides four pixel units, with vp as the reference data unit. +ArkUI provides four pixel units, with vp as the reference data unit. +>**Notes:** +> +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -| Name| Description | -| ---- | ------------------------------------------------------------ | -| px | Physical pixel unit of the screen. | + +| Name | Description | +| ---- | ---------------------------------------- | +| px | Physical pixel unit of the screen. | | vp | Pixel unit specific to the screen density. Pixels in this unit are converted into physical pixels of the screen based on the screen pixel density. This unit is used for values whose unit is not specified. On a screen with an actual width of 1440 physical pixels, 1 vp is approximately equal to 3 px.| -| fp | Font pixel, which is similar to vp and varies according to the system font size.| +| fp | Font pixel, which is similar to vp and varies according to the system font size. | | lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **designWidth**). For example, if **designWidth** is set to **720** (default value), then 1 lpx is equal to 2 px for a screen with an actual width of 1440 physical pixels.| @@ -15,12 +19,12 @@ The framework provides four pixel units, with vp as the reference data unit. Conversion between px and other pixel units is supported. -| API | Description | -| --------------------------------------------------- | ------------------------------------------------------------ | -| vp2px(value : number) : number | Converts a value in units of vp to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| -| px2vp(value : number) : number | Converts a value in units of px to a value in units of vp.
Since API version 9, this API is supported in ArkTS widgets.| -| fp2px(value : number) : number | Converts a value in units of fp to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| -| px2fp(value : number) : number | Converts a value in units of px to a value in units of fp.
Since API version 9, this API is supported in ArkTS widgets.| +| API | Description | +| ---------------------------------------- | ---------------------------------------- | +| vp2px(value : number) : number | Converts a value in units of vp to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| +| px2vp(value : number) : number | Converts a value in units of px to a value in units of vp.
Since API version 9, this API is supported in ArkTS widgets.| +| fp2px(value : number) : number | Converts a value in units of fp to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| +| px2fp(value : number) : number | Converts a value in units of px to a value in units of fp.
Since API version 9, this API is supported in ArkTS widgets.| | lpx2px(value : number) : number | Converts a value in units of lpx to a value in units of px.
Since API version 9, this API is supported in ArkTS widgets.| | px2lpx(value : number) : number | Converts a value in units of px to a value in units of lpx.
Since API version 9, this API is supported in ArkTS widgets.| diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-click.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-click.md index f6ed907ac1dc0941cc422e262298359a52257b45..5b83363ed4374806ef0f4daca3db716ce1d22e91 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-click.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-click.md @@ -12,7 +12,7 @@ Click control attributes are used to set whether a component can respond to fing | Name | Type| Description | | ----------- | -------- | ------------------------ | -| touchable | boolean | Whether the component can respond to finger interactions such as click and touch events.
Default value: **true**| +| touchable(deprecated) | boolean | Whether the component can respond to finger interactions such as click and touch events.
Default value: **true**
**NOTE**
This API is deprecated since API version 9. You are advised to use [hitTestBehavior](ts-universal-attributes-hit-test-behavior.md) instead.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-sheet-transition.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-sheet-transition.md index 2dd74f689b7a90bfdc9810ee0aa5c67d88b80ff0..a6a11470211d552783c6218ce240102bf175bfc7 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-sheet-transition.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-sheet-transition.md @@ -18,7 +18,7 @@ You can bind a sheet to a component through the **bindSheet** attribute. You can | Name | Type | Mandatory| Description | | ------------------ | -------------------------------------- | ---- | ---------------------- | | height | [SheetSize](#sheetsize10) \| [Length](ts-types.md#length) | No| Height of the sheet. | -| showDragBar | boolean | No | Whether the control bar is visible. | +| dragBar | boolean | No | Whether the control bar is visible. | ## SheetSize10+ diff --git a/en/application-dev/reference/arkui-ts/ts-universal-events-keyboardshortcut.md b/en/application-dev/reference/arkui-ts/ts-universal-events-keyboardshortcut.md index 011fe91e02257575d4f11e08cc502e34e1dcf286..5efbffa663ce4c8126c4bb0bc0b236fa766c9e3f 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-events-keyboardshortcut.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-events-keyboardshortcut.md @@ -1,4 +1,4 @@ -# Custom Keyboard Shortcuts +# Component Keyboard Shortcut Event You can set one or more custom keyboard shortcuts for a component. The behavior of these keyboard shortcuts is the same as that of clicks. Components can respond to custom keyboard shortcuts even when they are not focused. @@ -12,23 +12,23 @@ keyboardShortcut(value: string | [FunctionKey], keys: Array<[ModifierKey]>) **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------------- | ---- | ------------------------------------------------------------ | -| value | string \| [FunctionKey](#functionkey) | Yes | Character key (which can be entered through the keyboard) or [function key](#functionkey).
| -| keys | Array<[ModifierKey](#modifierkey)> | Yes | Modifier keys.
| +| Name | Type | Mandatory | Description | +| ----- | ------------------------------------- | ---- | ---------------------------------------- | +| value | string \| [FunctionKey](#functionkey) | Yes | Character key (which can be entered through the keyboard) or [function key](#functionkey).
| +| keys | Array<[ModifierKey](#modifierkey)> | Yes | Modifier keys.
| ## ModifierKey -| Name | Description | -| ----- | ------------------- | +| Name | Description | +| ----- | ------------ | | CTRL | Ctrl key on the keyboard. | | SHIFT | Shift key on the keyboard.| | ALT | Alt key on the keyboard. | ## FunctionKey -| Name| Description | -| ---- | --------------------- | +| Name | Description | +| ---- | ------------ | | ESC | Esc key on the keyboard.| | F1 | F1 key on the keyboard. | | F2 | F2 key on the keyboard. | @@ -45,35 +45,35 @@ keyboardShortcut(value: string | [FunctionKey], keys: Array<[ModifierKey]>) ## Precautions for Using Keyboard Shortcuts -| Scenario | Processing Logic | Example | -| ------------------------------------------------------------ | -------------------------------------------------------- | ------------------------------------------------------------ | -| All components that support the **onClick** event | Custom keyboard shortcuts are supported. | – | -| Requirements for custom keyboard shortcuts | A custom keyboard shortcut consists of one or more modifier keys (**Ctrl**, **Shift**, **Alt**, or any combination thereof) and a character key or function key.| Button('button1').keyboardShortcut('a',[ModifierKey.CTRL]) | -| Setting one custom keyboard shortcut for multiple components | Only the first component in the component tree responds to the custom keyboard shortcut. | Button('button1').keyboardShortcut('a',[ModifierKey.CTRL])
Button('button2').keyboardShortcut('a',[ModifierKey.CTRL]) | -| When the component is focused or not | The component responds to the custom keyboard shortcut as long as the window is focused. | – | -| When a single keyboard shortcut is set, it can be canceled by setting the **value**, **keys**, or both of them to null in the **keyboardShortcut** API.
When multiple keyboard shortcuts are set, they cannot be canceled.| Canceling the custom keyboard shortcut settings | Button('button1').keyboardShortcut('',[ModifierKey.CTRL])
Button('button2').keyboardShortcut('a',[l])
Button('button3').keyboardShortcut('',[]) | -| The independent pipeline sub-window and main window coexist | The focused window responds to the keyboard shortcut. | – | -| Ctrl, Shift, or Alt key in the **keys** parameter of the **keyboardShortcut** API | Both the keys on the left or right sides of the keyboard work. | Button('button1').keyboardShortcut('a',[ModifierKey.CTRL, ModifierKey.ALT]) | -| Character key in the **value** parameter of the **keyboardShortcut** API | The response is case-insensitive. | Button('button1').keyboardShortcut('a',[ModifierKey.CTRL])
Button('button2').keyboardShortcut('A',[ModifierKey.CTRL]) | -| Response to keyboard shortcuts | The component responds continuously to the keyboard shortcut when all the set keys are pressed. | – | -| Hidden component
| The keyboard shortcut also works. | – | -| Components in the disable state | The keyboard shortcut does not work. | – | -| 1. The keyboard shortcut is the same as an existing one (including the system-defined ones).
2. The **value** parameter contains multiple character keys.
3. The **key** parameter has a duplicate modifier key.| In these cases, the keyboard shortcut is not added, and the previously added keyboard shortcuts still work. | Button('button1').keyboardShortcut('c',[ModifierKey.CTRL])
Button('button2').keyboardShortcut('ab',[ModifierKey.CTRL])
Button('button3').keyboardShortcut('ab',[ModifierKey.CTRL,ModifierKey.CTRL]) | +| Scenario | Processing Logic | Example | +| ---------------------------------------- | ---------------------------------- | ---------------------------------------- | +| All components that support the **onClick** event | Custom keyboard shortcuts are supported. | – | +| Requirements for custom keyboard shortcuts | A custom keyboard shortcut consists of one or more modifier keys (**Ctrl**, **Shift**, **Alt**, or any combination thereof) and a character key or function key.| Button('button1').keyboardShortcut('a',[ModifierKey.CTRL]) | +| Setting one custom keyboard shortcut for multiple components | Only the first component in the component tree responds to the custom keyboard shortcut. | Button('button1').keyboardShortcut('a',[ModifierKey.CTRL])
Button('button2').keyboardShortcut('a',[ModifierKey.CTRL]) | +| When the component is focused or not | The component responds to the custom keyboard shortcut as long as the window is focused. | – | +| When a single keyboard shortcut is set, it can be canceled by setting the **value**, **keys**, or both of them to null in the **keyboardShortcut** API.
When multiple keyboard shortcuts are set, they cannot be canceled.| Canceling the custom keyboard shortcut settings | Button('button1').keyboardShortcut('',[ModifierKey.CTRL])
Button('button2').keyboardShortcut('a',[l])
Button('button3').keyboardShortcut('',[]) | +| The independent pipeline sub-window and main window coexist | The focused window responds to the keyboard shortcut. | – | +| Ctrl, Shift, or Alt key in the **keys** parameter of the **keyboardShortcut** API| Both the keys on the left or right sides of the keyboard work. | Button('button1').keyboardShortcut('a',[ModifierKey.CTRL, ModifierKey.ALT]) | +| Character key in the **value** parameter of the **keyboardShortcut** API | The response is case-insensitive. | Button('button1').keyboardShortcut('a',[ModifierKey.CTRL])
Button('button2').keyboardShortcut('A',[ModifierKey.CTRL]) | +| Response to keyboard shortcuts | The component responds continuously to the keyboard shortcut when all the set keys are pressed. | – | +| Hidden component
| The keyboard shortcut also works. | – | +| Components in the disable state | The keyboard shortcut does not work. | – | +| 1. The keyboard shortcut is the same as an existing one (including the system-defined ones).
2. The **value** parameter contains multiple character keys.
3. The **key** parameter has a duplicate modifier key.| In these cases, the keyboard shortcut is not added, and the previously added keyboard shortcuts still work. | Button('button1').keyboardShortcut('c',[ModifierKey.CTRL])
Button('button2').keyboardShortcut('ab',[ModifierKey.CTRL])
Button('button3').keyboardShortcut('ab',[ModifierKey.CTRL,ModifierKey.CTRL]) | ## System-defined Keyboard Shortcuts -| Keyboard Shortcut | Component | -| -------------- | ------------------------------------------------------------ | +| Keyboard Shortcut | Component | +| -------------- | ---------------------------------------- | | Ctrl + C | [Image](ts-basic-components-image.md), [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| | Ctrl+ A | [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| | Ctrl+ V | [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| | Ctrl+ X | [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| -| Shift + arrow keys| [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| +| Shift + arrow keys | [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| | Ctrl+ Shift+ Z | [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| | Ctrl+ Z | [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| | Ctrl+ Y | [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| -| Arrow keys and Enter key| [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| -| Tab key | [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| +| Arrow keys and Enter key | [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| +| Tab key | [TextInput](ts-basic-components-textinput.md), [TextArea](ts-basic-components-textarea.md)| ## Example diff --git a/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-css.md b/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-css.md index 79aa6fa9c7dbb7ea0373a545633307df3df62f41..3d3332c012725d3b6c275ad20d905ae1483e48e4 100644 --- a/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-css.md +++ b/en/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-css.md @@ -23,7 +23,7 @@ CSS files can be imported using the **\@import** statement. This facilitates mod The **.css** file with the same name as the **.hml** file in each page directory describes the styles of components on the HML page, determining how the components will be displayed. 1. Internal style: The **style** and **class** attributes can be used to specify the component style. Example: - + ```html
@@ -31,7 +31,7 @@ The **.css** file with the same name as the **.hml** file in each page directory
``` - + ```css /* index.css */ .container { @@ -40,7 +40,7 @@ The **.css** file with the same name as the **.hml** file in each page directory ``` 2. External style files: You need to import the files. For example, create a **style.css** file in the **common** directory and import the file at the beginning of **index.css**. - + ```css /* style.css */ .title { @@ -48,7 +48,7 @@ The **.css** file with the same name as the **.hml** file in each page directory } ``` - + ```css /* index.css */ @import '../../common/style.css'; @@ -62,10 +62,10 @@ The **.css** file with the same name as the **.hml** file in each page directory A CSS selector is used to select elements for which styles need to be added to. The following table lists the supported selectors. -| Selector| Example| Description| -| -------- | -------- | -------- | +| Selector | Example | Description | +| ------ | ---------- | ------------------------- | | .class | .container | Selects all components whose **class** is **container**.| -| \#id | \#titleId | Selects all components whose **id** is **titleId**.| +| \#id | \#titleId | Selects all components whose **id** is **titleId**. | Example: diff --git a/en/application-dev/security/cryptoFramework-guidelines.md b/en/application-dev/security/cryptoFramework-guidelines.md index 5da4bc32d6ecb1951d067da0cd4369569e4d80d4..f1a037f2bb442bcd9e72c14ed9fbd8feb95d124a 100644 --- a/en/application-dev/security/cryptoFramework-guidelines.md +++ b/en/application-dev/security/cryptoFramework-guidelines.md @@ -4,27 +4,30 @@ > > This guide applies to JS development using OpenHarmony API version 9 and SDK version 3.2.7 or later. -## Generating and Converting a Key +## Key Generation and Conversion -**When to Use** +### When to Use Typical key generation operations involve the following: -1. Randomly create a key instance for subsequent encryption and decryption. -2. Convert external or stored binary data into a key instance for subsequent encryption and decryption. -3. Obtain the binary data of a key for storage or transmission. -> **NOTE**
The key instance can be a symmetric key instance (**SymKey**) or an asymmetric key pair instance (**KeyPair**). The **KeyPair** instance consists a public key (**PubKey**) and a private key (**PriKey**). For details about the relationship between keys, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). +1. Randomly create a key object for subsequent encryption and decryption. +2. Create a key object based on the specified key parameters for subsequent encryption and decryption. +3. Convert external or internal binary data into a key object for subsequent encryption and decryption. +4. Obtain the binary data of a key object for storage or transmission. +5. Obtain the parameter properties of an asymmetric key object for storage or transmission. +> **NOTE** +> +> The key object can be a symmetric key object (**SymKey**) or an asymmetric key pair object (**KeyPair**). The **KeyPair** object consists a public key (**PubKey**) and a private key (**PriKey**). For details about the relationship between keys, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). -**Available APIs** - -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). +### Available APIs -The table below describes the APIs used in this guide. +The following table describes the APIs used in typical key generation operations. For more information about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). |Instance|API|Description| |---|---|---| -|cryptoFramework|createAsyKeyGenerator(algName : string) : AsyKeyGenerator|Creates an **AsyKeyGenerator** instance.| +|cryptoFramework|createAsyKeyGenerator(algName : string) : AsyKeyGenerator|Creates an **AsyKeyGenerator** instance based on the asymmetric key pair specifications specified by **algName**.| +|cryptoFramework|createAsyKeyGeneratorBySpec(asyKeySpec: AsyKeySpec): AsyKeyGeneratorBySpec;|Creates an **AsyKeyGenerator** instance based on the asymmetric key specifications specified by the key parameter.| |cryptoFramework|createSymKeyGenerator(algName : string) : SymKeyGenerator|Creates a **SymKeyGenerator** instance.| |AsyKeyGenerator|generateKeyPair(callback : AsyncCallback\) : void|Generates an asymmetric key pair randomly. This API uses an asynchronous callback to return the result.| |AsyKeyGenerator|generateKeyPair() : Promise\|Generates an asymmetric key pair randomly. This API uses a promise to return the result.| @@ -36,17 +39,17 @@ The table below describes the APIs used in this guide. | SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\| Converts binary data into a symmetric key. This API uses a promise to return the result.| | Key | getEncoded() : DataBlob; | Obtains the binary data of a key. (The child class instances of **Key** include **SymKey**, **PubKey**, and **PriKey**.)| -**How to Develop** +### Randomly Generating an RSA Key Pair and Obtaining the Binary Data -Example 1: Randomly generate an asymmetric key pair and obtain its binary data. +Randomly generate an asymmetric key pair and obtain its binary data. 1. Create an **AsyKeyGenerator** instance. 2. Randomly generate an asymmetric key pair using **AsyKeyGenerator**. -3. Obtain binary data of the key pair generated. +3. Obtain the binary data of the key pair generated. -The following sample code demonstrates how to randomly generate an RSA key (1024 bits and two primes) using promise-based APIs. +Example: Randomly generate an RSA key (1024 bits and two primes) in promise mode. -```javascript +```js import cryptoFramework from '@ohos.security.cryptoFramework'; function generateAsyKey() { @@ -67,15 +70,17 @@ function generateAsyKey() { } ``` -Example 2: Randomly generate a symmetric key and obtain its binary data. +### Randomly Generating an AES Key and Obtaining the Binary Data + +Randomly generate a symmetric key and obtain its binary data. 1. Create a **SymKeyGenerator** instance. -2. Randomly generate a symmetric key using **SymKeyGenerator**. -3. Obtain binary data of the key generated. +2. Randomly generate a symmetric key using **SymKeyGenerator**. +3. Obtain the binary data of the key generated. -The following example demonstrates how to randomly generate a 256-bit AES key using promise-based APIs. +Example: Randomly generate an AES key (256 bits) in promise mode. -```javascript +```js import cryptoFramework from '@ohos.security.cryptoFramework'; // Output the byte streams in hexadecimal format. @@ -98,12 +103,14 @@ function testGenerateAesKey() { } ``` -Example 3: Generate an asymmetric key pair from the binary RSA key data. +### Converting Binary Data into an RSA Key Pair + +Generate an RSA asymmetric key pair from the binary data. 1. Obtain the binary data of the RSA public or private key. The public key must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format. The private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. -2. Create an **AsyKeyGenerator** instance and call **convertKey()** to convert the key binary data (data of the private or public key, or both) into a **KeyPair** instance. +2. Create an **AsyKeyGenerator** instance, and use **convertKey()** to convert the key binary data (data of the private or public key, or both) into a **KeyPair** instance. -```javascript +```js import cryptoFramework from '@ohos.security.cryptoFramework'; function convertAsyKey() { @@ -121,22 +128,24 @@ function convertAsyKey() { > **NOTE** > -> The public key material to be converted in **convertKey()** must be in the DER format complying with X.509 specifications, and the private key material must be in the DER format complying with PKCS #8 specifications. +> The public key binary data to be converted by **convertKey()** must be in the DER format complying with X.509 specifications, and the private key binary data must be in the DER format complying with PKCS #8 specifications. -Example 4: Generate an asymmetric key pair from the binary ECC key data. +### Converting Binary Data into an ECC Key Pair + +Generate an ECC asymmetric key pair from the binary data. 1. Obtain the ECC binary key data and encapsulate it into a **DataBlob** instance. -2. Call **convertKey()** to convert the key binary data (data of the private or public key, or both) into a **KeyPair** instance. +2. Use **convertKey()** to convert the binary data (data of the private or public key, or both) into a **KeyPair** instance. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; function convertEccAsyKey() { let pubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,83,96,142,9,86,214,126,106,247,233,92,125,4,128,138,105,246,162,215,71,81,58,202,121,26,105,211,55,130,45,236,143,55,16,248,75,167,160,167,106,2,152,243,44,68,66,0,167,99,92,235,215,159,239,28,106,124,171,34,145,124,174,57,92]); let priKeyArray = new Uint8Array([48,49,2,1,1,4,32,115,56,137,35,207,0,60,191,90,61,136,105,210,16,27,4,171,57,10,61,123,40,189,28,34,207,236,22,45,223,10,189,160,10,6,8,42,134,72,206,61,3,1,7]); let pubKeyBlob = { data: pubKeyArray }; let priKeyBlob = { data: priKeyArray }; - let generator = cryptoFramework.createAsyKeyGenerator("ECC256"); + let generator = cryptoFrameWork.createAsyKeyGenerator("ECC256"); generator.convertKey(pubKeyBlob, priKeyBlob, (error, data) => { if (error) { AlertDialog.show({message : "Convert keypair fail"}); @@ -146,15 +155,17 @@ function convertEccAsyKey() { } ``` -Example 5: Generate a symmetric key from binary data. +### Converting Binary Data into a 3DES Key + +Generate a symmetric key from the binary data. 1. Create a **SymKeyGenerator** instance. -2. Generate a symmetric key from the binary data passed in. -3. Obtain binary data of the key generated. +2. Convert the binary data into a **SymKey** instance. +3. Obtain the binary data of the key instance generated. -The following example demonstrates how to generate a 3DES key (192 bits only) using callback-based APIs. +Example: Generate a 3DES key (192 bits only) in callback mode. -```javascript +```js import cryptoFramework from '@ohos.security.cryptoFramework'; // Output the byte streams in hexadecimal format. @@ -189,48 +200,259 @@ function testConvertAesKey() { let encodedKey = key.getEncoded(); // Obtain the binary data of the symmetric key and output a 192-bit byte stream. console.info('key getEncoded hex: ' + uint8ArrayToShowStr(encodedKey.data)); }) - } catch (error) { // Throw an exception immediately in synchronous mode when an error is detected during the parameter check. + } catch (error) { // Throw an exception immediately after an error is detected during the parameter check. console.error(`convertKey failed, ${error.code}, ${error.message}`); return; } } ``` -## Encrypting and Decrypting Data +## Generating an Asymmetric Key Object and Obtaining Key Parameters + +### When to Use + +Typical key generation operations involve the following: +1. Create a key object based on the specified asymmetric key parameters for subsequent encryption and decryption. +2. Obtain the parameter properties of an asymmetric key object for storage or transmission. + +> **NOTE** +> +> - Key parameters can be used to generate asymmetric keys from API version 10. +> - Asymmetric systems use a public key (**PubKey**) to encrypt data and a related private key (**PriKey**) to decrypt it. The public key and private key form a key pair (**KeyPair**). For details about asymmetric key parameters, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). + +### Available APIs + +The following table describes the APIs used in typical key generation operations. For more information about the APIs, see [AsyKeyGeneratorBySpec](../reference/apis/js-apis-cryptoFramework.md#asykeygeneratorbyspec10). + +|Instance|API|Description| +|---|---|---| +|AsyKeyGeneratorBySpec|generateKeyPair(callback: AsyncCallback): void;|Generates a **KeyPair** instance based on the key parameters. This API uses an asynchronous callback to return the result.| +|AsyKeyGeneratorBySpec|generateKeyPair(): Promise;|Generates a **KeyPair** instance based on the key parameters. This API uses a promise to return the result.| +|AsyKeyGeneratorBySpec|generatePriKey(callback: AsyncCallback): void;|Generates a **PriKey** instance based on the key parameters. This API uses an asynchronous callback to return the result.| +|AsyKeyGeneratorBySpec|generatePriKey(): Promise;|Generates a **PriKey** instance based on the key parameters. This API uses a promise to return the result.| +|AsyKeyGeneratorBySpec|generatePubKey(callback: AsyncCallback): void;|Generates a **PubKey** instance based on the key parameters. This API uses an asynchronous callback to return the result.| +|AsyKeyGeneratorBySpec|generatePubKey(): Promise;|Generates a **PubKey** instance based on the key parameters. This API uses a promise to return the result.| +| PriKey | getAsyKeySpec(itemType: AsyKeySpecItem): bigint \| string \| number; | Obtains the key specifications of a **PriKey** instance.| +| PubKey | getAsyKeySpec(itemType: AsyKeySpecItem): bigint \| string \| number; | Obtains the key specifications of a **PubKey** instance.| + +### Generating an ECC Key Pair and Obtaining Key Specifications -**When to Use** +Generate an ECC key pair based on parameters and obtain the key specifications. + +1. Create an **AsyKeyGenerator** based on key parameters. +2. Use the **AsyKeyGenerator** to generate an asymmetric key pair based on the specified key parameters. +3. Obtain the key specifications of a key object. + +Example: Generate an ECC key based on key parameters in promise mode. + +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; + +// Print bigint information. +function showBigIntInfo(bnName, bnValue) { + console.warn(bnName + ":"); + console.warn(". Decimal: " + bnValue.toString()); + console.warn(". Hexadecimal: " + bnValue.toString(16)); + console.warn (". Length (bits): " + bnValue.toString(2).length); +} + +// Construct the EccCommonSpec struct based on the key specifications. The EccCommonSpec struct defines the common parameters of the ECC private key and public key. +function genEccCommonSpec() { + let fieldFp = { + fieldType : "Fp", + p : BigInt("0xffffffffffffffffffffffffffffffff000000000000000000000001") + } + + let G = { + x : BigInt("0xb70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21"), + y : BigInt("0xbd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34") + } + + let eccCommonSpec = { + algName : "ECC", + specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC, + field : fieldFp, + a : BigInt("0xfffffffffffffffffffffffffffffffefffffffffffffffffffffffe"), + b : BigInt("0xb4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4"), + g : G, + n : BigInt("0xffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d"), + h : 1 + } + return eccCommonSpec; +} + +// Print the ECC key specifications. +function showEccSpecDetailInfo(key, keyType) { + console.info("show detail of " + keyType + ":"); + try { + let p = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FP_P_BN); + showBigIntInfo("--- p", p); //length is 224, hex : ffffffffffffffffffffffffffffffff000000000000000000000001 + + let a = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_A_BN); + showBigIntInfo("--- a", a); // length is 224, hex : fffffffffffffffffffffffffffffffefffffffffffffffffffffffe + + let b = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_B_BN); + showBigIntInfo("--- b", b); // length is 224, hex : b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4 + + let gX = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_G_X_BN); + showBigIntInfo("--- gX", gX); // length is 224, hex : b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21 + + let gY = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_G_Y_BN); + showBigIntInfo("--- gY", gY); // length is 224, hex : bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34 + + let n = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_N_BN); + showBigIntInfo("--- n", n); // length is 224, hex : ffffffffffffffffffffffffffff16a2e0b8f03e13dd29455c5c2a3d + + let h = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_H_NUM); + console.warn("--- h: " + h); //key h: 1 + + let fieldType = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FIELD_TYPE_STR); + console.warn("--- field type: " + fieldType); // key field type: Fp + + let fieldSize = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_FIELD_SIZE_NUM); + console.warn("--- field size: " + fieldSize); // key field size: 224 + + let curveName = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_CURVE_NAME_STR); + console.warn("--- curve name: " + curveName); // key curve name: NID_secp224r1 + + if (keyType == "priKey") { + let sk = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_SK_BN); + showBigIntInfo("--- sk", sk); + } else if (keyType == "pubKey") { + let pkX = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_PK_X_BN); + showBigIntInfo("--- pkX", pkX); + let pkY = key.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.ECC_PK_Y_BN); + showBigIntInfo("--- pkY", pkY); + } + } catch (error) { + console.error("getAsyKeySpec error"); + console.error("error code: " + error.code + ", message is: " + error.message); + } +} + +// Generate an ECC key pair based on the EccCommonSpec instance and obtain the key specifications. +function testEccUseCommKeySpecGet() +{ + try { + let commKeySpec = genEccCommonSpec(); // Construct the EccCommonSpec object. + let generatorBySpec = cryptoFramework.createAsyKeyGeneratorBySpec(commKeySpec); // Create an AsyKeyGenerator instance based on the EccCommonSpec object. + let keyPairPromise = generatorBySpec.generateKeyPair(); // Generate an ECC key pair. + keyPairPromise.then( keyPair => { + showEccSpecDetailInfo(keyPair.priKey, "priKey"); // Obtain the ECC specifications of the private key. + showEccSpecDetailInfo(keyPair.pubKey, "pubKey"); // Obtain the ECC specifications of the public key. + }).catch(error => { + console.error("generateComm error"); + console.error("error code: " + error.code + ", message is: " + error.message); + }) + } catch(error) { + console.error("testEccUseCommSpec error"); + console.error("error code: " + error.code + ", message is: " + error.message); + } +} +``` + +### Generating an RSA Public Key and Obtaining Key Specifications + +Generate an RSA public key based on parameters and obtain key specifications. + +1. Create an **AsyKeyGenerator** based on key parameters. +2. Use the **AsyKeyGenerator** to generate the public key of an asymmetric key pair. +3. Obtain the key specifications of the public key object. + +Example: Generate an RSA public key based on key parameters in callback mode. +```js +import cryptoFramework from '@ohos.security.cryptoFramework'; + +// Generate RSA public key specifications. +function genRsaPubKeySpec(nIn : bigint, eIn : bigint) { + let rsaCommSpec = { n : nIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC }; + let rsaPubKeySpec = { params: rsaCommSpec, pk : eIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.PUBLIC_KEY_SPEC }; + return rsaPubKeySpec; +} + +// Construct an RSA public key specifications object based on the key parameters. +function genRsa2048PubKeySpec() { + let nIn = BigInt("0x9260d0750ae117eee55c3f3deaba74917521a262ee76007cdf8a56755ad73a1598a1408410a01434c3f5bc54a88b57fa19fc4328daea0750a4c44e88cff3b2382621b80f670464433e4336e6d003e8cd65bff211da144b88291c2259a00a72b711c116ef7686e8fee34e4d933c868187bdc26f7be071493c86f7a5941c3510806ad67b0f94d88f5cf5c02a092821d8626e8932b65c5bd8c92049c210932b7afa7ac59c0e886ae5c1edb00d8ce2c57633db26bd6639bff73cee82be9275c402b4cf2a4388da8cf8c64eefe1c5a0f5ab8057c39fa5c0589c3e253f0960332300f94bea44877b588e1edbde97cf2360727a09b775262d7ee552b3319b9266f05a25"); + let eIn = BigInt("0x010001"); + return genRsaPubKeySpec(nIn, eIn); +} + +// Compare the RSA public key specifications with the expected values. +function compareRsaPubKeyBySpec(rsaKeySpec, n, e) { + if (rsaKeySpec.params.n != n) { + return false; + } + if (rsaKeySpec.pk != e) { + return false; + } + return true; +} + +// Generate an RSA public key based on the RSA public key specifications, obtain the key specifications, and compare the key specifications with the expected values. +function rsaUsePubKeySpecGetCallback() { + let rsaPubKeySpec = genRsa2048PubKeySpec(); + let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaPubKeySpec); + rsaGeneratorSpec.generatePubKey((error, key) => { + let pubKey = key; + let nBN = pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.RSA_N_BN); + let eBN = pubKey.getAsyKeySpec(cryptoFramework.AsyKeySpecItem.RSA_PK_BN); + if (compareRsaPubKeyBySpec(rsaPubKeySpec, nBN, eBN) != true) { + AlertDialog.show({ message : "error pub key big number"} ); + } else { + console.info("n, e in the pubKey are same as the spec."); + } + if (error) { + console.error("generate pubKey error" + "error code: " + error.code + "error message" + error.message); + } + }); +} +``` + +## Encryption and Decryption + +### When to Use Important data needs to be encrypted in data storage or transmission for security purposes. Typical encryption and decryption operations involve the following: 1. Encrypt and decrypt data using a symmetric key. 2. Encrypt and decrypt data using an asymmetric key pair. +3. Obtain and set the **CipherSpecItem** parameter when the PKCS1_OAEP padding mode is used in RSA. -**Available APIs** +> **NOTE** +> +> - From API version 10, [CipherSpecItem](../reference/apis/js-apis-cryptoFramework.md#cipherspecitem10) can be obtained and set when the PKCS1_OAEP padding mode is used in RSA. +> - From API version 10, the string parameter without the key length is supported in encryption and decryption. + +### Available APIs + +The following table describes the APIs used in the typical encryption and decryption operations. For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). + +> **NOTE** +> +> Due to complexity of cryptographic algorithms, the implementation varies depending on the key specifications and parameters you use, and cannot be enumerated by sample code. Before you start, understand the APIs to ensure correct use of these APIs. -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
Due to the complexity of cryptographic algorithms, the implementation varies depending on the specifications and parameters you use, and cannot be enumerated by sample code. Before you start, understand the APIs in the API reference to ensure correct use of these APIs. -The table below describes the APIs used in this guide. |Instance|API|Description| |---|---|---| -|cryptoFramework|createCipher(transformation : string) : Cipher|Creates a **Cipher** instance.| -|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void|Sets a key and initializes the **Cipher** instance. This API uses an asynchronous callback to return the result.| -|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\|Sets a key and initializes the **Cipher** instance. This API uses a promise to return the result.| +|cryptoFramework|createCipher(transformation : string) : Cipher|Creates a **Cipher** instance based on the algorithm specified by **transformation**.| +|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void|Initializes the **Cipher** instance. This API uses an asynchronous callback to return the result.| +|Cipher|init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\|Initializes the **Cipher** instance. This API uses a promise to return the result.| |Cipher|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for encryption and decryption. This API uses an asynchronous callback to return the result.| |Cipher|update(data : DataBlob) : Promise\|Updates the data for encryption and decryption. This API uses a promise to return the result.| |Cipher|doFinal(data : DataBlob, callback : AsyncCallback\) : void|Finalizes the encryption or decryption. This API uses an asynchronous callback to return the result.| |Cipher|doFinal(data : DataBlob) : Promise\|Finalizes the encryption or decryption. This API uses a promise to return the result.| +|Cipher|getCipherSpec(itemType: CipherSpecItem): string \| Uint8Array|Obtains cipher specifications. Currently, only the RSA is supported.| +|Cipher|setCipherSpec(itemType: CipherSpecItem, itemValue: Uint8Array): void|Sets cipher specifications. Currently, only the RSA is supported.| -**How to Develop** +### Encrypting and Decrypting Data Using AES GCM (Promise) -Example 1: Encrypt and decrypt data using a symmetric key. +Encrypt and decrypt data using an AES symmetric key. 1. Create a **SymKeyGenerator** instance. -2. Use the key generator to generate a symmetric key. +2. Use the **SymKeyGenerator** to randomly generate a symmetric key. 3. Create a **Cipher** instance. 4. Encrypt or decrypt data. -The following example demonstrates how to use the AES-GCM to encrypt and decrypt data with promise-based APIs. - ```js import cryptoFramework from '@ohos.security.cryptoFramework'; @@ -251,7 +473,7 @@ function genGcmParamsSpec() { arr = [0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0]; // 16 bytes let dataTag = new Uint8Array(arr); let tagBlob = {data : dataTag}; // The authTag of GCM is obtained by doFinal() in encryption and passed in params of init() in decryption. - + let gcmParamsSpec = {iv : ivBlob, aad : aadBlob, authTag : tagBlob, algName : "GcmParamsSpec"}; return gcmParamsSpec; } @@ -281,17 +503,7 @@ function uint8ArrayToString(array) { return arrayString; } -function genKeyMaterialBlob() { - let arr = [ - 0xba, 0x3d, 0xc2, 0x71, 0x21, 0x1e, 0x30, 0x56, - 0xad, 0x47, 0xfc, 0x5a, 0x46, 0x39, 0xee, 0x7c, - 0xba, 0x3b, 0xc2, 0x71, 0xab, 0xa0, 0x30, 0x72]; // keyLen = 192 (24 bytes) - let keyMaterial = new Uint8Array(arr); - return {data : keyMaterial}; -} - - -// Automatically generate a key in AES GCM mode and return the result in a promise. +// Automatically generate an AES GCM key in promise mode. function testAesGcm() { return new Promise((resolve, reject) => { setTimeout(() => { @@ -308,7 +520,7 @@ function testAesGcm() { console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`); // Use the key generator to randomly generate a 128-bit symmetric key. let promiseSymKey = symKeyGenerator.generateSymKey(); - // Constructor + // Generate GCM parameter specifications. globalGcmParams = genGcmParamsSpec(); // Create a Cipher instance. @@ -344,7 +556,7 @@ function testAesGcm() { globalGcmParams.authTag = authTag; return; }).then(() => { - // Initialize the cipher environment and start decryption. + // Initialize the Cipher instance and start decryption. let mode = cryptoFramework.CryptoMode.DECRYPT_MODE; let promiseInit = globalCipher.init(mode, globalKey, globalGcmParams); // init return promiseInit; @@ -365,7 +577,14 @@ function testAesGcm() { } ``` -The following example demonstrates how to use the the 3DES ECB to convert existing data into a key and encrypt and decrypt data using callback-based APIs. +### Encrypting and Decrypting Data Using a 3DES ECB Symmetric Key (Callback) + +Encrypt and decrypt data using a 3DES symmetric key. + +1. Create a **SymKeyGenerator** instance. +2. Generate a key based on the existing binary data. +3. Create a **Cipher** instance. +4. Encrypt or decrypt data using the **Cipher** instance. ```js import cryptoFramework from '@ohos.security.cryptoFramework'; @@ -409,7 +628,7 @@ function genKeyMaterialBlob() { return {data : keyMaterial}; } -// Use the 3DES ECB to Generate a key from the existing data and encrypt and decrypt data using callback-based APIs. +// Generate a 3DES ECB key from the existing data in callback mode. function test3DesEcb() { // Create a SymKeyGenerator instance. let symAlgName = '3DES192'; @@ -444,7 +663,7 @@ function test3DesEcb() { console.info('key getEncoded hex: ' + uint8ArrayToShowStr(encodedKey.data)); globalKey = key; - // Initialize the cipher environment and start encryption. + // Initialize the Cipher instance and start encryption. let mode = cryptoFramework.CryptoMode.ENCRYPT_MODE; // init globalCipher.init(mode, key, null, (err, ) => { @@ -465,7 +684,7 @@ function test3DesEcb() { globalCipherText = new Uint8Array(globalCipherText); globalCipherText = {data : globalCipherText}; } - // Initialize the cipher environment and start decryption. + // Initialize the Cipher instance and start decryption. let mode = cryptoFramework.CryptoMode.DECRYPT_MODE; // init globalCipher.init(mode, globalKey, null, (err, ) => { @@ -490,9 +709,19 @@ function test3DesEcb() { } } ``` -The following example demonstrates how to call **update()** multiple times to implement AES GCM encryption and decryption by using promise-based APIs. -```javascript +### Encrypting and Decrypting Data Using an AES GCM Symmetric Key by Segment (Promise) + +Use an AES symmetric key to encrypt and decrypt a large amount of data by segment using **update()**. + +1. Create a **SymKeyGenerator** instance. +2. Generate a key based on the existing binary data. +3. Create a **Cipher** instance. +4. Encrypt or decrypt data. + +Example: Encrypt and decrypt a large amount in AES GCM mode by calling **update()** multiple times in promise mode. + +```js import cryptoFramework from '@ohos.security.cryptoFramework'; var globalCipher; @@ -550,7 +779,7 @@ function testAesMultiUpdate() { console.info(`symKeyGenerator algName: ${symKeyGenerator.algName}`); // Use the key generator to randomly generate a 128-bit symmetric key. let promiseSymKey = symKeyGenerator.generateSymKey(); - // Constructor + // Construct key specifications. globalGcmParams = genGcmParamsSpec(); // Create a Cipher instance. @@ -578,7 +807,7 @@ function testAesMultiUpdate() { let messageArr = []; let updateLength = 20; // Pass in 20 bytes by update() each time. globalCipherText = []; - + for (let i = 0; i <= plainText.length; i++) { if ((i % updateLength == 0 || i == plainText.length) && messageArr.length != 0) { let message = new Uint8Array(messageArr); @@ -602,7 +831,7 @@ function testAesMultiUpdate() { globalGcmParams.authTag = authTag; return; }).then(() => { - // Initialize the cipher environment and start decryption. + // Initialize the Cipher instance and start decryption. let mode = cryptoFramework.CryptoMode.DECRYPT_MODE; let promiseInit = globalCipher.init(mode, globalKey, globalGcmParams); // init return promiseInit; @@ -632,76 +861,103 @@ function testAesMultiUpdate() { } ``` -Example 2: Encrypt and decrypt data using an asymmetric key pair. +### Encrypting and Decrypting Data Using RSA + +Encrypt and decrypt data using an RSA asymmetric key pair. 1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. 2. Create a **Cipher** instance.
Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode. -3. Perform encryption and decryption operations.
Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data. +3. Encrypt and decrypt data.
Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data. -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" let plan = "This is cipher test."; +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpArray = new Uint8Array(arr); - return tmpArray; + return new Uint8Array(arr); } +// Encrypt the message in promise mode. function encryptMessageProMise() { + // Create an AsyKeyGenerator instance. let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + // Create a Cipher instance. let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); + // Generate an asymmetric key pair using the AsyKeyGenerator instance. let keyGenPromise = rsaGenerator.generateKeyPair(); keyGenPromise.then(rsaKeyPair => { let pubKey = rsaKeyPair.pubKey; + // Initialize the Cipher instance and use the public key to encrypt the data. return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); }).then(() => { + // doFinal let input = { data : stringToUint8Array(plan) }; return cipher.doFinal(input); }).then(dataBlob => { + // Obtain the encrypted data. console.info("EncryptOutPut is " + dataBlob.data); }); } +// Encrypt the message in callback mode. function encryptMessageCallback() { + // Create an AsyKeyGenerator instance. let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + // Create a Cipher instance. let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); + // Generate an asymmetric key pair using the AsyKeyGenerator instance. rsaGenerator.generateKeyPair(function (err, keyPair) { let pubKey = keyPair.pubKey; + // Initialize the Cipher instance and use the public key to encrypt the data. cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) { let input = {data : stringToUint8Array(plan) }; + // doFinal cipher.doFinal(input, function (err, data) { + // Obtain the encrypted data. console.info("EncryptOutPut is " + data.data); }) }) }) } +// Encrypt and decrypt the message in promise mode. function decryptMessageProMise() { + // Create an AsyKeyGenerator instance. let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + // Create a Cipher instance for encryption. let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); + // Create a Cipher instance for decryption. let decoder = cryptoFramework.createCipher("RSA1024|PKCS1"); + // Generate an asymmetric key pair using the AsyKeyGenerator instance. let keyGenPromise = rsaGenerator.generateKeyPair(); let keyPair; let cipherDataBlob; let input = { data : stringToUint8Array(plan) }; keyGenPromise.then(rsaKeyPair => { keyPair = rsaKeyPair; + // Initialize the Cipher instance and use the public key to encrypt the message. return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null); }).then(() => { + // Call doFinal() to encrypt data. return cipher.doFinal(input); }).then(dataBlob => { + // Obtain the encrypted information and use it as the input parameter for decryption. console.info("EncryptOutPut is " + dataBlob.data); AlertDialog.show({message : "output" + dataBlob.data}); cipherDataBlob = dataBlob; + // Initialize the Cipher instance and use the private key to decrypt the message. return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null); }).then(() => { + // Call doFinal() to decrypt the message. return decoder.doFinal(cipherDataBlob); }).then(decodeData => { + // Check whether the decrypted data is consistent with the original data. if (decodeData.data.toString() === input.data.toString()) { AlertDialog.show({message : "decrypt success"}); return; @@ -710,27 +966,38 @@ function decryptMessageProMise() { }); } +// Encrypt and decrypt the message in callback mode. function decryptMessageCallback() { + // Create an AsyKeyGenerator instance. let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + // Create a Cipher instance for encryption. let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); + // Create a Cipher instance for decryption. let decoder = cryptoFramework.createCipher("RSA1024|PKCS1"); let plainText = "this is cipher text"; let input = {data : stringToUint8Array(plainText) }; let cipherData; let keyPair; + // Generate an asymmetric key pair using the AsyKeyGenerator instance. rsaGenerator.generateKeyPair(function (err, newKeyPair) { keyPair = newKeyPair; + // Initialize the Cipher instance and use the public key to encrypt the message. cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null, function (err, data) { + // Call doFinal() to encrypt the message. cipher.doFinal(input, function (err, data) { + // Obtain the encrypted information and use it as the input parameter for decryption. AlertDialog.show({ message : "EncryptOutPut is " + data.data} ); cipherData = data; + // Initialize the Cipher instance and use the private key to decrypt the message. decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null, function (err, data) { + // Call doFinal() to decrypt the message. decoder.doFinal(cipherData, function (err, data) { + // Check whether the decrypted data is consistent with the original data. if (input.data.toString() === data.data.toString()) { - AlertDialog.show({ message : "decrype success"} ); + AlertDialog.show({ message : "decryption success"} ); return; } - AlertDialog.show({ message : "decrype fail"} ); + AlertDialog.show({ message : "decryption fail"} ); }); }); }); @@ -738,17 +1005,25 @@ function decryptMessageCallback() { }); } ``` -The following example demonstrates how to implement RSA asymmetric encryption and decryption (**doFinal()** is called multiple times). -```javascript + +### Encrypting and Decrypting Data Using RSA by Segment + +Use an RSA asymmetric key pair to encrypt and decrypt a large amount of data by segment. + +1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. +2. Create a **Cipher** instance.
Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode. +3. Encrypt and decrypt data.
Call **doFinal()** provided by the **Cipher** instance multiple times to encrypt and decrypt data. + +```js import cryptoFramework from "@ohos.security.cryptoFramework" +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpArray = new Uint8Array(arr); - return tmpArray; + return new Uint8Array(arr); } // Convert byte streams into strings in plaintext. @@ -784,9 +1059,9 @@ function encryptLongMessagePromise() { resolve("testRsaMultiDoFinal"); }, 10); }).then(() => { - return asyKeyGenerator.generateKeyPair(); // Generate an RSA key. + return asyKeyGenerator.generateKeyPair(); // Generate an RSA key pair. }).then(keyPair => { - globalKeyPair = keyPair; // Save the key to global variables. + globalKeyPair = keyPair; // Save the key pair as a global variable. return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, globalKeyPair.pubKey, null); }).then(async () => { globalCipherOutput = []; @@ -825,21 +1100,138 @@ function encryptLongMessagePromise() { > **NOTE** > -> - In RSA encryption and decryption, **init()** cannot be repeatedly called to initialize the **Cipher** instance. You must create a **Cipher** instance for each encryption and decryption. -> - The RSA encryption has a limit on the length of the plaintext to be encrypted. For details, see "Basic Concepts" in [Cryptographic Framework Overview](cryptoFramework-overview.md). +> - In RSA encryption and decryption, **init()** cannot be repeatedly called to initialize a **Cipher** instance. You must create a **Cipher** instance for each encryption and decryption. +> - The RSA encryption has a limit on the length of the plaintext to be encrypted. For details, see [Encryption and Decryption](cryptoFramework-overview.md#encryption-and-decryption). > - In RSA decryption, the length of the ciphertext to be decrypted each time is the number of bits of the RSA key divided by 8. -## Generating and Verifying a Signature +### Using PKCS1_OAEP in RSA Encryption and Decryption + +Use the PKCS1_OAEP padding mode in RSA encryption and decryption in promise mode. -**When to Use** +1. Generate an RSA key pair based on the key parameters.
Call **createAsyKeyGeneratorBySpec()** to create an **AsyKeyGeneratorBySpec** object and generate an RSA asymmetric key pair. (You can also use **createAsyKeyGenerator()** to randomly generate or convert an RSA key object.) +2. Create a **Cipher** instance.
Call **createCipher()** to create a cipher instance, initialize the cipher instance, set the key and encryption/decryption mode, use **setCipherSpec()** to set PKCS1_OAEP **pSource**, and use **update()** to pass in data. +3. Encrypt and decrypt data.
Call the **doFinal()** provided by the **Cipher** class to perform encryption or decryption. The **pSource** of the **Cipher** instance to be encrypted must be the same as that decrypted. + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Convert strings in plaintext into byte streams. +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + +// Construct the key parameters of the RSA asymmetric key pair based on the key pair specifications. +function genRsaKeyPairSpec(nIn : bigint, eIn : bigint, dIn : bigint) { + let rsaCommSpec = { n : nIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC }; + let rsaKeyPairSpec = { params: rsaCommSpec, sk : dIn, pk : eIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC }; + return rsaKeyPairSpec; +} + +// Generate RSA2048 key pair parameters. +function genRsa2048KeyPairSpec() { + let nIn = BigInt("0x9260d0750ae117eee55c3f3deaba74917521a262ee76007cdf8a56755ad73a1598a1408410a01434c3f5bc54a88b57fa19fc4328daea0750a4c44e88cff3b2382621b80f670464433e4336e6d003e8cd65bff211da144b88291c2259a00a72b711c116ef7686e8fee34e4d933c868187bdc26f7be071493c86f7a5941c3510806ad67b0f94d88f5cf5c02a092821d8626e8932b65c5bd8c92049c210932b7afa7ac59c0e886ae5c1edb00d8ce2c57633db26bd6639bff73cee82be9275c402b4cf2a4388da8cf8c64eefe1c5a0f5ab8057c39fa5c0589c3e253f0960332300f94bea44877b588e1edbde97cf2360727a09b775262d7ee552b3319b9266f05a25"); + let eIn = BigInt("0x010001"); + let dIn = BigInt("0x6a7df2ca63ead4dda191d614b6b385e0d9056a3d6d5cfe07db1daabee022db08212d97613d3328e0267c9dd23d787abde2afcb306aeb7dfce69246cc73f5c87fdf06030179a2114b767db1f083ff841c025d7dc00cd82435b9a90f695369e94df23d2ce458bc3b3283ad8bba2b8fa1ba62e2dce9accff3799aae7c840016f3ba8e0048c0b6cc4339af7161003a5beb864a0164b2c1c9237b64bc87556994351b27506c33d4bcdfce0f9c491a7d6b0628c7c852be4f0a9c3132b2ed3a2c8881e9aab07e20e17deb074691be677776a78b5c502e05d9bdde72126b3738695e2dd1a0a98a14247c65d8a7ee79432a092cb0721a12df798e44f7cfce0c498147a9b1"); + return genRsaKeyPairSpec(nIn, eIn, dIn); +} + +function rsaUseSpecDecryptOAEPPromise() { + let plan = "This is cipher test."; + // Obtain the key parameter object of the RSA key pair. + let rsaKeyPairSpec = genRsa2048KeyPairSpec(); + // Generate an RSA key pair based on the RSA key parameters. + let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaKeyPairSpec); + let keyGenPromise = rsaGeneratorSpec.generateKeyPair(); + let cipher = cryptoFramework.createCipher("RSA|PKCS1_OAEP|SHA256|MGF1_SHA1"); + let decoder = cryptoFramework.createCipher("RSA|PKCS1_OAEP|SHA256|MGF1_SHA1"); + let keyPair; + let cipherDataBlob; + // Set the pSource, which defines the encoding input P filled by OAEP. + let pSource = new Uint8Array([1,2,3,4]); + let input = { data : stringToUint8Array(plan) }; + // Generate the key pair. + keyGenPromise.then(rsaKeyPair => { + keyPair = rsaKeyPair; + // Initialize the Cipher instance for encryption. + return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null); + }).then(() => { + // Set and obtain the cipher specifications after the initialization. + cipher.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); + let retP = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR); + // Check whether the obtained PSource is the same as the PSource set. + if (retP.toString() != pSource.toString()) { + AlertDialog.show({message : "error init pSource" + retP}); + } else { + console.info("pSource changed ==" + retP); + } + // Obtain other OAEP parameters. + let md = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR); + console.info("md == " + md); + let mgf = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF_NAME_STR); + console.info("mgf == " + mgf); + let mgf1Md = cipher.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_MD_STR); + console.info("mgf1Md == " + mgf1Md); + return cipher.doFinal(input); + }).then(dataBlob => { + console.info("EncryptOutPut is " + dataBlob.data); + cipherDataBlob = dataBlob; + // The get() and set() operations can be performed before the init() operation of the Cipher object and are equivalent to those after the init() operation. For example, set and get the decoder. + decoder.setCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR, pSource); + let retP = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_PSRC_UINT8ARR); + // Check whether the obtained PSource is the same as the PSource set. + if (retP.toString() != pSource.toString()) { + AlertDialog.show({message : "error init pSource" + retP}); + } else { + console.info("pSource changed ==" + retP); + } + // Obtain other OAEP parameters. + let md = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MD_NAME_STR); + console.info("md == " + md); + let mgf = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF_NAME_STR); + console.info("mgf == " + mgf); + let mgf1Md = decoder.getCipherSpec(cryptoFramework.CipherSpecItem.OAEP_MGF1_MD_STR); + console.info("mgf1Md == " + mgf1Md); + // Initialize the decryption operation. + return decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null); + }).then(() => { + return decoder.doFinal(cipherDataBlob); + }).then(decodeData => { + // The decryption is successful. + if (decodeData.data.toString() === input.data.toString()) { + console.info("oaep decrypt success"); + AlertDialog.show({message : " oaep decrypt success"}); + } else { + AlertDialog.show({message : "oeap decrypt fail"}); + } + }); +} +``` + +## Signing and Signature Verification + +### When to Use A digital signature can be used to verify the authenticity of a message. Typical signing and signature verification operations involve the following: -- Use the RSA to generate and verify a signature. -- Use the ECC to generate and verify a signature. +1. Use RSA to generate a signature and verify the signature. +2. Use ECC to generate a signature and verify the signature. +3. Use RSA to generate a signature and verify the signature. Obtain and set **SignSpecItem** when the PSS padding mode is used. -**Available APIs** +> **NOTE** +> +> - From API version 10, [SignSpecItem](../reference/apis/js-apis-cryptoFramework.md#signspecitem10) can be set and obtained when the PSS padding mode is used. +> - From API version 10, the string parameter without the key length is supported in signature verification. + +### Available APIs -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md).
Due to the complexity of cryptographic algorithms, the implementation varies depending on the specifications and parameters you use, and cannot be enumerated by sample code. Before you start, understand the APIs in the API reference to ensure correct use of these APIs. +The following table describes the APIs used in typical signing and signature verification operations. For more information about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). + +> **NOTE** +> +> Due to complexity of cryptographic algorithms, the implementation varies depending on the specifications and parameters you use, and cannot be enumerated by sample code. Before you start, understand the APIs to ensure correct use of these APIs. |Instance|API|Description| |---|---|---| @@ -850,32 +1242,38 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry |Sign|update(data : DataBlob) : Promise\|Updates the data for signing. This API uses a promise to return the result.| |Sign|sign(data : DataBlob, callback : AsyncCallback\) : void|Signs the data. This API uses an asynchronous callback to return the result.| |Sign|sign(data : DataBlob) : Promise\|Signs the data. This API uses a promise to return the result.| +|Sign|getSignSpec(itemType: SignSpecItem): string \| number|Obtains the signing specifications. Currently, only the RSA is supported.| +|Sign|setSignSpec(itemType: SignSpecItem, itemValue: number): void|Sets signing specifications. Currently, only the RSA is supported.| |cryptoFramework|function createVerify(algName : string) : Verify|Creates a **Verify** instance.| -|Verify|init(priKey : PriKey, callback : AsyncCallback\) : void|Sets a key and initializes the **Verify** instance. This API uses an asynchronous callback to return the result.| -|Verify|init(priKey : PriKey) : Promise\|Sets a key and initializes the **Verify** instance. This API uses a promise to return the result.| +|Verify|init(pubKey : PubKey, callback : AsyncCallback\) : void|Sets a key and initializes the **Verify** instance. This API uses an asynchronous callback to return the result.| +|Verify|init(pubKey : PubKey) : Promise\|Sets a key and initializes the **Verify** instance. This API uses a promise to return the result.| |Verify|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for signature verification. This API uses an asynchronous callback to return the result.| |Verify|update(data : DataBlob) : Promise\|Updates the data for signature verification. This API uses a promise to return the result.| -|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\) : void|Verifies the signature. This API uses an asynchronous callback to return the result.| -|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise\|Verifies the signature. This API uses a promise to return the result.| +|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\) : void|Verifies a signature. This API uses an asynchronous callback to return the result.| +|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise\|Verifies a signature. This API uses a promise to return the result.| +|Verify|getVerifySpec(itemType: SignSpecItem): string \| number|Obtains signature verification specifications. Currently, only the RSA is supported.| +|Verify|setVerifySpec(itemType: SignSpecItem, itemValue: number): void|Sets signature verification specifications. Currently, only the RSA is supported.| + +### Signing and Signature Verification Using RSA -**How to Develop** +Use RSA to sign data and verify the signature. -Example 1: Use the RSA to generate and verify a signature. 1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. 2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. -3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature. +3. Generate a signature.
Call **update()** provided by the **Sign** class to pass in the data for signing and call **sign()** to generate a signature. 4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. -5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature. -```javascript +5. Verify the signature.
Call **update()** provided by the **Verify** class to pass in the signature data and call **verify()** to verify the signature. + +```js import cryptoFramework from "@ohos.security.cryptoFramework" +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpArray = new Uint8Array(arr); - return tmpArray; + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); } let globalKeyPair; @@ -887,7 +1285,7 @@ let input2 = { data : stringToUint8Array(plan2) }; function signMessagePromise() { let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); - let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); // From API version 10, a Sign instance can be created by specifying a string parameter defining the key specifications. let keyGenPromise = rsaGenerator.generateKeyPair(); keyGenPromise.then( keyPair => { globalKeyPair = keyPair; @@ -917,7 +1315,7 @@ function verifyMessagePromise() { function signMessageCallback() { let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); - let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); // From API version 10, a Sign instance can be created by specifying a string parameter defining the key specifications. rsaGenerator.generateKeyPair(function (err, keyPair) { globalKeyPair = keyPair; let priKey = globalKeyPair.priKey; @@ -944,23 +1342,26 @@ function verifyMessageCallback() { } ``` -Example 2: Use the ECDSA to generate and verify a signature. +### Signing and Signature Verification Using ECDSA + +Use the ECDSA to sign data and verify the signature. + 1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. 2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. -3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature. +3. Generate a signature.
Call **update()** provided by the **Sign** class to pass in the data for signing and call **doFinal()** to generate a signature. 4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. -5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature. +5. Verify the signature.
Call **update()** provided by the **Verify** class to pass in the signature data and call **doFinal()** to verify the signature. -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpArray = new Uint8Array(arr); - return tmpArray; + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); } let globalKeyPair; @@ -1028,17 +1429,27 @@ function verifyMessageCallback() { }) } ``` -The following example demonstrates how to call **update()** multiple times to implement signing and signature verification. -```javascript + +### Signing and Signature Verification Using RSA by Segment + +Use RSA to sign data and verify the signature by segment. + +1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing. +3. Generate a signature.
Call the **update()** provided by the **Sign** class multiple times to pass in data by segment and call **sign()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification. +5. Verify the signature.
Call the **update()** provided by the **Verify** class multiple times to pass in data by segment and call **verify()** to verify the signature. + +```js import cryptoFramework from "@ohos.security.cryptoFramework" +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpArray = new Uint8Array(arr); - return tmpArray; + return new Uint8Array(arr); } function signLongMessagePromise() { @@ -1056,16 +1467,16 @@ function signLongMessagePromise() { let cipherAlgName = "RSA1024|PKCS1|SHA256"; let globalKeyPair; let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(keyGenName); // Create an AsyKeyGenerator object. - let signer = cryptoFramework.createSign(cipherAlgName); //Create a cipher object for encryption. - let verifier = cryptoFramework.createVerify(cipherAlgName); // Create a Decoder object for decryption. + let signer = cryptoFramework.createSign(cipherAlgName); //Create a Sign object for signing. + let verifier = cryptoFramework.createVerify(cipherAlgName); // Create a Verify object for signature verification. return new Promise((resolve, reject) => { setTimeout(() => { resolve("testRsaMultiUpdate"); }, 10); }).then(() => { - return asyKeyGenerator.generateKeyPair(); // Generate an RSA key. + return asyKeyGenerator.generateKeyPair(); // Generate an RSA key pair. }).then(keyPair => { - globalKeyPair = keyPair; // Save the key to global variables. + globalKeyPair = keyPair; // Save the key pair as a global variable. return signer.init(globalKeyPair.priKey); }).then(async () => { // If the plaintext is too large, split the plaintext based on the specified length and cyclically call update() to pass in the plaintext. @@ -1095,26 +1506,183 @@ function signLongMessagePromise() { } ``` -## Generating a Digest +### Using PSS in RSA Signing and Signature Verification -**When to Use** +Use the PSS padding mode in RSA signing and signature verification in callback mode. -A message digest (MD) is a fixed size numeric representation of the content of a message, computed by a has function. It is sent with the message. The receiver can generate a digest for the message and compare it with the digest received. If the two digests are the same, the message integrity is verified. +1. Generate an RSA key pair based on the key parameters.
Call **createAsyKeyGeneratorBySpec** to create an **AsyKeyGeneratorBySpec** object and generate an RSA asymmetric key pair. +2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** object, initialize the **Sign** object, set the private key for signing, and set and obtain PSS parameters. +3. Generate a signature.
Call **update()** provided by the **Sign** class to pass in the data for signing and call **sign()** to generate a signature. +4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** object, initialize the object, set the public key for signature verification, and set and obtain PSS parameters. The signature verification is successful if the salt length is the same. +5. Verify the signature.
Call **update()** provided by the **Verify** class to pass in the signature data and call **verify()** to verify the signature. -Typical MD operations involve the following: +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Convert strings in plaintext into byte streams. +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + +// Construct the key parameters of the RSA asymmetric key pair based on the key pair specifications. +function genRsaKeyPairSpec(nIn : bigint, eIn : bigint, dIn : bigint) { + let rsaCommSpec = { n : nIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC }; + let rsaKeyPairSpec = { params: rsaCommSpec, sk : dIn, pk : eIn, algName : "RSA", specType : cryptoFramework.AsyKeySpecType.KEY_PAIR_SPEC }; + return rsaKeyPairSpec; +} + +// Generate RSA2048 key pair parameters. +function genRsa2048KeyPairSpec() { + let nIn = BigInt("0x9260d0750ae117eee55c3f3deaba74917521a262ee76007cdf8a56755ad73a1598a1408410a01434c3f5bc54a88b57fa19fc4328daea0750a4c44e88cff3b2382621b80f670464433e4336e6d003e8cd65bff211da144b88291c2259a00a72b711c116ef7686e8fee34e4d933c868187bdc26f7be071493c86f7a5941c3510806ad67b0f94d88f5cf5c02a092821d8626e8932b65c5bd8c92049c210932b7afa7ac59c0e886ae5c1edb00d8ce2c57633db26bd6639bff73cee82be9275c402b4cf2a4388da8cf8c64eefe1c5a0f5ab8057c39fa5c0589c3e253f0960332300f94bea44877b588e1edbde97cf2360727a09b775262d7ee552b3319b9266f05a25"); + let eIn = BigInt("0x010001"); + let dIn = BigInt("0x6a7df2ca63ead4dda191d614b6b385e0d9056a3d6d5cfe07db1daabee022db08212d97613d3328e0267c9dd23d787abde2afcb306aeb7dfce69246cc73f5c87fdf06030179a2114b767db1f083ff841c025d7dc00cd82435b9a90f695369e94df23d2ce458bc3b3283ad8bba2b8fa1ba62e2dce9accff3799aae7c840016f3ba8e0048c0b6cc4339af7161003a5beb864a0164b2c1c9237b64bc87556994351b27506c33d4bcdfce0f9c491a7d6b0628c7c852be4f0a9c3132b2ed3a2c8881e9aab07e20e17deb074691be677776a78b5c502e05d9bdde72126b3738695e2dd1a0a98a14247c65d8a7ee79432a092cb0721a12df798e44f7cfce0c498147a9b1"); + return genRsaKeyPairSpec(nIn, eIn, dIn); +} + +function verifyMessageCallbackPSS() { + let plan1 = "This is Sign test plan1"; + let plan2 = "This is Sign test plan1"; + let input1 = { data : stringToUint8Array(plan1) }; + let input2 = { data : stringToUint8Array(plan2) }; + let globalKeyPair; + let signMessageBlob; + // Obtain the key parameter object of the RSA key pair. + let rsaKeyPairSpec = genRsa2048KeyPairSpec(); + // Create an RSA key pair generator. + let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaKeyPairSpec); + // Both sign() and verify() support the RSA key with or without the length. + let signer = cryptoFramework.createSign("RSA|PSS|SHA256|MGF1_SHA256"); + let verifyer = cryptoFramework.createVerify("RSA2048|PSS|SHA256|MGF1_SHA256"); + rsaGeneratorSpec.generateKeyPair(function (err, keyPair) { + globalKeyPair = keyPair; + signer.init(globalKeyPair.priKey, function (err, data) { + // After the initialization, set and obtain the PSS parameters. + let setN = 32; + signer.setSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); + let saltLen = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); + console.info("SaltLen == " + saltLen); + let tf = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_TRAILER_FIELD_NUM); + console.info("trailer field == " + tf); + let md = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_MD_NAME_STR); + console.info("md == " + md); + let mgf = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_MGF_NAME_STR); + console.info("mgf == " + mgf); + let mgf1Md = signer.getSignSpec(cryptoFramework.SignSpecItem.PSS_MGF1_MD_STR); + console.info("mgf1Md == " + mgf1Md); + signer.update(input1, function (err, data) { + signer.sign(input2, function (err, data) { + // Before signature verification initialization, set and obtain PSS parameters. The functions are the same as those after initialization. + signMessageBlob = data; + AlertDialog.show({message : "res" + signMessageBlob.data}); + let setN = 32; + verifyer.setVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM, setN); + let saltLen = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_SALT_LEN_NUM); + console.info("SaltLen == " + saltLen); + let tf = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_TRAILER_FIELD_NUM); + console.info("trailer field == " + tf); + let md = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_MD_NAME_STR); + console.info("md == " + md); + let mgf = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_MGF_NAME_STR); + console.info("mgf == " + mgf); + let mgf1Md = verifyer.getVerifySpec(cryptoFramework.SignSpecItem.PSS_MGF1_MD_STR); + console.info("mgf1Md == " + mgf1Md); + verifyer.init(globalKeyPair.pubKey, function (err, data) { + verifyer.update(input1, function(err, data) { + verifyer.verify(input2, signMessageBlob, function(err, data) { + AlertDialog.show({message : "res " + data}); + }) + }); + }); + }); + }); + }); + }); +} +``` -1. Create an **Md** instance. -2. Add one or more segments of data for generating a digest. -3. Compute a digest. -4. Obtain the algorithm and length of a digest. +## Key Agreement -**Available APIs** +### When to Use + +Key agreement allows two parties to establish a shared secret over an insecure channel. + +> **NOTE** +> +> From API version 10, the string parameter without the key length is supported in key agreement. + +### Available APIs For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). +|Instance|API|Description| +|---|---|---| +|cryptoFramework|createKeyAgreement(algName : string) : KeyAgreement|Creates a **KeyAgreement** instance.| +|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\) : void|Generates a shared secret. This API uses an asynchronous callback to return the result.| +|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\|Generates a shared secret. This API uses a promise to return the result.| + +### How to Develop + +1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair. +2. Generate a shared secret by using the private and public ECC keys. + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" + +let globalKeyPair; + +function ecdhPromise() { + let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); + let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256"); // ECC is supported for key agreement from API version 10. + let keyGenPromise = eccGenerator.generateKeyPair(); + keyGenPromise.then( keyPair => { + globalKeyPair = keyPair; + return eccKeyAgreement.generateSecret(keyPair.priKey, keyPair.pubKey); + }).then((secret) => { + console.info("ecdh output is " + secret.data); + }).catch((error) => { + console.error("ecdh error."); + }); +} + +function ecdhCallback() { + let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); + let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256"); + eccGenerator.generateKeyPair(function (err, keyPair) { + globalKeyPair = keyPair; + eccKeyAgreement.generateSecret(keyPair.priKey, keyPair.pubKey, function (err, secret) { + if (err) { + console.error("ecdh error."); + return; + } + console.info("ecdh output is " + secret.data); + }); + }); +} +``` + +## Message Digest + +### When to Use + +A message digest (MD) is a fixed size numeric representation of the content of a message, computed by a hash function. It is sent with the message. The receiver can generate a digest for the message and compare it with the digest received. If the two digests are the same, the message integrity is verified. + +Typical MD operations involve the following: + +1. Create an **Md** instance with the specified digest algorithm (such as SHA-256). +2. Pass in one or more messages for generating a digest, and generate a digest. +3. Obtain the digest algorithm and digest length (in bytes). + +### Available APIs + +For more information about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). + | Instance | API | Description | | --------------- | ------------------------------------------------------------ | -------------------------------------------------- | -| cryptoFramework | function createMd(algName : string) : Md; | Creates an **Md** instance. | +| cryptoFramework | function createMd(algName : string) : Md; | Creates an **Md** instance with the specified algorithm. | | Md | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.| | Md | update(input : DataBlob) : Promise\; | Updates the data for a digest. This API uses a promise to return the result. | | Md | digest(callback : AsyncCallback\) : void; | Generates the digest. This API uses an asynchronous callback to return the result. | @@ -1122,226 +1690,155 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry | Md | getMdLength() : number; | Obtains the digest length based on the specified digest algorithm. | | Md | readonly algName : string; | Obtains the digest algorithm. | -**How to Develop** +### Generating a Digest -1. Call **createMd()** to create an **Md** instance. -2. Call **update()** to pass in the data for computing a digest. **update()** can be called multiple times to pass in the data by segment. -3. Call **digest()** to compute a digest. +1. Use **createMd()** to create an **Md** instance. +2. Use **update()** to pass in data. **update()** can be called multiple times. The algorithm library does not limit the data length of a single **update()**. +3. Use **digest()** to compute a digest. 4. Obtain the digest algorithm and length of the digest generated. -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -// Convert string into uint8Arr. +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; -} - -// Generate a dataBlob of the given length. -function GenDataBlob(dataBlobLen) { - var dataBlob; - if (dataBlobLen == 12) { - dataBlob = {data: stringToUint8Array("my test data")}; - } else { - console.error("GenDataBlob: dataBlobLen is invalid"); - dataBlob = {data: stringToUint8Array("my test data")}; + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); } - return dataBlob; + return new Uint8Array(arr); } -// Compute an MD using promise-based APIs. -function doMdByPromise(algName) { - var md; +// Generate a digest in promise mode. +function doMdByPromise() { + let mdAlgName = "SHA256"; // Digest algorithm name. + let message = "mdTestMessgae"; // Data to be digested. + let md; + let mdOutput; try { - md = cryptoFramework.createMd(algName); + md = cryptoFramework.createMd(mdAlgName); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); + return; } - console.error("[Promise]: Md algName is: " + md.algName); - // Initial update(). - var promiseMdUpdate = md.update(GenDataBlob(12)); + console.info("[Promise]: Md algName is: " + md.algName); + // If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter. + let promiseMdUpdate = md.update({ data: stringToUint8Array(message) }); promiseMdUpdate.then(() => { - // Call update() multiple times based on service requirements. - promiseMdUpdate = md.update(GenDataBlob(12)); - return promiseMdUpdate; - }).then(mdOutput => { - var PromiseMdDigest = md.digest(); + // Call digest() to return the result. + let PromiseMdDigest = md.digest(); return PromiseMdDigest; - }).then(mdOutput => { - console.error("[Promise]: MD result: " + mdOutput.data); - var mdLen = md.getMdLength(); - console.error("[Promise]: MD len: " + mdLen); + }).then(digestOutput => { + mdOutput = digestOutput; + console.info("[Promise]: MD result: " + mdOutput.data); + let mdLen = md.getMdLength(); + console.info("[Promise]: MD len: " + mdLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); } -// Compute an MD using callback-based APIs. -function doMdByCallback(algName) { - var md; +// Generate a digest in callback mode. +function doMdByCallback() { + let mdAlgName = "SHA256"; // Digest algorithm name. + let message = "mdTestMessgae"; // Data to be digested. + let md; + let mdOutput; try { - md = cryptoFramework.createMd(algName); + md = cryptoFramework.createMd(mdAlgName); } catch (error) { console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } - console.error("[Callback]: Md algName is: " + md.algName); - // Initial update(). - md.update(GenDataBlob(12), (err,) => { + console.info("[Callback]: Md algName is: " + md.algName); + // If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter. + md.update({ data: stringToUint8Array(message) }, (err,) => { if (err) { console.error("[Callback]: err: " + err.code); } - // Call update() multiple times based on service requirements. - md.update(GenDataBlob(12), (err1,) => { + md.digest((err1, digestOutput) => { if (err1) { console.error("[Callback]: err: " + err1.code); + } else { + mdOutput = digestOutput; + console.info("[Callback]: MD result: " + mdOutput.data); + let mdLen = md.getMdLength(); + console.info("[Callback]: MD len: " + mdLen); } - md.digest((err2, mdOutput) => { - if (err2) { - console.error("[Callback]: err: " + err2.code); - } else { - console.error("[Callback]: MD result: " + mdOutput.data); - var mdLen = md.getMdLength(); - console.error("[Callback]: MD len: " + mdLen); - } - }); }); }); } ``` -The following example demonstrates how to call **update()** multiple times to update the MD. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" -async function updateData(index, obj, data) { - console.error("update " + (index + 1) + " MB data..."); - return obj.update(data); -} +### Generating a Digest by Segment + +1. Use **createMd()** to create an **Md** instance. +2. Use **update()** multiple times to pass in by segment. +3. Use **digest()** to compute a digest. +4. Obtain the digest algorithm and length of the digest generated. + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; -} - -function GenDataBlob(dataBlobLen) { - var dataBlob; - if (dataBlobLen == 12) { - dataBlob = {data: stringToUint8Array("my test data")}; - } else { - console.error("GenDataBlob: dataBlobLen is invalid"); - dataBlob = {data: stringToUint8Array("my test data")}; - } - return dataBlob; + return new Uint8Array(arr); } -function LoopMdPromise(algName, loopSize) { - var md; +// Generate a digest by segment in promise mode. +async function doLoopMdPromise() { + let mdAlgName = "SHA256"; // Digest algorithm name. + let md; + let mdOutput; try { - md = cryptoFramework.createMd(algName); + md = cryptoFramework.createMd(mdAlgName); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); return; } - console.error("[Promise]: Md algName is: " + md.algName); - var promiseMdUpdate = md.update(GenDataBlob(12)); - promiseMdUpdate.then(() => { - var PromiseMdDigest = md.digest(); - return PromiseMdDigest; - }).then(async () => { - for (var i = 0; i < loopSize; i++) { - await updateData(i, md, GenDataBlob(12)); + console.info("[Promise]: Md algName is: " + md.algName); + let messageText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // Assume that the message is of 43 bytes. + let messageArr = []; + let updateLength = 20; // For example, pass in 20 bytes in each update(). + + for (let i = 0; i <= messageText.length; i++) { + if ((i % updateLength == 0 || i == messageText.length) && messageArr.length != 0) { + let message = new Uint8Array(messageArr); + let messageBlob = { data : message }; + // Use await to process the update() in the for() loop. + try { + await md.update (messageBlob); // Call update() to process data by segment. + } catch (error) { + console.error("await update error code: " + error.code + ", message is: " + error.message); + return; + } + messageArr = []; } - var PromiseMdDigest = md.digest(); - return PromiseMdDigest; - }).then(mdOutput => { - console.error("[Promise]: MD result: " + mdOutput.data); - var mdLen = md.getMdLength(); - console.error("[Promise]: MD len: " + mdLen); + // Pad messageArr based on the segment length. + if (i < messageText.length) { + messageArr.push(messageText.charCodeAt(i)); + } + } + let PromiseMdDigest = md.digest(); + PromiseMdDigest.then(digestOutput => { + mdOutput = digestOutput; + console.info("[Promise]: MD result: " + mdOutput.data); + let mdLen = md.getMdLength(); + console.info("[Promise]: MD len: " + mdLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); } ``` -## Performing Key Agreement - -**When to Use** - -Key agreement allows two parties to establish a shared secret over an insecure channel. - -**Available APIs** - -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). - -|Instance|API|Description| -|---|---|---| -|cryptoFramework|createKeyAgreement(algName : string) : KeyAgreement|Creates a **KeyAgreement** instance.| -|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\) : void|Generates a shared secret. This API uses an asynchronous callback to return the result.| -|KeyAgreement|generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\|Generates a shared secret. This API uses a promise to return the result.| - -**How to Develop** +## HMAC -1. Use **createKeyAgreement()** to create a **KeyAgreement** object for subsequent key agreement operations. -2. Use **generateSecret()** provided by **KeyAgreement** to pass in the peer ECC public key object and the ECC private key object generated locally. +### When to Use -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -let globalSelfPriKey; -let globalPeerPubKey; - -function ecdhPromise() { - let peerPubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,83,96,142,9,86,214,126,106,247,233,92,125,4,128,138,105,246,162,215,71,81,58,202,121,26,105,211,55,130,45,236,143,55,16,248,75,167,160,167,106,2,152,243,44,68,66,0,167,99,92,235,215,159,239,28,106,124,171,34,145,124,174,57,92]); - let peerPubKeyBlob = { data: peerPubKeyArray }; - let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); - let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256"); - eccGenerator.convertKey(peerPubKeyBlob, null).then((peerKeyPair) => { - globalPeerPubKey = peerKeyPair.pubKey; - return eccGenerator.generateKeyPair(); - }).then((keyPair) => { - globalSelfPriKey = keyPair.priKey; - return eccKeyAgreement.generateSecret(globalSelfPriKey, globalPeerPubKey); - }).then((secret) => { - console.info("ecdh promise output is " + secret.data); - }).catch((error) => { - console.error("ecdh error."); - }); -} - -function ecdhCallback() { - let peerPubKeyArray = new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0,4,83,96,142,9,86,214,126,106,247,233,92,125,4,128,138,105,246,162,215,71,81,58,202,121,26,105,211,55,130,45,236,143,55,16,248,75,167,160,167,106,2,152,243,44,68,66,0,167,99,92,235,215,159,239,28,106,124,171,34,145,124,174,57,92]); - let peerPubKeyBlob = { data: peerPubKeyArray }; - let eccGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); - let eccKeyAgreement = cryptoFramework.createKeyAgreement("ECC256"); - eccGenerator.convertKey(peerPubKeyBlob, null, function (err, peerKeyPair) { - globalPeerPubKey = peerKeyPair.pubKey; - eccGenerator.generateKeyPair(function (err, keyPair) { - globalSelfPriKey = keyPair.priKey; - eccKeyAgreement.generateSecret(globalSelfPriKey, globalPeerPubKey, function (err, secret) { - if (err) { - console.error("ecdh error."); - return; - } - console.info("ecdh callback output is " + secret.data); - }); - }); - }) -} -``` - -## Generating a MAC - -**When to Use** - -A message authentication code (MAC) can be used to verify both the integrity and authenticity of a message using a shared secret. +A hash-based message authentication code (HMAC) can be used to verify both the integrity and authenticity of a message using a shared secret. Typical MAC operations involve the following: @@ -1349,104 +1846,100 @@ Typical MAC operations involve the following: 2. Initialize the **Mac** instance, add one or more segments of data for generating a MAC, and generate a MAC. 3. Obtain the algorithm and length of a MAC. -**Available APIs** +### Available APIs For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). | Instance | API | Description | | --------------- | ------------------------------------------------------------ | --------------------------------------------------- | | cryptoFramework | function createMac(algName : string) : Mac; | Creates a **Mac** instance. | -| Mac | init(key : SymKey, callback : AsyncCallback\) : void; | Initializes the MAC operation. This API uses an asynchronous callback to return the result.| -| Mac | init(key : SymKey) : Promise\; | Initializes the MAC operation. This API uses a promise to return the result. | +| Mac | init(key : SymKey, callback : AsyncCallback\) : void; | Initializes the **Mac** instance. This API uses an asynchronous callback to return the result. | +| Mac | init(key : SymKey) : Promise\; | Initializes the **Mac** instance. This API uses a promise to return the result. | | Mac | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for the MAC operation. This API uses an asynchronous callback to return the result. | | Mac | update(input : DataBlob) : Promise\; | Updates the data for the MAC operation. This API uses a promise to return the result. | -| Mac | doFinal(callback : AsyncCallback\) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. | +| Mac | doFinal(callback : AsyncCallback\) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. | | Mac | doFinal() : Promise\; | Finalizes the MAC operation to generate a MAC. This API uses a promise to return the result. | | Mac | getMacLength() : number; | Obtains the length of the MAC based on the specified algorithm. | | Mac | readonly algName : string; | Obtains the digest algorithm. | -**How to Develop** +### Generating an HMAC -1. Call **createMac()** to create a **Mac** instance. -2. Call **init()** to initialize the **Mac** instance with the symmetric key passed in. -3. Call **update()** one or more times to add the data for computing a MAC. -4. Call **doFinal()** to generate a MAC. -5. Obtain the algorithm and length of the MAC. +1. Use **createMac()** to create a **Mac** instance. +2. Use **init()** to initialize the **Mac** instance with the symmetric key passed in. +3. Use **update()** to pass in the data for computing an HMAC. +4. Use **doFinal()** to generate an HMAC. +5. Obtain the algorithm and length of the HMAC. -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -// Convert string into uint8Arr. +// Convert strings in plaintext into byte streams. function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { - arr.push(str.charCodeAt(i)); - } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; -} - -// Generate a blob. -function GenDataBlob(dataBlobLen) { - var dataBlob; - if (dataBlobLen == 12) { - dataBlob = {data: stringToUint8Array("my test data")}; - } else { - console.error("GenDataBlob: dataBlobLen is invalid"); - dataBlob = {data: stringToUint8Array("my test data")}; + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); } - return dataBlob; + return new Uint8Array(arr); } -function doHmacByPromise(algName) { - var mac; +// Generate an HMAC in promise mode. +function doHmacByPromise() { + let macAlgName = "SHA256"; // Digest algorithm name. + let message = "hmacTestMessgae"; // Data used to generate an HMAC. + let macOutput; + let mac; try { - mac = cryptoFramework.createMac(algName); + mac = cryptoFramework.createMac(macAlgName); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } - console.error("[Promise]: Mac algName is: " + mac.algName); - var KeyBlob = { + console.info("[Promise]: Mac algName is: " + mac.algName); + let KeyBlob = { + // 128-bit key data : stringToUint8Array("12345678abcdefgh") } - var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); - var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); + let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); + // Convert the binary data into a key. + let promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); + let promiseMacInit = mac.init(symKey); return promiseMacInit; }).then(() => { - // Initial update(). - var promiseMacUpdate = mac.update(GenDataBlob(12)); - return promiseMacUpdate; - }).then(() => { - // Call update() multiple times based on service requirements. - var promiseMacUpdate = mac.update(GenDataBlob(12)); + // If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter. + let promiseMacUpdate = mac.update({ data: stringToUint8Array(message) }); return promiseMacUpdate; }).then(() => { - var PromiseMacDoFinal = mac.doFinal(); + let PromiseMacDoFinal = mac.doFinal(); return PromiseMacDoFinal; - }).then(macOutput => { - console.error("[Promise]: HMAC result: " + macOutput.data); - var macLen = mac.getMacLength(); - console.error("[Promise]: MAC len: " + macLen); + }).then(output => { + macOutput = output; + console.info("[Promise]: HMAC result: " + macOutput.data); + let macLen = mac.getMacLength(); + console.info("[Promise]: MAC len: " + macLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); } -// Generate a MAC using callback-based APIs. -function doHmacByCallback(algName) { - var mac; +// Generate an HMAC in callback mode. +function doHmacByCallback() { + let macAlgName = "SHA256"; // Digest algorithm name. + let message = "hmacTestMessgae"; // Data used to generate an HMAC. + let macOutput; + let mac; try { - mac = cryptoFramework.createMac(algName); + mac = cryptoFramework.createMac(macAlgName); } catch (error) { AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message}); console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } - var KeyBlob = { + console.info("[Promise]: Mac algName is: " + mac.algName); + let KeyBlob = { + // 128-bit key data : stringToUint8Array("12345678abcdefgh") } - var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); + let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); + // Convert the binary data into a key. symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { if (err) { console.error("[Callback]: err: " + err.code); @@ -1455,127 +1948,138 @@ function doHmacByCallback(algName) { if (err1) { console.error("[Callback]: err: " + err1.code); } - // Initial update(). - mac.update(GenDataBlob(12), (err2, ) => { + // If the data volume is small, you can use update() once to pass in all data. There is no limit on the length of the input parameter. + mac.update({ data: stringToUint8Array(message) }, (err2, ) => { if (err2) { console.error("[Callback]: err: " + err2.code); } - // Call update() multiple times based on service requirements. - mac.update(GenDataBlob(12), (err3, ) => { + mac.doFinal((err3, output) => { if (err3) { console.error("[Callback]: err: " + err3.code); + } else { + macOutput = output; + console.error("[Callback]: HMAC result: " + macOutput.data); + let macLen = mac.getMacLength(); + console.error("[Callback]: MAC len: " + macLen); } - mac.doFinal((err4, macOutput) => { - if (err4) { - console.error("[Callback]: err: " + err4.code); - } else { - console.error("[Callback]: HMAC result: " + macOutput.data); - var macLen = mac.getMacLength(); - console.error("[Callback]: MAC len: " + macLen); - } - }); }); }); }); }); } ``` -The following example demonstrates how to call **update()** multiple times to update the MAC. -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" -async function updateData(index, obj, data) { - console.error("update " + (index + 1) + " MB data..."); - return obj.update(data); -} +### Generating an HMAC by Segment + +Generate an HMAC by segment. + +1. Use **createMac()** to create a **Mac** instance. +2. Use **init()** to initialize the **Mac** instance with the symmetric key passed in. +3. Call **update()** multiple times to pass in data by segment. +4. Use **doFinal()** to generate an HMAC. +5. Obtain the algorithm and length of the HMAC. + +```js +import cryptoFramework from "@ohos.security.cryptoFramework" function stringToUint8Array(str) { - var arr = []; - for (var i = 0, j = str.length; i < j; ++i) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } - var tmpUint8Array = new Uint8Array(arr); - return tmpUint8Array; -} - -function GenDataBlob(dataBlobLen) { - var dataBlob; - if (dataBlobLen == 12) { - dataBlob = {data: stringToUint8Array("my test data")}; - } else { - console.error("GenDataBlob: dataBlobLen is invalid"); - dataBlob = {data: stringToUint8Array("my test data")}; - } - return dataBlob; + return new Uint8Array(arr); } -function LoopHmacPromise(algName, loopSize) { - var mac; +function doLoopHmacPromise() { + let macAlgName = "SHA256"; // Digest algorithm name. + let macOutput; + let mac; try { - mac = cryptoFramework.createMac(algName); + mac = cryptoFramework.createMac(macAlgName); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); return; } - console.error("[Promise]: Mac algName is: " + mac.algName); - var KeyBlob = { + console.info("[Promise]: Mac algName is: " + mac.algName); + let KeyBlob = { + // 128-bit key data : stringToUint8Array("12345678abcdefgh") } - var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); - var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); + let messageText = "aaaaa.....bbbbb.....ccccc.....ddddd.....eee"; // Assume that the message is of 43 bytes. + let updateLength = 20; // For example, pass in 20 bytes in each update(). + let symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); + // Convert the binary data into a key. + let promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); promiseConvertKey.then(symKey => { - var promiseMacInit = mac.init(symKey); + let promiseMacInit = mac.init(symKey); return promiseMacInit; }).then(async () => { - for (var i = 0; i < loopSize; i++) { - await updateData(i, mac, GenDataBlob(12)); + let promiseMacUpdate; + let messageArr = []; + for (let i = 0; i <= messageText.length; i++) { + if ((i % updateLength == 0 || i == messageText.length) && messageArr.length != 0) { + let message = new Uint8Array(messageArr); + let messageBlob = { data : message }; + // Use await to process the update() in the for() loop. + try { + promiseMacUpdate = await mac.update(messageBlob); // Invoke update() multiple times. + } catch (error) { + console.error("await update error code: " + error.code + ", message is: " + error.message); + return; + } + messageArr = []; + } + // Pad messageArr based on the segment length. + if (i < messageText.length) { + messageArr.push(messageText.charCodeAt(i)); + } } - var promiseMacUpdate = mac.update(GenDataBlob(12)); return promiseMacUpdate; }).then(() => { - var PromiseMacDoFinal = mac.doFinal(); + let PromiseMacDoFinal = mac.doFinal(); return PromiseMacDoFinal; - }).then(macOutput => { - console.error("[Promise]: HMAC result: " + macOutput.data); - var macLen = mac.getMacLength(); - console.error("[Promise]: MAC len: " + macLen); + }).then(output => { + macOutput = output; + console.log("[Promise]: HMAC result: " + macOutput.data); + let macLen = mac.getMacLength(); + console.log("[Promise]: MAC len: " + macLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); } ``` +## Random Number -## Generating a Random Number - -**When to Use** +### When to Use Typical random number operations involve the following: -- Generate a random number. -- Set a seed based on the random number generated. +1. Create a **Random** instance and specify the length (in bytes) of the random number to generate a secure random number of the specified length (ranging from **1** to **INT_MAX**). +2. Set a seed based on the random number generated. -**Available APIs** +### Available APIs -For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). +For more information about the APIs, see [Crypto Framework](../reference/apis/js-apis-cryptoFramework.md). -| Instance | API | Description | -| --------------- | ------------------------------------------------------------ | ---------------------------------------------- | -| cryptoFramework | function createRandom() : Random; | Creates a **Random** instance. | -| Random | generateRandom(len : number, callback: AsyncCallback\) : void; | Generates a random number. This API uses an asynchronous callback to return the result. | -| Random | generateRandom(len : number) : Promise\; | Generates a random number. This API uses a promise to return the result. | -| Random | setSeed(seed : DataBlob) : void; | Sets a seed. | +| Instance | API | Description | +| --------------- | ------------------------------------------------------------ | ------------------------------------------ | +| cryptoFramework | function createRandom() : Random; | Creates a **Random** instance. | +| Random | generateRandom(len : number, callback: AsyncCallback\) : void; | Generates a random number. This API uses an asynchronous callback to return the result.| +| Random | generateRandom(len : number) : Promise\; | Generates a random number. This API uses a promise to return the result. | +| Random | generateRandomSync(len: number): DataBlob; | Generates a random number of the specified length synchronously. | +| Random | setSeed(seed : DataBlob) : void; | Sets a seed. | -**How to Develop** +### How to Develop -1. Call **createRandom()** to create a **Random** instance. -2. Call **generateRandom()** to generate a random number of the given length. -3. Call **setSeed()** to set a seed. +1. Use **createRandom()** to create a **Random** instance. +2. Use **generateRandom()** to generate a random number of the given length. +3. Use **setSeed()** to set a seed. -```javascript +```js import cryptoFramework from "@ohos.security.cryptoFramework" -// Generate a random number and set a seed using promise-based APIs. +// Generate a random number in promise mode. function doRandByPromise(len) { var rand; try { @@ -1596,7 +2100,7 @@ function doRandByPromise(len) { }); } -// Generate a random number and set a seed using callback-based APIs. +// Generate a random number in callback mode. function doRandByCallback(len) { var rand; try { @@ -1617,4 +2121,25 @@ function doRandByCallback(len) { } }); } + +// Generate a random number synchronously. +function doRandBySync(len) { + var rand; + try { + rand = cryptoFramework.createRandom(); + } catch (error) { + console.error("[Sync]: error code: " + error.code + ", message is: " + error.message); + } + + try { + let randData = rand.generateRandomSync(len); + if (randData != null) { + console.info("[Sync]: rand result: " + randData.data); + } else { + console.error("[Sync]: get rand result fail!"); + } + } catch (error) { + console.error("[Sync]: error: " + error.message); + } +} ``` diff --git a/en/application-dev/security/cryptoFramework-overview.md b/en/application-dev/security/cryptoFramework-overview.md index 72bbb1148908d177498d54cfc9585c12b3b1d73f..dc44626d8429376093bd476e7e43d7364a8677bf 100644 --- a/en/application-dev/security/cryptoFramework-overview.md +++ b/en/application-dev/security/cryptoFramework-overview.md @@ -1,175 +1,244 @@ # Crypto Framework Overview -The cryptographic (crypto for shot) framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, signing and signature verification, and operations of the message authentication code (MAC), hashes, and secure random numbers. You can use the APIs provided by this framework to implement cipher development quickly. +The Cryptographic (Crypto for shot) Framework shields the implementation differences of third-party cryptographic algorithm libraries and implements encryption and decryption, digital signature and signature verification, message authentication code (MAC) generation, hashes, and generation of secure random numbers. You can use the APIs provided by this framework to implement cipher development quickly. > **NOTE** > -> The crypto framework provides cryptographic operations on keys, but not key management. It is used when the application keeps the key securely (for example, temporary session keys are used only in the memory or the application implements secure key storage). If the system is required to provide key management (such as key storage), use the [HUKS](huks-overview.md). +> The Crypto Framework provides cryptographic operations, but not key management. It can be used when temporary session keys are used only in the memory or the applications implement secure key storage. If the system is required to provide key management (such as key storage), use the [HUKS](huks-overview.md). ## Working Principles -The crypto framework provides components in the following layers: -- Interface layer: provides unified JS interface externally. +The Crypto Framework provides components in the following layers: + +- Interface layer: provides unified JavaScript interfaces externally. - Plug-in layer: implements third-party algorithm libraries. -- Framework layer: loads plug-ins at the plug-in layer to adapt to third-party algorithm libraries and shield implementation differences between these libraries. +- Framework layer: flexibly loads plug-ins at the plug-in layer to adapt to third-party algorithm libraries and shield differences between these libraries. ## Basic Concepts -**Symmetric Key** + +### Symmetric Key A symmetric key is a key used both to encrypt and decrypt data. In symmetric encryption, the sender converts information in plaintext into ciphertext using a key and certain algorithm for security purposes. The receiver converts the ciphertext into plaintext using the same key and algorithm. -- AES +- **AES key** - Advanced Encryption Standard (AES) is the most common symmetric encryption algorithm. AES is a block cipher. A block cipher divides plaintext into fixed-length groups of bits, called blocks. A block is encrypted each time until the entire plaintext is encrypted. The block size in AES is 128 bits. That is, each block contains 16 bytes (8 bits/byte). The key length can be 128 bits, 192 bits, or 256 bits. -- 3DES - - Triple Data Encryption Standard (3DES), also called 3DESede or Triple DES, applies the DES cipher three times to each data block. It uses three 64-bit keys to encrypt a data block three times. Compared with DES, 3DES provides higher security due to longer key length, but its processing speed is lower. The AES is faster and more secure than 3DES. + Advanced Encryption Standard (AES) is the most common symmetric encryption algorithm. AES is a block cipher, which divides plaintext into fixed-length groups of bits, called blocks. A block is encrypted each time until the entire plaintext is encrypted. The block size in AES is 128 bits. That is, each block contains 16 bytes (8 bits/byte). The AES key length can be 128 bits, 192 bits, or 256 bits. -**Asymmetric Key** +- **3DES key** -In the asymmetric cryptography, a private and public key pair is required. The private key is used to encrypt the plaintext, and the public key is used to decrypt the ciphertext. The public key is public and open to anyone in the system, while the private key is private. For signing and signature verification, the private key is used to sign the plaintext, and the public key is used to verify the signature data. + Triple Data Encryption Standard (3DES), also called 3DESede or Triple DES, applies the DES cipher three times to each data block. It uses three 64-bit keys to encrypt a data block three times. Compared with DES, 3DES provides higher security due to longer key length, but lower processing speed. AES is faster and more secure than 3DES. -- RSA key +### Asymmetric Key - The security of RSA relies on the factoring problem, that is, the difficulty of factoring the product of two large prime numbers. The keys for the RSA algorithm are generated as follows: +In the asymmetric cryptography, a private and public key pair is required. The private key is used to encrypt the plaintext, and the public key is used to decrypt the ciphertext. The public key is public and open to anyone in the system, while the private key is private. For digital signature and signature verification, the private key is used to sign the plaintext, and the public key is used to verify the signature data. - 1. Generate two large prime numbers **p** and **q**. - - 2. Compute **n** = **p** x **q**. - - **n** is used as the modulus for both the public and private keys, and is released as part of the public key. - - 3. Choose an integer **e** such that 1 < **e** < (**p** - 1) x (**q** - 1), that is, **e** and (**p** - 1) x (**q** - 1) are coprime. - - 4. Compute **d**. **e** x **d** - 1 is a multiple of (**p** - 1) and (**q** - 1). - - The public key consists of the modulus **n** and the public exponent **e**. The private key consists of **n** and the private exponent **d**. - - In addition to the default RSA key generation from two primes, the crypto framework provides key generation from multiple primes. You can set the **primes** parameter (PRIMES_2, PRIMES_3, PRIMES_4, PRIMES_5) to specify the number of primes during key generation. The keys generated from multiple primes help reduce the computation workload in decryption and signing (Chinese remainder theorem). However, such keys are weak. The algorithm library defines specifications based on the rules for using OpenSSL prime numbers. For details, see [**Constraints**](#constraints). - -- ECC key - - Elliptic-Curve Cryptography (ECC) is a public-key encryption based on the algebraic structure of elliptic curve over finite fields. The crypto framework provides a variety of ECC key generation capabilities. +- **RSA key** + + Rivest-Shamir-Adleman (RSA) is an asymmetric encryption algorithm widely used for secure data transmission. The security of RSA depends on the practical difficulty of factoring the product of two large prime numbers. + + The RSA key parameters include the following integers: + + **n**: modulus, which is a public parameter of the private key and public key. + + **sk**: private exponent, which is often written as **d** in the formula. + + **pk**: public exponent, which is often written as **e** in the formula. + +- **ECC key** + + Elliptic-curve cryptography (ECC) is a public-key encryption algorithm based on elliptic curve mathematics. It security is based on the assumption that it is infeasible to find the discrete logarithm of a random elliptic curve element with respect to a publicly known base point. The Crypto Framework provides capabilities for generating a variety of ECC keys. + + The ECC algorithm can be regarded as an operation of numbers defined in a special set. Currently, the Crypto Framework supports elliptic curves in **Fp** fields, where **p** is prime. The **Fp** fields are also called the prime fields. + + The ECC key parameters in the **Fp** fields include the following: + + **p**: prime number used to determine **Fp**. + + **a**, **b**: determine the elliptic curve equation. -**Encryption and Decryption** + **g**: base point of the elliptic curve, which can be represented as **gx** or **gy**. -- Symmetric AES encryption and decryption + **n**: order of the base point **g**. + + **h**: cofactor. + + **sk**: private key, which is a random integer less than **n**. + + **pk**: public key, which is a point on the elliptic curve. **pk** = **sk** x **g**. + +- **DSA key** + + Digital Signature Algorithm (DSA) is a public-key algorithm based on the modular exponentiation and discrete logarithm problem. It is used for digital signatures and signature verification, but not for encryption and decryption. The Crypto Framework provides the capability of generating DSA keys of different lengths. + + The DSA key parameters include the following: + + **p**: a prime modulus, whose length is an integer multiple of 64. + + **q**: prime factor of p – 1. The length varies depending on the length of **p**. + + **g**: g = (h ^ ((p - 1) / q)) mod p, where **h** is any integer that meets 1 < h < p -1. + + **sk**: private key, which is a randomly generated integer and complies with 0 < sk < q. + + **pk**: public key. pk = (g ^ sk) mod p + +### Encryption and Decryption + +- **Symmetric AES encryption and decryption** The algorithm library provides the following cipher modes of operation for AES: ECB, CBC, OFB, CFB, CTR, GCM, and CCM. AES is a block cipher, with a fixed block size of 128 bits. In actual applications, the last block of plaintext may be less than 128 bits and needs to be padded. The padding options are as follows: - - **NoPadding**: no padding. - - **PKCS5**: pads a block cipher with a block size of 8 bytes - - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. + - **NoPadding**: no padding. + - **PKCS5**: pads a block cipher with a block size of 8 bytes. + - **PKCS7**: pads any block size from 1 to 255 bytes. The PKCS #7 padding scheme is the same as that of PKCS #5. - > **NOTE**
In ECB and CBC, the plaintext must be padded if its length is not an integer multiple of 128 bits. Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 16 bytes in AES encryption. - -- **Symmetric 3DES Encryption and Decryption** + > **NOTE** + > + > In ECB and CBC modes, the plaintext must be padded if its length is not an integer multiple of 128 bits.
+ > Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 16 bytes in AES encryption. + +- **Symmetric 3DES encryption and decryption** 3DES encryption and decryption apply the DES cipher three times to each data block to obtain the ciphertext or plaintext. The algorithm library provides the following cipher modes of operation for 3DES encryption and decryption: ECB, CBC, OFB, and CFB. DES is a block cipher, with a fixed block size of 64 bits. In actual applications, the last block of plaintext may be less than 64 bits and needs to be padded. The padding options are as follows: - - **NoPadding**: no padding. - - **PKCS5**: pads a block cipher with a block size of 8 bytes - - **PKCS7**: The PKCS #7 padding scheme is the same as that of PKCS #5 padding except that PKCS #5 padding is defined for 8-byte block sizes, while PKCS #5 padding works for any block size from 1 to 255 bytes. - - > **NOTE**
In ECB and CBC, the plaintext must be padded if its length is not an integer multiple of 64 bits.
Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 8 bytes in 3DES encryption. - -- **Asymmetric RSA Encryption and Decryption** - - After the RSA public key (n, e) and private key (n, d) are held, the RSA encryption process is as follows: - - Ciphertext = Plaintext ^ **e** mod **n** - - The decryption process is as follows: - - Plaintext = Ciphertext ^ **d** mod **n** - - The algorithm library provides the following modes of operation for RSA encryption and decryption: **PKCS1**, **PKCS1_ OAEP**, and **NoPadding**. RSA is a block cipher, with fixed-length blocks. In actual applications, diverse padding modes are used. The padding options are as follows: - - - **NoPadding**: No padding is required. The length of the input or output data must be the same as that of the RSA key modulus. - - **PKCS1**: PKCS #1 v1.5 is the default padding mode for RSA encryption and decryption. The length of the input data must be less than or equal to the RSA key modulus minus 11, and the length of the output data must be the same as that of the RSA key modulus. - - **PKCS1_OAEP**: The RSA_PKCS1_OAEP_PADDING is a new padding mode provided by PKCS #1. In this mode, two digests (**md** and **mgf1_md**) must be set. The length of the input data must be less than RSA key modulus length minus the **md** length, **mgf1_md** length, and two. The length of the output data must be the same as that of the RSA key modulus. - - > **NOTE** - > - > Length of the RSA key modulus = (Number of RSA bits + 7)/8 - -**Signing and Signature Verification** - -- RSA signing and signature verification - - After the RSA public key (n, e) and private key (n, d) are held, the RSA signature is generated as follows: + - **NoPadding**: no padding. + - **PKCS5**: pads a block cipher with a block size of 8 bytes. + - **PKCS7**: pads any block size from 1 to 255 bytes. The PKCS #7 padding scheme is the same as that of PKCS #5. + + > **NOTE** + > + > In ECB and CBC modes, the plaintext must be padded if its length is not an integer multiple of 64 bits. + > Since the plaintext is padded to the block size, the PKCS #5 and PKCS #7 used in the algorithm library use the block size as the padding length. That is, data is padded to 8 bytes in 3DES encryption. + +- **Asymmetric RSA encryption and decryption** + + RSA is a block cipher, with fixed-length blocks. In actual applications, diverse padding modes are used. Currently, the Crypto Framework provides the following padding modes: + - **NoPadding**: no padding. The length of the input or output data must be the same as that of the RSA key modulus. - Signature = Message ^ **d** mod **n** + - **PKCS1**: RSAES-PKCS1-V1_5 mode in RFC3447 (corresponding to RSA_PKCS1_PADDING in OpenSSL). The RSA converts the source data D into an encryption block (EB). In encryption, the length of the input data must be less than or equal to the RSA key modulus minus 11. The length of the output data is the same as that of the RSA key modulus. - The signature verification process is as follows: + - **PKCS1_OAEP**: RSAES-OAEP mode in RFC 3447 (corresponding to RSA_PKCS1_OAEP_PADDING in OpenSSL). It is a new padding mode developed by PKCS#1. In this mode, two digests (**md** and **mgf1_md**) need to be set. During encryption, the length of the input data must meet the following requirements: - Message = Signature ^ **d** mod **n** + Input data length < RSA key modulus – **md** length (bytes) – **mgf1_md** length (bytes) – 2 - The sender sends the message and the signature signed by the private key. The receiver decrypts the signature using the public key to verify the signature. Generally, the message sent is longer than the RSA key modulus. Therefore, the crypto framework provides two padding modes to extract the hash value of the message digest before signing the message. The crypto framework provides the following padding modes for signing and signature verification: + The length of the output data is the same as that of the RSA key modulus. In this mode, you can also set the **pSource** byte stream to define the encoding input **P** filled by OAEP and obtain the parameters related to PKCS1_OAEP. - - **PKCS1**: PKCS #1 v1.5 is the default padding mode for RSA encryption and decryption. When this mode is used, the digest (**md**) must be set. - - **PSS**: The PSS mode is a padding algorithm based on the RSA algorithm. When it is used, the digest (**md**) and mask function (**mgf1_md**) are required. + The **PKCS1_OAEP** parameters include the following: + **md**: message digest algorithm.
+ **mgf**: mask generation algorithm. Currently, only MGF1 is supported.
+ **mgf1_md**: mgf1 digest algorithm.
+ **pSource**: byte stream, which is the source for encoding input P in OAEP padding. -- ECDSA + > **NOTE** + > + > RSA key modulus = (RSA bits + 7)/8 - The Elliptic Curve Digital Signature Algorithm (ECDSA) is a Digital Signature Algorithm (DSA) that uses the ECC. Compared with the ordinary Discrete Logarithm Problem (DLP) and Integer Factorization Problem (IFP), the ECC provides a higher unit bit strength than other public-key cryptographic systems. The crypto framework provides the ECDSA that combines multiple elliptic curve and digest algorithms. +### Signing and Signature Verification -**Key Agreement** +- **RSA signing and signature verification** -- **ECDH** + The Crypto Framework provides the following padding modes for RSA signing and signature verification: + - **PKCS1**: RSASSA-PKCS1-V1_5 mode in RFC3447 (corresponding to RSA_PKCS1_PADDING in OpenSSL). When this mode is used for signing and signature verification, the digest (**md**) must be set, the digest algorithm output length (bytes) must be less than the RSA key modulus. + - **PSS**: RSASSA-PSS mode in RFC 3447 (corresponding to RSA_PKCS1_PSS_PADDING in OpenSSL). In this mode, two digests (**md** and **mgf1_md**) must be set, and the total length (bytes) of **md** and **mgf1_md** must be less than the RSA key modulus. In this mode, the salt length (**saltLen**, in bytes) can also be set, and PSS-related parameters can be obtained.
+ The PSS parameters include the following:
+ **md**: message digest algorithm.
+ **mgf**: mask generation algorithm. Currently, only MGF1 is supported.
+ **mgf1_md**: digest algorithm used in the MGF1 algorithm.
+ **saltLen**: salt length, in bytes.
+ **trailer_field**: integer used for encoding. The value must be **1**. - Elliptic Curve Diffie-Hellman (ECDH) allows two parties to establish a shared secret over an insecure channel. The crypto framework provides a variety of ECDH capabilities based on the open-source algorithm library. + > **NOTE** + > + > RSA key modulus = (RSA bits + 7)/8 -**Digest** +- **ECDSA** + + The Elliptic Curve Digital Signature Algorithm (ECDSA) is a digital signature algorithm that uses the ECC. Compared with the ordinary Discrete Logarithm Problem (DLP) and Integer Factorization Problem (IFP), the ECC provides a higher unit bit strength than other public-key cryptographic systems. The Crypto Framework provides the ECDSA that combines multiple elliptic curves and digest algorithms. + +- **DSA** + + The DSA security is based on the difficulty of the DLP in integer finite field. The DSA features high compatibility and applicability. + +### Key Agreement + +**ECDH** + +Elliptic Curve Diffie-Hellman (ECDH) allows two parties to establish a shared secret over an insecure channel. The Crypto Framework provides a variety of ECDH capabilities based on the open-source algorithm library. + +### Message Digest + +The message digest (MD) algorithm allows a fixed-length digest to be generated from data of arbitrary size by using the hash algorithm. It is used for sensitive information encryption because it is infeasible to invert or reverse the computation. The MD algorithm is also referred to as a hash algorithm or a one-way hash algorithm. -The message digest algorithm allows a fixed-length digest to be generated from data of arbitrary size by using the hash algorithm. It is used for sensitive information encryption because it is infeasible to invert or reverse the computation. The MD algorithm is also referred to as a hash algorithm or a one-way hash algorithm. When the same digest algorithm is used, the generated digest (hash value) has the following features: - The same message always results in the same hash value. - The digest generated is of the fixed length no matter the length of messages. (The digest length is determined by the algorithm used). - It is almost impossible to find two different messages with the same hash value. (The probability still exists, depending on the length of the digest.) -There are three types of message digest algorithms: MD, SHA, and MAC. For details, see **HMAC**. +There are three types of message digest algorithms: MD, SHA, and MAC. For details, see section "HMAC". + MD algorithms include MD2, MD4, and MD5. + Major SHA algorithms include SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512. -**HMAC** +### HMAC -Hash-based Message Authentication Code (HMAC) is a key-based message authentication code algorithm. HMAC provides authentication using a shared secret instead of using a digital signature. The MAC generated can be used to verify the integrity and authenticity of the message. The length of the MAC generated by HMAC is fixed. Compared with MAC, HMAC introduces the shared secret, which ensures data correctness. +Hash-based Message Authentication Code (HMAC) is a key-based message authentication code algorithm. It provides authentication using a shared secret instead of using a digital signature. The MAC generated can be used to verify the integrity and authenticity of the message. The length of the MAC generated by HMAC is fixed. Compared with MAC, HMAC introduces the shared secret, which ensures data correctness. -**Random Number** +### Random Number Random numbers are mainly used to generate temporary session keys or keys in asymmetric encryption. They are generated by a hardware random number generator or software-based pseudo-random number generator. In encryption and decryption, a secure random number generator must feature randomness, unrepeatability, and unpredictability. The random numbers generated by the Cryptography Secure Random Number Generator (CSPRNG) meet the requirements of cryptography security pseudo-randomness. - Internal state
A value in the random number generator memory. The same internal state produces the same sequence of the random number. - Seed
A number used to initialize the internal state of a pseudorandom number generator. The random number generator generates a series of random sequences based on the seeds. - ## Constraints -- The crypto framework does not support concurrent operations of multiple threads. +- The Crypto Framework does not support concurrent operations of multiple threads. - Currently, the algorithm library supports only OpenSSL. +- For a key generated based on key parameters, the bigint type must be a positive number in big-endian format. +- The Crypto Framework algorithm library provides common algorithms. Some algorithms and specifications, such as MD5, are not applicable to security scenarios. You need to select the proper algorithms as required. -### Key Generation Specifications +## Key Generation Specifications -**Symmetric Key Generation Specifications** +A key can be generated based on either of the following specifications: +- String parameter: provides the specifications of the key to be generated in the form of a string. +- Key parameters: constructs a key object using the specific cryptography information. -- The following parameters are supported: +### AES Key Generation Specifications - |Symmetric Key Algorithm|Key Length (Bit)|String Parameter| - |---|---|---| - |3DES|192|3DES192| - |AES|128|AES128| - |AES|192|AES192| - |AES|256|AES256| +The AES key can be generated based on a string parameter. + +|Symmetric Key Algorithm|Key Length (Bit)|String Parameter| +|---|---|---| +|AES|128|AES128| +|AES|192|AES192| +|AES|256|AES256| + +> **NOTE** +> +> As a combination of the symmetric key algorithm and the key length, the string parameter specifies the key specifications when a symmetric key generator is created. - > **NOTE**
**String Parameter** is a combination of **Symmetric Key Algorithm** and **Key Length**. It specifies the key specifications when a symmetric key generator is created. +### 3DES Key Generation Specifications -**Asymmetric Key Generation Specifications** -- **RSA key generation** +The 3DES key can be generated based on a string parameter. - The following parameters are supported: +|Symmetric Key Algorithm|Key Length (Bit)|String Parameter| +|---|---|---| +|3DES|192|3DES192| - |Asymmetric Key Type|Number of Primes|String Parameter| +> **NOTE** +> +> As a combination of the symmetric key algorithm and the key length, the string parameter specifies the key specifications when a symmetric key generator is created. + +### RSA Key Generation Specifications + + > **NOTE** + > + > The RSA keys can be generated based on key parameters from API version 10. + +- The RSA key can be generated based on a string parameter. + + |RSA Key Type|Number of Primes|String Parameter| |---|---|---| |RSA512|2|RSA512\|PRIMES_2| |RSA768|2|RSA768\|PRIMES_2| @@ -187,48 +256,154 @@ Random numbers are mainly used to generate temporary session keys or keys in asy |RSA8192|4|RSA8192\|PRIMES_4| |RSA8192|5|RSA8192\|PRIMES_5| - > **NOTE**
When an RSA asymmetric key is generated, the default prime number is 2, and **PRIMES_2** is optional. + > **NOTE** + > + > As a combination of the RSA key type and the number of primes, the string parameter specifies the key specifications when an asymmetric key generator is created. + > + > The default number of primes for generating the RSA asymmetric key is 2, and **PRIMES_2** can be omitted. -- **ECC key generation** +- The RSA key can also be generated based on key parameters. The following table lists the types of key parameters and cryptography specifications of each key parameter. - The following parameters are supported: + | |Common Parameter|Public Key Parameter|Private Key Parameter|Public/Private Key Pair Parameter| + |---|---------|---|---|---| + |n |× |√ |× |√ | + |pk| |√ | |√ | + |sk| | |× |√ | - |Asymmetric Key Algorithm|Key Length| - |---|---| - |ECC|ECC224| - |ECC|ECC256| - |ECC|ECC384| - |ECC|ECC521| + > **NOTE** + > + > The key parameters are used to specify the key specifications when an asymmetric key generator is created. + > + The preceding table describes the public and private key parameters supported by the Crypto Framework algorithm library for generating RSA keys.
**√** indicates that properties needs to be specified to construct the key parameter.
x indicates that the Crypto Framework currently does not support key generation based on this parameter. + + > **CAUTION** + > + > - RSA does not support random key generation by specifying the public parameter (**n**). + > + > - RSA does not support generation of the private key by specifying private key parameters (**n**, **sk**). + +### ECC Key Generation Specifications + + > **NOTE** + > + > The ECC key can be generated based on key parameters from API version 10. + +- The ECC key can be generated based on a string parameter. + + |Asymmetric Key Algorithm|Key Length (Bit)|Curve Name|String Parameter| + |---|---|---|---| + |ECC|224|NID_secp224r1|ECC224| + |ECC|256|NID_X9_62_prime256v1|ECC256| + |ECC|384|NID_secp384r1|ECC384| + |ECC|521|NID_secp521r1|ECC521| + + > **NOTE** + > + > As a combination of the asymmetric key algorithm and the key Length, the string parameter specifies the key specifications when an asymmetric key generator is created. + > + > Currently, only ECC Fp curves are supported. + +- The ECC key can also be generated based on key parameters. The following table lists the types of key parameters and cryptography specifications of each key parameter. + | |Common Parameter|Public Key Parameter|Private Key Parameter|Public/Private Key Pair Parameter| + |---|---|---|---|---| + |fieldType| √| √| √| √| + |p | √| √| √| √| + |a | √| √| √| √| + |b | √| √| √| √| + |g | √| √| √| √| + |n | √| √| √| √| + |h | √| √| √| √| + |pk | | √| | √| + |sk | | | √| √| + + > **NOTE** + > + > The key parameters specify the key specifications when an asymmetric key generator is created. + > + > The preceding table describes the public and private key parameters supported by the Crypto Framework algorithm library for generating ECC keys. √ indicates that properties need to be specified to construct the key parameter. -### Encryption and Decryption Specifications + > **CAUTION** + > + > - Currently, the ECC supports only the **Fp** fields. Therefore, **fieldType** has a fixed value of **Fp**. **fieldType** and **p** constitute the property **field**, which currently supports only [ECFieldFp](../reference/apis/js-apis-cryptoFramework.md#ecfieldfp10). + > - **g** and **pk** are points on the ECC curve and belong to the [Point](../reference/apis/js-apis-cryptoFramework.md#point10) type. You need to specify the X and Y coordinates. -**Symmetric Encryption and Decryption** +### DSA Key Generation Specifications -- The following symmetric encryption algorithms are supported: + > **NOTE** + > + > From API version 10, the DSA algorithm is supported for key generation, signing, and signature verification. + +- The DSA key can be generated based on a string parameter. - |Algorithm|Block Cipher Mode| String Parameter | + |Asymmetric Key Algorithm|Key Length (Bit)|String Parameter| |---|---|---| - |3DES|ECB|3DES192\|ECB\|[NoPadding\|PKCS5\|PKCS7]| - |3DES|CBC|3DES192\|CBC\|[NoPadding\|PKCS5\|PKCS7]| - |3DES|OFB|3DES192\|OFB\|[NoPadding\|PKCS5\|PKCS7]| - |3DES|CFB|3DES192\|CFB\|[NoPadding\|PKCS5\|PKCS7]| - |AES|ECB|AES[128\|192\|256]\|ECB\|[NoPadding\|PKCS5\|PKCS7]| - |AES|CBC|AES[128\|192\|256]\|CBC\|[NoPadding\|PKCS5\|PKCS7]| - |AES|CTR|AES[128\|192\|256]\|CTR\|[NoPadding\|PKCS5\|PKCS7]| - |AES|OFB|AES[128\|192\|256]\|OFB\|[NoPadding\|PKCS5\|PKCS7]| - |AES|CFB|AES[128\|192\|256]\|CFB\|[NoPadding\|PKCS5\|PKCS7]| - |AES|GCM|AES[128\|192\|256]\|GCM\|[NoPadding\|PKCS5\|PKCS7]| - |AES|CCM|AES[128\|192\|256]\|CCM\|[NoPadding\|PKCS5\|PKCS7]| + |DSA|1024|DSA1024| + |DSA|2048|DSA2048| + |DSA|3072|DSA3072| + + > **NOTE** + > + > As a combination of the asymmetric key algorithm and the key length, the string parameter specifies the key specifications when an asymmetric key generator is created. + +- The DSA key can also be generated based on key parameters. The following table lists the types of key parameters and cryptography specifications of each key parameter. + + | |Common Parameter|Public Key Parameter|Private Key Parameter|Public/Private Key Pair Parameter| + |---|---------|---|---|---| + |p |√ |√ |× |√ | + |q |√ |√ |× |√ | + |g |√ |√ |× |√ | + |pk | |√ | |√ | + |sk | | |× |√ | + + > **NOTE** + > + > The key parameters specify the key specifications when an asymmetric key generator is created. + > + > The preceding table describes the public and private key parameters supported by the Crypto Framework algorithm library for generating DSA keys. + > + > **√** indicates that properties needs to be specified to construct the key parameter.
x indicates that the Crypto Framework currently does not support key generation based on this parameter. + + > **CAUTION** + > + > - DSA does not support generation of the private key by specifying the private key parameters (**p**, **q**, **g**, **sk**). + > - When common parameters (**p**, **q**, **g**) are specified to generate a DSA key pair, the DSA key length must be at least 1024 bits. + +## Encryption and Decryption Specifications + +### Symmetric Encryption and Decryption + + > **NOTE** + > + > The APIs support specifications without the key length for symmetric encryption and decryption from API version 10. + +The following symmetric encryption algorithms are supported. +|Symmetric Encryption and Decryption Algorithm|Block Cipher Mode|String Parameter | +|---|---|---| +|3DES|ECB|3DES192\|ECB\|[NoPadding\|PKCS5\|PKCS7]| +|3DES|CBC|3DES192\|CBC\|[NoPadding\|PKCS5\|PKCS7]| +|3DES|OFB|3DES192\|OFB\|[NoPadding\|PKCS5\|PKCS7]| +|3DES|CFB|3DES192\|CFB\|[NoPadding\|PKCS5\|PKCS7]| +|AES|ECB|AES[128\|192\|256]\|ECB\|[NoPadding\|PKCS5\|PKCS7]| +|AES|CBC|AES[128\|192\|256]\|CBC\|[NoPadding\|PKCS5\|PKCS7]| +|AES|CTR|AES[128\|192\|256]\|CTR\|[NoPadding\|PKCS5\|PKCS7]| +|AES|OFB|AES[128\|192\|256]\|OFB\|[NoPadding\|PKCS5\|PKCS7]| +|AES|CFB|AES[128\|192\|256]\|CFB\|[NoPadding\|PKCS5\|PKCS7]| +|AES|GCM|AES[128\|192\|256]\|GCM\|[NoPadding\|PKCS5\|PKCS7]| +|AES|CCM|AES[128\|192\|256]\|CCM\|[NoPadding\|PKCS5\|PKCS7]| > **NOTE** -> +> > - The options included in the square brackets ([]) are mutually exclusive. -> - **String Parameter** is a combination of **Algorithm** (including the key length), **Block Cipher Mode**, and padding mode. It specifies the symmetric encryption/decryption algorithm specifications when a symmetric encryption/decryption instance is created. +> - As a combination of the algorithm (including the key length), block cipher mode, and padding mode, the string parameter specifies the symmetric encryption/decryption algorithm specifications when a symmetric encryption/decryption instance is created. -**Asymmetric RSA Encryption and Decryption** +### Asymmetric RSA Encryption and Decryption -The crypto framework provides three padding modes for RSA encryption/decryption: **NoPadding**, **PKCS1**, and **PKCS1_OAEP**. -- Parameters for **NoPadding** + > **NOTE** + > + > The APIs support specifications without the key length for asymmetric RSA encryption and decryption from API version 10. + +The Crypto Framework provides three padding modes for RSA encryption/decryption: **NoPadding**, **PKCS1**, and **PKCS1_OAEP**. +- If **NoPadding** is used, the following parameters can be specified. |Asymmetric Key Type| Padding Mode| String Parameter| |---|---|---| @@ -239,8 +414,14 @@ The crypto framework provides three padding modes for RSA encryption/decryption: |RSA3072|NoPadding|RSA3072\|NoPadding| |RSA4096|NoPadding|RSA4096\|NoPadding| |RSA8192|NoPadding|RSA8192\|NoPadding| + |RSA|NoPadding|RSA\|NoPadding| -- Parameters for **PKCS1** + > **NOTE** + > + > - As a combination of the asymmetric key type and the padding mode, the string parameter specifies the asymmetric encryption/decryption algorithm specifications when an asymmetric encryption/decryption instance is created. + > - The RSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The encryption/decryption operation varies depending on the actual key length. + +- If **PKCS1** is used, the following parameters can be specified. |Asymmetric Key Type| Padding Mode| String Parameter| |---|---|---| @@ -251,174 +432,277 @@ The crypto framework provides three padding modes for RSA encryption/decryption: |RSA3072|PKCS1|RSA3072\|PKCS1| |RSA4096|PKCS1|RSA4096\|PKCS1| |RSA8192|PKCS1|RSA8192\|PKCS1| + |RSA|PKCS1|RSA\|PKCS1| -- Parameters for **PKCS1_OAEP** > **NOTE** - > + > + > - As a combination of the asymmetric key type and the padding mode, the string parameter specifies the asymmetric encryption/decryption algorithm specifications when an asymmetric encryption/decryption instance is created. + > - The RSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The encryption/decryption operation varies depending on the actual key length. + +- If **PKCS1_OAEP** is used, the following parameters can be specified. + + | Asymmetric Key Type| Padding Mode| Digest| Mask Digest| + |---|---|---|---| + |RSA512|PKCS1_OAEP|MD5| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224] + |RSA768|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| + |RSA768|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA768|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| + |RSA1024|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| + |RSA2048|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA|PKCS1_OAEP|Digest algorithm that meets the requirements for length|MGF1_ digest algorithm that meets the requirements for length| + + > **NOTE** + > > - The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. - > - Combine the asymmetric key type, padding mode, digest, and mask digest, with a vertical bar (|) in between. For example, **RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA256**. + > - As a combination of the asymmetric key type, padding mode, digest, and mask digest with a vertical bar (|) in between, the string parameter specifies the asymmetric encryption/decryption algorithm specifications when an asymmetric encryption/decryption instance is created. For example, **RSA2048|PKCS1_OAEP|SHA256|MGF1_SHA256**. + > - The RSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The encryption/decryption operation varies depending on the actual key length. + > - The input data must meet the following requirement:
Input data length < RSA key modulus - **md** length - **mgf1_md** length - 2
For example, if the RSA key is 512 bits, SHA-512 is not supported. For details about the definition of the RSA key modulus and digest length, see "Asymmetric RSA encryption and decryption" in [Encryption and Decryption](#encryption-and-decryption). -| Asymmetric Key Type| Padding Mode| Digest| Mask Digest| -|---|---|---|---| -|RSA512|PKCS1_OAEP|MD5| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| -|RSA768|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| -|RSA768|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA768|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| -|RSA1024|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| -|RSA2048|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512 ]| -|RSA8192|PKCS1_OAEP|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PKCS1_OAEP|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - - -### Signing and Signature Verification Specifications - -**RSA Signing and Signature Verification** - -The crypto framework provides two padding modes for RSA signing and signature verification: **PKCS1** and **PSS**. -- Parameters for **PKCS1** +- If **PKCS1_OAEP** is used, you can obtain the [OAEP cipher parameter](../reference/apis/js-apis-cryptoFramework.md#cipherspecitem10) and set the encoding input P for OAEP padding. + + | OAEP Parameter|Enum Value| Get()| Set()| + |---|---|---|---| + |md|OAEP_MD_NAME_STR |√| + |mgf|OAEP_MGF_NAME_STR|√| + |mgf1_md|OAEP_MGF1_MD_STR |√| + |pSource|OAEP_MGF1_PSRC_UINT8ARR|√|√| + + > **NOTE** + > + > The preceding table presents the **Get()** and **Set()** capabilities for OAEP parameters supported by the Crypto Framework. **√** indicates that the parameter can be obtained or set. + +## Signing and Signature Verification Specifications + +### RSA Signing and Signature Verification + + > **NOTE** + > + > The APIs support specifications without the key length for RSA signing and signature verification from API version 10. + +The Crypto Framework provides two padding modes for RSA signing and signature verification: **PKCS1** and **PSS**. + +- If **PKCS1** is used, the following parameters can be specified. | Asymmetric Key Type| Padding Mode| Digest| String Parameter| |---|---|---|---| - |RSA512|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384]|RSA512\|PKCS1\| [MD5\|SHA1\|SHA224\|SHA256\|SHA384]| + |RSA512|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384]|RSA512\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384]| |RSA768|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA768\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| |RSA1024|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA1024\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| |RSA2048|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA2048\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| |RSA3072|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA3072\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| |RSA4096|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA4096\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| |RSA8192|PKCS1|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|RSA8192\|PKCS1\|[MD5\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |RSA|PKCS1|Digest algorithm that meets the requirements for length|RSA\|PKCS1\|Digest algorithm that meets the requirements for length| -- Parameters for **PSS** > **NOTE** - > + > > - The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. - > - Combine the asymmetric key type, padding mode, digest, and mask digest, with a vertical bar (|) in between. For example, **RSA2048|PSS|SHA256|MGF1_SHA256**. + > - The RSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The signing or signature verification operation varies depending on the actual key length. + > - During RSA signature verification, the output length of the digest algorithm must be less than the RSA key modulus. For example, if the RSA key is 512 bits, SHA-512 is not supported. For details, see "RSA signing and signature verification" in [Signing and Signature Verification](#signing-and-signature-verification). + +- If **PSS** is used, the following parameters can be specified. + + | Asymmetric Key Type| Padding Mode| Digest| Mask Digest| + |---|---|---|---| + |RSA512|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA512|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]|RSA512\|PSS\|SHA256\|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| + |RSA768|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA768|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| + |RSA768|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| + |RSA768|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| + |RSA1024|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA1024|PSS|SHA512| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| + |RSA2048|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA2048|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA3072|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA4096|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA8192|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| + |RSA|PSS|Digest algorithm that meets the requirements for length|MGF1_ digest algorithm that meets the requirements for length| + + > **NOTE** + > + > - The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. + > - As a combination of the asymmetric key type, padding mode, digest, and mask digest with a vertical bar (|) in between, the string parameter specifies the asymmetric signing or signature verification algorithm specifications when an asymmetric signing or signature verification instance is created. For example, **RSA2048|PSS|SHA256|MGF1_SHA256**. + > - The RSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The signing or signature verification operation varies depending on the actual key length. + > - If the PSS padding mode is used in RSA signing or signature verification, the total length (in bytes) of **md** and **mgf1_md** must be less than the RSA key modulus. For example, if the RSA key is 512 bits, **md** and **mgf1_md** cannot be SHA256 at the same time. For details about the definition of the RSA key modulus and digest length, see "RSA signing and signature verification" in [Signing and Signature Verification](#signing-and-signature-verification). -| Asymmetric Key Type| Padding Mode| Digest| Mask Digest| -|---|---|---|---| -|RSA512|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA512|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]|RSA512\|PSS\|SHA256\|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| -|RSA768|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA768|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| -|RSA768|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256]| -|RSA768|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224]| -|RSA1024|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA1024|PSS|SHA512| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384]| -|RSA2048|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA2048|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA3072|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA4096|PSS|SHA512|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|MD5|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|SHA1|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|SHA224|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|SHA256|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|SHA384|[MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| -|RSA8192|PSS|SHA512| [MGF1_MD5\|MGF1_SHA1\|MGF1_SHA224\|MGF1_SHA256\|MGF1_SHA384\|MGF1_SHA512]| - -**ECDSA Signing and Signature Verification** - -- The following ECDSA parameters are supported: - - |Asymmetric Key Algorithm|Supported Type| - |---|---| - |ECC|ECC224| - |ECC|ECC256| - |ECC|ECC384| - |ECC|ECC521| +- If the PSS mode is used, you can obtain the PSS [parameter](../reference/apis/js-apis-cryptoFramework.md#signspecitem10) for signing or signature verification, and set the salt length (**saltLen**, in bytes) for the PSS. - |Digest Algorithm|Supported Type| - |---|---| - |HASH|SHA1| - |HASH|SHA224| - |HASH|SHA256| - |HASH|SHA384| - |HASH|SHA512| + | PSS Parameter|Enum Value| Get()| Set()| + |---|---|---|---| + |md|PSS_MD_NAME_STR |√| + |mgf|PSS_MGF_NAME_STR|√| + |mgf1_md|PSS_MGF1_MD_STR |√| + |saltLen|PSS_SALT_LEN_NUM|√|√| + |trailer_field|PSS_TRAILER_FIELD_NUM|√| -### Key Agreement Specifications + > **NOTE** + > + > The preceding table presents the **Get()** and **Set()** capabilities for PSS parameters supported by the Crypto Framework. **√** indicates that the parameter can be obtained or set. -**ECDH** +### ECDSA Signing and Signature Verification + + > **NOTE** + > The APIs support specifications without the key length for ECDSA signing and signature verification from API version 10. +- The following ECDSA parameters are supported. + + |Asymmetric Key Type|Digest|String Parameter| + |---|---|---| + |ECC224|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|ECC224\|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |ECC256|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|ECC256\|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |ECC384|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|ECC384\|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |ECC521|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|ECC521\|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |ECC|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|ECC\|[SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + + > **NOTE** + > + > - The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. + > - As a combination of the asymmetric key type and digest with a vertical bar (|) in between, the string parameter specifies the asymmetric signing or signature verification algorithm specifications when an asymmetric signing or signature verification instance is created. For example, **ECC224|SHA256**. + > - The ECC key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The ECDSA signing or signature verification operation varies depending on the actual key length. + +### DSA Signing and Signature Verification + + > **NOTE** + > + > DSA signing and signature verification specifications are supported from API version 10. + +- The following DSA parameters are supported. + + |Asymmetric Key Type|Digest|String Parameter| + |---|---|---| + |DSA1024|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|DSA1024\|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |DSA2048|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|DSA2048\|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |DSA3072|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|DSA3072\|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + |DSA|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]|DSA\|[NoHash\|SHA1\|SHA224\|SHA256\|SHA384\|SHA512]| + + > **NOTE** + > + > - The options included in the square brackets ([]) are mutually exclusive. The options outside the square brackets are fixed values. + > - As a combination of the asymmetric key type and digest with a vertical bar (|) in between, the string parameter specifies the asymmetric signing or signature verification algorithm specifications when an asymmetric signing or signature verification instance is created. For example, **DSA1024|SHA256**. + > - The DSA key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The signing or signature verification operation varies depending on the actual key length. -- The following ECDH parameters are supported: +## Key Agreement Specifications - |Asymmetric Key Algorithm|Supported Type| +### ECDH + + > **NOTE** + > + > The APIs support specifications without the key length for ECDH from API version 10. + +- The following ECDH parameters are supported. + + |Asymmetric Key Algorithm|String Parameter| |---|---| |ECC|ECC224| |ECC|ECC256| |ECC|ECC384| |ECC|ECC521| + |ECC|ECC| -### MD Algorithm Specifications -- The crypto framework supports the following MD algorithm parameters: + > **NOTE** + > + > - The string parameter specifies the key agreement algorithm specifications when a key agreement instance is created. + > - The ECC key type in the last row of the preceding table does not contain the key length to ensure compatibility with the key generated based on the key parameters. The ECDH key agreement operation varies depending on the actual key length. - |Digest Algorithm|Supported Type| - |---|---| - |HASH|SHA1| - |HASH|SHA224| - |HASH|SHA256| - |HASH|SHA384| - |HASH|SHA512| - |HASH|MD5| -### HMAC Algorithm Specifications -- The crypto framework supports the following HMAC algorithm parameters: +## MD Algorithm Specifications - |Digest Algorithm|Supported Type| - |---|---| - |HASH|SHA1| - |HASH|SHA224| - |HASH|SHA256| - |HASH|SHA384| - |HASH|SHA512| +The Crypto Framework supports the following MD algorithm parameters. + +|Digest algorithm|Supported Type| +|---|---| +|HASH|SHA1| +|HASH|SHA224| +|HASH|SHA256| +|HASH|SHA384| +|HASH|SHA512| +|HASH|MD5| + +> **NOTE** +> +> **Supported Type** specifies the MD algorithm specifications when an MD instance is created. + +## HMAC Algorithm Specifications + +The Crypto Framework supports the following HMAC algorithm parameters. + +|Digest algorithm|Supported Type| +|---|---| +|HASH|SHA1| +|HASH|SHA224| +|HASH|SHA256| +|HASH|SHA384| +|HASH|SHA512| + +> **NOTE** +> +> **Supported Type** specifies the HMAC algorithm specifications when an HMAC instance is created. + +## Random Number +Currently, the Crypto Framework supports only the CTR_DRBG algorithm. + +> **NOTE** +> +> - Currently, only secure random numbers with length of 1 to **INT_MAX** bytes are supported. +> - The random number generation algorithm uses the **RAND_priv_bytes** interface of OpenSSL to generate secure random numbers. \ No newline at end of file diff --git a/en/application-dev/ui/arkts-common-components-button.md b/en/application-dev/ui/arkts-common-components-button.md index 8abc45a87a9cc0ed6d0b40eaf907c2afb5692299..3040cfbdb16865189e316aab3a513f2ead8907f5 100644 --- a/en/application-dev/ui/arkts-common-components-button.md +++ b/en/application-dev/ui/arkts-common-components-button.md @@ -54,33 +54,36 @@ Use the **type** parameter to set the button type to **Capsule**, **Circle**, or - Capsule button (default type) + Buttons of this type have rounded corners whose radius is automatically set to half of the button height. The rounded corners cannot be reset through the **borderRadius** attribute. - + ```ts Button('Disable', { type: ButtonType.Capsule, stateEffect: false }) .backgroundColor(0x317aff) .width(90) .height(40) ``` - + ![en-us_image_0000001511421208](figures/en-us_image_0000001511421208.png) - Circle button + Buttons of this type are round. The rounded corners cannot be reset through the **borderRadius** attribute. - + ```ts Button('Circle', { type: ButtonType.Circle, stateEffect: false }) .backgroundColor(0x317aff) .width(90) .height(90) ``` - + ![en-us_image_0000001511740428](figures/en-us_image_0000001511740428.png) - + - Normal button + Buttons of this type have rounded corners set to 0. The rounded corners can be reset through the **borderRadius** attribute. - + ```ts Button('Ok', { type: ButtonType.Normal, stateEffect: true }) .borderRadius(8) @@ -88,56 +91,60 @@ Use the **type** parameter to set the button type to **Capsule**, **Circle**, or .width(90) .height(40) ``` - + ![en-us_image_0000001563060641](figures/en-us_image_0000001563060641.png) ## Setting Styles -- Set the border radius: +- Set the border radius. + In general cases, you can use universal attributes to define the button styles. For example, you can use the **borderRadius** attribute to set the border radius. - + ```ts Button('circle border', { type: ButtonType.Normal }) .borderRadius(20) .height(40) ``` - + ![en-us_image_0000001511900392](figures/en-us_image_0000001511900392.png) -- The **Font** type is used to set the text style. - Add a font style for text displayed on the button. - +- Set the text style. + + Add text style attributes for the button. + ```ts Button('font style', { type: ButtonType.Normal }) .fontSize(20) .fontColor(Color.Pink) .fontWeight(800) ``` - + ![en-us_image_0000001511580828](figures/en-us_image_0000001511580828.png) -- Set the background color: - You can do so by adding the **backgroundColor** attribute. - +- Set the background color. + + Add the **backgroundColor** attribute for the button. + ```ts Button('background color').backgroundColor(0xF55A42) ``` - + ![en-us_image_0000001562940477](figures/en-us_image_0000001562940477.png) -- Assign a function to the button: +- Assign a function to the button. + In this example, the delete function is assigned to the button. - + ```ts Button({ type: ButtonType.Circle, stateEffect: true }) { Image($r('app.media.ic_public_delete_filled')).width(30).height(30) }.width(55).height(55).margin({ left: 20 }).backgroundColor(0xF55A42) ``` - + ![en-us_image_0000001511740436](figures/en-us_image_0000001511740436.png) @@ -153,9 +160,10 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true }) ``` -## Example Scenario +## Example + +- Using the button for startup -- Using the Button for Startup You can use the button for any UI element that involves the startup operation. The button triggers the predefined event based on the user's operation. For example, you can use a button in the **\** container to redirect the user to another page. ```ts @@ -194,7 +202,8 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true }) ![en-us_image_0000001562700393](figures/en-us_image_0000001562700393.png) -- Use the button for submitting forms: +- Using the button for submitting forms + On the user login/registration page, you can use a button to submit a login or registration request. ```ts @@ -217,7 +226,8 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true }) ![en-us_image_0000001562940473](figures/en-us_image_0000001562940473.png) -- Configure the button to float: +- Configuring the button to float + The button can remain floating when the user swipes on the screen. ```ts diff --git a/en/application-dev/ui/arkts-common-events-touch-screen-event.md b/en/application-dev/ui/arkts-common-events-touch-screen-event.md index 714632ca346c2c4c2af4a534ef74b87d70b9272c..8ea799215eba028933a83a571e0d45d22c113ca7 100644 --- a/en/application-dev/ui/arkts-common-events-touch-screen-event.md +++ b/en/application-dev/ui/arkts-common-events-touch-screen-event.md @@ -12,7 +12,7 @@ Touchscreen events are events triggered when a finger or stylus is placed on, mo ## Click Event -A click event is triggered when a complete press and lift action performed by using a finger or a stylus. When a click event occurs, the following callback is triggered: +A click event is triggered when a complete press and lift action is performed by using a finger or a stylus. When a click event occurs, the following callback is triggered: ```ts onClick(event: (event?: ClickEvent) => void) diff --git a/en/application-dev/ui/arkts-drawing-customization-on-canvas.md b/en/application-dev/ui/arkts-drawing-customization-on-canvas.md index 7e0e1f79da9c0f26c210a939a54586a09f083832..93b8e8f114dc32163bbf2859710b85c0e681bf2c 100644 --- a/en/application-dev/ui/arkts-drawing-customization-on-canvas.md +++ b/en/application-dev/ui/arkts-drawing-customization-on-canvas.md @@ -89,11 +89,7 @@ You can draw custom graphics on the canvas in any of the following ways: import lottie from '@ohos/lottie' ``` - For details about the APIs, see [Lottie](../reference/arkui-ts/ts-components-canvas-lottie.md). - - >**NOTE** - > - >Before using Lottie for the first time, run the **ohpm install \@ohos/lottieETS** command in the Terminal window to download Lottie. + For details about the APIs, see [Lottie](https://gitee.com/openharmony-tpc/lottieETS). ## Initializing the Canvas Component @@ -117,7 +113,7 @@ Canvas(this.context) ## Canvas Component Drawing Modes -Two modes are available for drawing with the **Canvas** component: +Two modes are available for drawing with the **Canvas** component: - After the **onReady()** callback of the **Canvas** component is invoked, use the **CanvasRenderingContext2D** and **OffscreenCanvasRenderingContext2D** objects to call related APIs for drawing. @@ -159,9 +155,8 @@ Two modes are available for drawing with the **Canvas** component: - Draw a basic shape. - -You can draw a basic shape by calling APIs such as [arc](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#arc), [ellipse](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#ellipse), and [rect](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#rect). - + You can draw a basic shape by calling APIs such as [arc](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#arc), [ellipse](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#ellipse), and [rect](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#rect). + ```ts Canvas(this.context) .width('100%') @@ -183,9 +178,9 @@ You can draw a basic shape by calling APIs such as [arc](../reference/arkui-ts/t }) ``` - + ![2023022794521(1)](figures/2023022794521(1).jpg) - + - Draw text. You can use APIs such as [fillText](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#filltext) and [strokeText](../reference/arkui-ts/ts-canvasrenderingcontext2d.md#stroketext) to draw text. @@ -345,4 +340,3 @@ You can draw a basic shape by calling APIs such as [arc](../reference/arkui-ts/t ``` ![2023032422159](figures/2023032422159.jpg) - diff --git a/en/application-dev/ui/arkts-event-overview.md b/en/application-dev/ui/arkts-event-overview.md index b12ad179de90e821c1b61226e02469a289f67d6a..621bb32a1cf96eaf90dea0bd2f1b01dd1aa1e89f 100644 --- a/en/application-dev/ui/arkts-event-overview.md +++ b/en/application-dev/ui/arkts-event-overview.md @@ -1,23 +1,23 @@ -# Event Overview +# Interaction Event Overview -Interaction events are classified into touchscreen events, keyboard and mouse events, and focus events based on trigger types. +Interaction events are classified based on trigger types into touchscreen events, keyboard and mouse events, and focus events. -- [Touchscreen event](arkts-common-events-touch-screen-event.md): single-finger or single-stroke operation performed by a finger or stylus on the touchscreen. +- [Touchscreen event](arkts-common-events-touch-screen-event.md): an event triggered by the operation performed a finger or stylus on the touchscreen. -- [Keyboard and mouse event](arkts-common-events-device-input-event.md): includes operation events of the peripheral mouse or touchpad and key events of the peripheral keyboard. - - The mouse event refers to an event responded to when an operation is performed with a peripheral mouse/touchpad. - - The key event refer to an event responded to when an operation is performed with a peripheral keyboard. +- [Keyboard and mouse event](arkts-common-events-device-input-event.md): an event triggered by an operation performed on a peripheral mouse, touchpad, or keyboard. + - The mouse event refers to an event responded to when an operation is performed with a peripheral mouse or touchpad. + - The keyboard event refera to an event responded to when an operation is performed with a peripheral keyboard. -- [Focus event](arkts-common-events-focus-event.md): controls the focusability and response events of the component in the preceding ways. +- [Focus event](arkts-common-events-focus-event.md): an event triggered when a component receives or loses focus. -The gesture event includes the gesture binding method and the bound gesture. The bound gesture may be classified into two types: a single gesture and a combined gesture, and is distinguished according to complexity of the gesture. +The gesture event includes the gesture binding method and the bound gesture – a single or combined gesture. -- [Gesture binding](arkts-gesture-events-binding.md): binds a single gesture or a combination of gestures to a component and declares the response priority of the bound gesture. +- [Gesture binding method](arkts-gesture-events-binding.md): a method that binds a single or combined gesture to a component and declares the response priority of the bound gesture. -- [Single gesture](arkts-gesture-events-single-gesture.md): basic unit of a gesture, which is a part of all complex gestures. +- [Single gesture](arkts-gesture-events-single-gesture.md): basic unit of gestures, which is a part of all complex gestures. -- [Combined gesture](arkts-gesture-events-combined-gestures.md): a combination of multiple single gestures. Multiple single gestures can be combined into a combined gesture according to a declared type and a certain rule, and the combined gesture can be used. +- [Combined gesture](arkts-gesture-events-combined-gestures.md): a combination of single gestures brought together according to a declared type and a certain rule. diff --git a/en/application-dev/web/web-debugging-with-devtools.md b/en/application-dev/web/web-debugging-with-devtools.md index 3a38a48ab12cfd740bba0d5b99cf8140d4224e4b..d5a1b57085384e5e10b50bde2c4d99dbd43367f3 100644 --- a/en/application-dev/web/web-debugging-with-devtools.md +++ b/en/application-dev/web/web-debugging-with-devtools.md @@ -28,8 +28,17 @@ To use DevTools for frontend page debugging, perform the following steps: } } ``` +2. Declare the required permission in the **module.json5** file of the application project in DevEco Studio. -2. Connect your device to a PC, and configure port mapping on the PC as follows: + ``` + "requestPermissions":[ + { + "name" : "ohos.permission.INTERNET" + } + ] + ``` + +3. Connect your device to a PC, and configure port mapping on the PC as follows: ``` // Configure port mapping. @@ -38,7 +47,7 @@ To use DevTools for frontend page debugging, perform the following steps: hdc fport ls ``` -3. Enter **chrome://inspect/\#devices** in the address box of the Chrome browser on the PC. Once the device is identified, you can get started with page debugging. The debugging effect is as follows: +4. Enter **chrome://inspect/\#devices** in the address box of the Chrome browser on the PC. Once the device is identified, you can get started with page debugging. The debugging effect is as follows: **Figure 1** Page debugging effect diff --git a/en/release-notes/changelogs/OpenHarmony_3.2.9.1/changelogs-arkui.md b/en/release-notes/changelogs/OpenHarmony_3.2.9.1/changelogs-arkui.md index 80e5645eba71f86ec75134e366d436164a961802..b962d696651520951a8ac1b8be731402fb1dafa4 100644 --- a/en/release-notes/changelogs/OpenHarmony_3.2.9.1/changelogs-arkui.md +++ b/en/release-notes/changelogs/OpenHarmony_3.2.9.1/changelogs-arkui.md @@ -2,15 +2,15 @@ ## cl.arkui.1 xcomponent API Change -The following APIs of the **xcomponent** component of the ArkUI subsystem are changed: +Changed the following APIs of the **xcomponent** component of the ArkUI subsystem: - - **getXComponentSurfaceId** and **setXComponentSurfaceSize**: The **@systemapi** tag is removed. - - **getXComponentSurfaceId**, **getXComponentContext**, and **setXComponentSurfaceSize**: The return value types are specified. + - **getXComponentSurfaceId** and **setXComponentSurfaceSize**: Removed the **@systemapi** tag. + - **getXComponentSurfaceId**, **getXComponentContext**, and **setXComponentSurfaceSize**: Specified return value types. -You need to adapt your applications based on the following information. +You need to adapt your application based on the following information. -**Change Impacts** +**Change Impact** Released JS APIs are affected. The application needs to adapt these APIs so that it can be properly compiled in the SDK environment of the new version. @@ -27,35 +27,35 @@ Startup rules for different scenarios are as follows: Adaptions to be made: - **getXComponentSurfaceId** - - OpenHarmony 3.2 Beta3 rules: + - In OpenHarmony 3.2 Beta3: - System API - No specified return value - - OpenHarmony 3.2 Beta4 rules: + - In OpenHarmony 3.2 Beta4: - Public API - Return value type specified as string - You need to process the return value as a string. - **setXComponentSurfaceSize** - - OpenHarmony 3.2 Beta3 rules: + - In OpenHarmony 3.2 Beta3: - System API - No specified return value - - OpenHarmony 3.2 Beta4 rules: + - In OpenHarmony 3.2 Beta4: - Public API - Return value type specified as void - You need to process the return value as a void. - **getXComponentContext** - - OpenHarmony 3.2 Beta3 rules: + - In OpenHarmony 3.2 Beta3: - No specified return value - - OpenHarmony 3.2 Beta4 rules: + - In OpenHarmony 3.2 Beta4: - Return value type specified as object - You need to process the return value as an object. - + ## cl.arkui.2 Change of Styles of Popup Component and APIs The styles of the **alertDialog**, **actionSheet**, and **customDialog** components, as well as the **prompt** and **promptAction** APIs were changed. Specifically speaking: The popup background blurring effect is added to **promptAction.showDialog**, **promptAction.showActionMenu**, **alertDialog**, **actionSheet**, and **customDialog**. -**Change Impacts** +**Change Impact** The popup background blurring effect is set by default. @@ -70,9 +70,10 @@ No adaptation is required. ## cl.arkui.3 Supplementation of the Initialization Mode and Restriction Verification Scenarios of Custom Components' Member Variables -For details, see [Restrictions and Extensions](../../../application-dev/quick-start/arkts-restrictions-and-extensions.md). +Added verification for scenarios previously left out concerning initialization of custom components' member variables. + -**Change Impacts** +**Change Impact** If custom components' member variables are initialized or assigned with values not according to the document specifications, an error will be reported during compilation. @@ -86,10 +87,10 @@ Make modification according to specifications in the above document. ## cl.arkui.4 Supplementation of Verification Scenarios of Value Assignment Restrictions on Member Variables of Custom Parent Components and Child Components -For details, see [Restrictions and Extensions](../../../application-dev/quick-start/arkts-restrictions-and-extensions.md). +Added verification for scenarios previously left out concerning value assignment of member variables of custom parent components and child components. -**Change Impacts** +**Change Impact** If member variables of the parent component or child component are initialized not according to the document specifications, an error will be reported during compilation. @@ -101,14 +102,13 @@ N/A Make modification according to specifications in the above document, using other decorators or normal member variables for value assignment. -## cl.arkui.5 Supplementation of Verification for a Single Subcomponent - -Verification for a single subcomponent is enabled for the following components: **Button**, **FlowItem**, **GridItem**, **GridCol**, **ListItem**, **Navigator**, **Refresh**, **RichText**, **ScrollBar**, **StepperItem**, and **TabContent**. +## cl.arkui.5 Supplementation of Verification for a Single Child Component +Added verification for a single child component for the following components: **Button**, **FlowItem**, **GridItem**, **GridCol**, **ListItem**, **Navigator**, **Refresh**, **RichText**, **ScrollBar**, **StepperItem**, and **TabContent**. -**Change Impacts** +**Change Impact** -If one of the preceding components contains more than one subcomponent, an error will be reported during compilation. +If one of the preceding components contains more than one child component, an error will be reported during compilation. **Key API/Component Changes** @@ -123,4 +123,4 @@ RichText('RichText') { **Adaptation Guide** -Make modification based on the error message. Make sure that the specified component contains only one subcomponent. +Make modification based on the error message. Make sure that the specified component contains only one child component. diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.7.3/changelog-web.md b/en/release-notes/changelogs/OpenHarmony_4.0.7.3/changelog-web.md new file mode 100644 index 0000000000000000000000000000000000000000..f3ee5e7e3ddd0e4492ea0d5133a9bcb5d0c49066 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.7.3/changelog-web.md @@ -0,0 +1,126 @@ +# Web Subsystem Changelog + +Compared with earlier versions, OpenHarmony 4.0.7.3 has the following API changes in its web subsystem: + +## cl.web.1 New Input Parameter Type of the setResponseData API + +Added the input parameter type **Resource** for the **setResponseData** API. + +**Change Impact** + +In the scenario where a HAP file is not decompressed, the file path in the HAP does not exist. Under this scenario, to access resources in the HAP file, you must use the input parameter **data:Resource** instead of **data:number**. + + +**Key API/Component Changes** + +- Involved APIs: + + setResponseData + +- Before change: + + ```ts + setResponseData(data: string | number) + ``` + +- After change: + + ```ts + setResponseData(data: string | number | Resource) + ``` + +**Adaptation Guide** + +When a HAP file is decompressed, open the hold the FD of the target resource file, and then transfer the resource response data to the kernel through **setResponseData(data:number)**. + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' +import fileio from '@ohos.fileio'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + responseweb: WebResourceResponse = new WebResourceResponse() + heads: Header[] = new Array() + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onInterceptRequest((event) => { + console.log('url:' + event.request.getRequestUrl()) + var head1:Header = { + headerKey:"Connection", + headerValue:"keep-alive" + } + var head2:Header = { + headerKey:"Cache-Control", + headerValue:"no-cache" + } + var length = this.heads.push(head1) + length = this.heads.push(head2) + this.responseweb.setResponseHeader(this.heads) + this.responseweb.setResponseEncoding('utf-8') + this.responseweb.setResponseMimeType('text/html') + this.responseweb.setResponseCode(200) + this.responseweb.setReasonMessage('OK') + + //// fd scheme --start + // '/xxx/.../test.html' is the local path of the file. + // @ts-ignore + let fd = fileio.openSync('/xxx/.../test.html', 0o102, 0o666) + this.responseweb.setResponseData(fd) + //// fd scheme --end + + return this.responseweb + }) + } + } +} +``` + +When a HAP file is decompressed, the file path in the HAP does not exist. In this case, transfer the resource response data to the kernel through **setResponseData(data:Resource)**. +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + responseweb: WebResourceResponse = new WebResourceResponse() + heads: Header[] = new Array() + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onInterceptRequest((event) => { + console.log('url:' + event.request.getRequestUrl()) + var head1:Header = { + headerKey:"Connection", + headerValue:"keep-alive" + } + var head2:Header = { + headerKey:"Cache-Control", + headerValue:"no-cache" + } + var length = this.heads.push(head1) + length = this.heads.push(head2) + this.responseweb.setResponseHeader(this.heads) + this.responseweb.setResponseEncoding('utf-8') + this.responseweb.setResponseMimeType('text/html') + this.responseweb.setResponseCode(200) + this.responseweb.setReasonMessage('OK') + + //// Resource scheme --start + // Specify the target file in the rawfile directory of the HAP file. + this.responseweb.setResponseData($rawfile('test.html')) + //// Resource scheme --end + + return this.responseweb + }) + } + } +} +``` diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.7.5/changelogs-arkui.md b/en/release-notes/changelogs/OpenHarmony_4.0.7.5/changelogs-arkui.md new file mode 100644 index 0000000000000000000000000000000000000000..1e42e43eda4636eab4db83e5bb2e34bed083a475 --- /dev/null +++ b/en/release-notes/changelogs/OpenHarmony_4.0.7.5/changelogs-arkui.md @@ -0,0 +1,17 @@ +# ArkUI Subsystem Changelog + +## cl.arkui.1 Change in the \