From b308e15d24608dab9b17ad890135ba41e37c34f7 Mon Sep 17 00:00:00 2001 From: birdswu Date: Wed, 21 May 2025 09:48:02 +0800 Subject: [PATCH] =?UTF-8?q?LocalizationKit=20ArkWebKit=20CryptoArchitectur?= =?UTF-8?q?eKit=E6=A0=87=E8=AF=86=E6=B7=BB=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../entry/src/main/ets/pages/AddHeader.ets | 41 ++++++ .../src/main/ets/pages/BackPageByGestures.ets | 46 ++++++ .../entry/src/main/ets/pages/CookieInject.ets | 39 +++++ .../src/main/ets/pages/DebugProcessId.txt | 58 ++++++++ .../src/main/ets/pages/GetRawfileHtml.ets | 35 +++++ .../entry/src/main/ets/pages/GetScroll.ets | 80 ++++++++++ .../entry/src/main/ets/pages/HidePdf.ets | 39 +++++ .../src/main/ets/pages/InterceptRequest.ets | 53 +++++++ .../src/main/ets/pages/LoginCookieConfig.ets | 50 +++++++ .../entry/src/main/ets/pages/MixContent.ets | 45 ++++++ .../main/ets/pages/OnlyOnTheFirstTrigger.ets | 39 +++++ .../src/main/ets/pages/RequestCookie.ets | 55 +++++++ .../entry/src/main/ets/pages/RouteLink.ets | 36 +++++ .../src/main/ets/pages/RunJavaScript1.ets | 75 ++++++++++ .../src/main/ets/pages/RunJavaScript4.ets | 47 ++++++ .../entry/src/main/ets/pages/SupportVue.ets | 43 ++++++ .../entry/src/main/ets/pages/SupportVue2.ets | 44 ++++++ .../entry/src/main/ets/pages/SupportVue3.ets | 48 ++++++ ArkWebKit/entry/src/main/ets/pages/UrlAdd.ets | 38 +++++ .../entry/src/main/ets/pages/WebUserAgent.ets | 45 ++++++ .../entry/src/main/ets/pages/registerFont.txt | 26 ++++ .../rawfile/LoadingURLTransferParameters.html | 29 ++++ .../src/main/resources/rawfile/RunJs_3.html | 42 ++++++ .../src/main/resources/rawfile/RunJs_4.html | 41 ++++++ .../src/main/resources/rawfile/RunJs_one.html | 47 ++++++ .../src/main/resources/rawfile/RunJs_two.html | 35 +++++ .../src/main/resources/rawfile/details.html | 14 ++ .../src/main/resources/rawfile/index.html | 16 ++ .../src/main/resources/rawfile/index2.html | 69 +++++++++ .../src/main/resources/rawfile/local.html | 15 ++ .../src/main/resources/rawfile/local1.html | 14 ++ .../entry/src/main/ets/pages/EncryptRSA.ets | 50 +++++++ .../ets/pages/EncryptionAndDecryption.ets | 104 +++++++++++++ .../entry/src/main/ets/pages/GetHmac.ets | 73 +++++++++ .../entry/src/main/ets/pages/GetKey.ets | 56 +++++++ .../entry/src/main/ets/pages/HMACFailed.ets | 23 +++ .../entry/src/main/ets/pages/HMACFailed2.ets | 37 +++++ .../src/main/ets/pages/PubKeysConvert.ets | 42 ++++++ .../src/main/ets/pages/PublicKeysStored.ets | 73 +++++++++ .../entry/src/main/ets/pages/RsaDecrypt.ets | 138 ++++++++++++++++++ .../src/main/ets/pages/RsaPubKeyEncrypt.ets | 62 ++++++++ .../entry/src/main/ets/pages/SM3Encrypted.ets | 84 +++++++++++ .../src/main/ets/pages/TestAesMultiUpdate.ets | 99 +++++++++++++ .../src/main/ets/pages/CurrencyDelimiter.ets | 23 +++ .../entry/src/main/ets/pages/FileToString.ets | 48 ++++++ .../entry/src/main/ets/pages/GetRawfile.ets | 49 +++++++ .../entry/src/main/ets/pages/ToPingyin.ets | 30 ++++ 47 files changed, 2295 insertions(+) create mode 100644 ArkWebKit/entry/src/main/ets/pages/AddHeader.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/BackPageByGestures.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/CookieInject.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/DebugProcessId.txt create mode 100644 ArkWebKit/entry/src/main/ets/pages/GetRawfileHtml.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/GetScroll.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/HidePdf.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/InterceptRequest.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/LoginCookieConfig.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/MixContent.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/OnlyOnTheFirstTrigger.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/RequestCookie.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/RouteLink.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/RunJavaScript1.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/RunJavaScript4.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/SupportVue.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/SupportVue2.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/SupportVue3.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/UrlAdd.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/WebUserAgent.ets create mode 100644 ArkWebKit/entry/src/main/ets/pages/registerFont.txt create mode 100644 ArkWebKit/entry/src/main/resources/rawfile/LoadingURLTransferParameters.html create mode 100644 ArkWebKit/entry/src/main/resources/rawfile/RunJs_3.html create mode 100644 ArkWebKit/entry/src/main/resources/rawfile/RunJs_4.html create mode 100644 ArkWebKit/entry/src/main/resources/rawfile/RunJs_one.html create mode 100644 ArkWebKit/entry/src/main/resources/rawfile/RunJs_two.html create mode 100644 ArkWebKit/entry/src/main/resources/rawfile/details.html create mode 100644 ArkWebKit/entry/src/main/resources/rawfile/index.html create mode 100644 ArkWebKit/entry/src/main/resources/rawfile/index2.html create mode 100644 ArkWebKit/entry/src/main/resources/rawfile/local.html create mode 100644 ArkWebKit/entry/src/main/resources/rawfile/local1.html create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/EncryptRSA.ets create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/EncryptionAndDecryption.ets create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/GetHmac.ets create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/GetKey.ets create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/HMACFailed.ets create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/HMACFailed2.ets create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/PubKeysConvert.ets create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/PublicKeysStored.ets create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/RsaDecrypt.ets create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/RsaPubKeyEncrypt.ets create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/SM3Encrypted.ets create mode 100644 CryptoArchitectureKit/entry/src/main/ets/pages/TestAesMultiUpdate.ets create mode 100644 LocalizationKit/entry/src/main/ets/pages/CurrencyDelimiter.ets create mode 100644 LocalizationKit/entry/src/main/ets/pages/FileToString.ets create mode 100644 LocalizationKit/entry/src/main/ets/pages/GetRawfile.ets create mode 100644 LocalizationKit/entry/src/main/ets/pages/ToPingyin.ets diff --git a/ArkWebKit/entry/src/main/ets/pages/AddHeader.ets b/ArkWebKit/entry/src/main/ets/pages/AddHeader.ets new file mode 100644 index 0000000..a8b07c9 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/AddHeader.ets @@ -0,0 +1,41 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何在Web请求时添加header头 +*/ + + +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct Index { + controller: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Button('Refresh UI') + .width('200vp') + .onClick(() => { + // [Start AddHeader] + // With parameter headers + this.controller.loadUrl('www.example.com', [{ headerKey: "headerKey", headerValue: "headerValue" }]); + // [End AddHeader] + }) + .margin({ bottom: '20vp' }) + } + } +} diff --git a/ArkWebKit/entry/src/main/ets/pages/BackPageByGestures.ets b/ArkWebKit/entry/src/main/ets/pages/BackPageByGestures.ets new file mode 100644 index 0000000..35c8659 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/BackPageByGestures.ets @@ -0,0 +1,46 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web组件中如何通过手势滑动返回上一个Web页面 +*/ + +// [Start BackPageByGesturesPage] +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct BackPageByGesturesPage { + controller: webview.WebviewController = new webview.WebviewController(); + + onBackPress() { + // 当前页面是否可前进或者后退给定的step步(-1),正数代表前进,负数代表后退 + if (this.controller.accessStep(-1)) { + this.controller.backward(); // 返回上一个web页 + // 执行用户自定义返回逻辑 + return true; + } else { + // 执行系统默认返回逻辑,返回上一个page页 + return false; + } + } + + build() { + Column() { + Web({ src: 'http://www.example.com', controller: this.controller })//需要手动替换为真实网站 + } + } +} +// [End BackPageByGesturesPage] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/CookieInject.ets b/ArkWebKit/entry/src/main/ets/pages/CookieInject.ets new file mode 100644 index 0000000..614009f --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/CookieInject.ets @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:登录信息的cookie应该在什么时机注入?如何确保刚刚打开的web能注入登录信息cookie +*/ + +// [Start CookieInject] +import { webview } from '@kit.ArkWeb' + +webview.once("webInited", () => { + console.log("setCookie"); + webview.WebCookieManager.configCookie("https://www.example.com", 'a=b,c=d,e=f'); +}) + +@Entry +@Component +struct WebComponent { + controller: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +// [End CookieInject] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/DebugProcessId.txt b/ArkWebKit/entry/src/main/ets/pages/DebugProcessId.txt new file mode 100644 index 0000000..06cf147 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/DebugProcessId.txt @@ -0,0 +1,58 @@ +/* +* 如何解决,webview每次调试都需要寻找进程号 +*/ + +// [Start DebugProcessId] +// xxx.bat +@echo off +setlocal + +:: Set devtools parameter +hdc shell param set web.debug.devtools true +if errorlevel 1 ( + echo Error: Failed to set devtools parameter. + pause + exit /b +) + +:: Get the domain socket name of devtools +for /f "tokens=*" %%a in ('hdc shell "cat /proc/net/unix | grep devtools"') do set SOCKET_NAME=%%a +if not defined SOCKET_NAME ( + echo Error: Failed to get the domain socket name of devtools. + pause + exit /b +) + +:: Extract process ID +for /f "delims=_ tokens=4" %%a in ("%SOCKET_NAME%") do set PID=%%a +if not defined PID ( + echo Error: Failed to extract process ID. + pause + exit /b +) + +:: Add mapping +hdc fport tcp:9222 localabstract:webview_devtools_remote_%PID% +if errorlevel 1 ( + echo Error: Failed to add mapping. + pause + exit /b +) + +:: Check mapping +hdc fport ls + +echo. +echo Script executed successfully. Press any key to exit... +pause >nul + +:: 尝试在 Edge 中打开页面 +start msedge chrome://inspect/#devices.com + +:: 如果 Edge 不可用,那么在 Chrome 中打开页面 +if errorlevel 1 ( + start chrome chrome://inspect/#devices.com +) + +endlocal +// [End DebugProcessId] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/GetRawfileHtml.ets b/ArkWebKit/entry/src/main/ets/pages/GetRawfileHtml.ets new file mode 100644 index 0000000..5046a56 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/GetRawfileHtml.ets @@ -0,0 +1,35 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web组件如何访问本地的资源文件,并添加查询参数 +*/ + +// [Start GetRawfileHtml] +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct WebComponent { + controller: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Web({ src: $rawfile('index.html'), controller: this.controller }) + .javaScriptAccess(true) + } + } +} +// [End GetRawfileHtml] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/GetScroll.ets b/ArkWebKit/entry/src/main/ets/pages/GetScroll.ets new file mode 100644 index 0000000..d2f7399 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/GetScroll.ets @@ -0,0 +1,80 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何判断Web滑动到了顶部/底部,并且把滑动事件传递给页面 +*/ + +// [Start GetScroll] +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct Index { + private scrollerForScroll: Scroller = new Scroller(); + controller: webview.WebviewController = new webview.WebviewController; + @State ScrollDirection: ScrollDirection = ScrollDirection.Vertical; + title = '2023落下帷幕,一起迎接2024年***********************************************'; + review = '评论'; + context = '一起迎接2024年,***********************************************************************************'; + list = [0, 0, 0, 0]; + + build() { + Flex() { + Scroll(this.scrollerForScroll) { + Column({ space: 5 }) { + Text(this.title) + .fontSize(40) + .padding(40) + List() { + ForEach(this.list, () => { + ListItem() { + Text(this.context).fontSize(16) + } + }) + } + + Web({ src: $rawfile('index.html'), controller: this.controller }) + .nestedScroll({ + scrollForward: NestedScrollMode.SELF_FIRST, + scrollBackward: NestedScrollMode.SELF_FIRST + }) + .height('100%') + .width('100%') + .layoutMode(WebLayoutMode.FIT_CONTENT) + Text(this.review) + .fontSize(30) + List() { + ForEach(this.list, () => { + ListItem() { + Text(this.context) + .fontSize(16) + } + }) + } + } + .width('95%') + } + .scrollBar(BarState.Off) + .width('100%') + .height('120%') + .scrollable(this.ScrollDirection) + } + .width('100%') + .height('100%') + + } +} +// [End GetScroll] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/HidePdf.ets b/ArkWebKit/entry/src/main/ets/pages/HidePdf.ets new file mode 100644 index 0000000..366ecb7 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/HidePdf.ets @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:PDF预览如何隐藏PDF操作按钮栏 +*/ + +// [Start HidePDFToolbar] +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct HidePDFToolbar { + controller: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Web({ src: 'resource://rawfile/test.pdf#toolbar=0&navpanes=0', controller: this.controller }) + .domStorageAccess(true) + .width('100%') + .height('100%') + } + .width('100%') + .height('100%') + } +} +// [End HidePDFToolbar] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/InterceptRequest.ets b/ArkWebKit/entry/src/main/ets/pages/InterceptRequest.ets new file mode 100644 index 0000000..b23b48b --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/InterceptRequest.ets @@ -0,0 +1,53 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:onInterceptRequest拦截URL并自定义HTML文件,页面加载失败 +*/ + +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct WebviewAlert { + controller: webview.WebviewController = new webview.WebviewController(); + responseweb: WebResourceResponse | null = null; + heads: Array
= new Array; + webdata: number = 1; + build() { + Column() { + // [Start InterceptRequest] + Web({ src: 'www.example.com',controller: this.controller }) + .onInterceptRequest((event) => { + console.log('url:' + event.request.getRequestUrl()) + this.responseweb = new WebResourceResponse(); + let head1: Header = { + headerKey: "Connection", + headerValue: "keep-alive" + } + let length = this.heads.push(head1) + this.responseweb.setResponseHeader(this.heads) + this.responseweb.setResponseData(this.webdata) + this.responseweb.setResponseEncoding('utf-8') + this.responseweb.setResponseMimeType('text/html') + this.responseweb.setResponseCode(200) + this.responseweb.setReasonMessage('OK') + return this.responseweb + }) + // [Start InterceptRequest] + } + } +} + diff --git a/ArkWebKit/entry/src/main/ets/pages/LoginCookieConfig.ets b/ArkWebKit/entry/src/main/ets/pages/LoginCookieConfig.ets new file mode 100644 index 0000000..6075f86 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/LoginCookieConfig.ets @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:多个Cookie如何进行批量设置 +*/ + +// [Start MultiCookieConfig] +import { webview } from '@kit.ArkWeb'; + +webview.once("webInited", () => { + console.info("webInited setCookie"); + webview.WebCookieManager.configCookie("https://www.example.com", 'a=b'); + webview.WebCookieManager.configCookie("https://www.example.com", 'c=d'); + webview.WebCookieManager.configCookie("https://www.example.com", 'e=f'); +}) + +@Entry +@Component +struct LoginCookieConfig { + controller: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Button('fetchCookieSync') + .onClick(() => { + try { + let value = webview.WebCookieManager.fetchCookieSync('https://www.example.com'); + console.log(`fetchCookieSync cookie value is: ${value}`); + } catch (error) { + console.error(`fetchCookieSync failed,error is: ${JSON.stringify(error)}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +// [End MultiCookieConfig] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/MixContent.ets b/ArkWebKit/entry/src/main/ets/pages/MixContent.ets new file mode 100644 index 0000000..7172b18 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/MixContent.ets @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:WebView如何设置mixcontent策略,用以解决http与https混合加载的问题 +*/ + +// [Start MixContent] +import { webview } from '@kit.ArkWeb'; +import { BusinessError } from '@kit.BasicServicesKit'; + +@Entry +@Component +export struct WebUserAgent { + controller: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Button('getUserAgent') + .onClick(() => { + try { + let userAgent = this.controller.getUserAgent(); + console.log("userAgent: " + userAgent); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +// [End MixContent] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/OnlyOnTheFirstTrigger.ets b/ArkWebKit/entry/src/main/ets/pages/OnlyOnTheFirstTrigger.ets new file mode 100644 index 0000000..8f84e35 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/OnlyOnTheFirstTrigger.ets @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何控制只在Web组件第一次加载url的时候触发onPageBegin,onPageEnd +*/ + +// [Start OnlyOnTheFirstTrigger] +import { webview } from '@kit.ArkWeb' + +webview.once("webInited", () => { + console.log("setCookie"); + webview.WebCookieManager.configCookie("https://www.example.com", 'a=b,c=d,e=f'); +}) + +@Entry +@Component +struct WebComponent { + controller: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +// [End OnlyOnTheFirstTrigger] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/RequestCookie.ets b/ArkWebKit/entry/src/main/ets/pages/RequestCookie.ets new file mode 100644 index 0000000..f2d61ca --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/RequestCookie.ets @@ -0,0 +1,55 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:通过网络请求而来的 Cookie 如何同步配置到web中 +*/ + +// [Start RequestCookie] +import { webview } from '@kit.ArkWeb' +@Entry +@Component +struct WebComponent { + controller: webview.WebviewController = new webview.WebviewController(); + headers : Array = [{ headerKey : "msg",headerValue : 'hello'}]; + build() { + Column() { + Button('configCookieSync') + .onClick(() => { + try { + webview.WebCookieManager.configCookieSync('https://www.example.com', 'a=b,c=d,e=f'); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Button('fetchCookieSync') + .onClick(() => { + try { + let value = webview.WebCookieManager.fetchCookieSync('https://www.example.com'); + console.log("fetchCookieSync cookie = " + value); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .width('100%') + .height('100%') + } + .layoutWeight(1) + } + } +} +// [End RequestCookie] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/RouteLink.ets b/ArkWebKit/entry/src/main/ets/pages/RouteLink.ets new file mode 100644 index 0000000..1e434cc --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/RouteLink.ets @@ -0,0 +1,36 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Webview如何加载带有#路由的链接 +*/ + +// [Start RouteLink] +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct LoadWebLink { + controller: webview.WebviewController = new webview.WebviewController(); + + build() { + RelativeContainer() { + Web({ src: 'resource://rawfile/LoadWebLink.html#AAA', controller: this.controller }) + } + .height('100%') + .width('100%') + } +} +// [End RouteLink] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/RunJavaScript1.ets b/ArkWebKit/entry/src/main/ets/pages/RunJavaScript1.ets new file mode 100644 index 0000000..4556839 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/RunJavaScript1.ets @@ -0,0 +1,75 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web加载的H5页面跳转后,如何避免原有页面注册的资源被清空 +*/ + +// [Start RunJavaScript1] +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct Index { + controller: webview.WebviewController = new webview.WebviewController(); + + build() { + Column({ space: 20 }) { + Button('调用注册资源') + .onClick(e => { + try { + this.controller.runJavaScript( + 'test()', + (error, result) => { + if (error) { + console.error(`run JavaScript error, ErrorCode: ${error.code}, Message: ${error.message}`); + return; + } + if (result) { + console.info(`The test() return value is: ${result}`); + } + }); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Button('调用注册资源') + .onClick(e => { + try { + this.controller.runJavaScript( + 'bodyOnLoadLocalStorage()', + (error, result) => { + if (error) { + console.error(`run JavaScript error, ErrorCode: ${error.code}, Message: ${error.message}`); + return; + } + if (result) { + console.info(`The bodyOnLoadLocalStorage() return value is: ${result}`); + } + }); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: $rawfile('index.html'), controller: this.controller }) + .javaScriptAccess(true) + .domStorageAccess(true) + .backgroundColor(Color.Grey) + .width('100%') + .height('100%') + } + } +} +// [End RunJavaScript1] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/RunJavaScript4.ets b/ArkWebKit/entry/src/main/ets/pages/RunJavaScript4.ets new file mode 100644 index 0000000..d818198 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/RunJavaScript4.ets @@ -0,0 +1,47 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web加载的H5页面跳转后,如何避免原有页面注册的资源被清空 +*/ + +// [Start RunJavaScript4] +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct Index { + controller: webview.WebviewController = new webview.WebviewController(); + private localStorage: string = + "if (typeof(Storage) !== 'undefined') {" + + " sessionStorage.setItem('color', 'Red');" + + "}"; + @State scripts: Array = [ + { script: this.localStorage, scriptRules: ["*"] } + ]; + + build() { + Column({ space: 20 }) { + Web({ src: $rawfile('index.html'), controller: this.controller }) + .javaScriptAccess(true) + .domStorageAccess(true) + .backgroundColor(Color.Grey) + .javaScriptOnDocumentStart(this.scripts) + .width('100%') + .height('100%') + } + } +} +// [End RunJavaScript4] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/SupportVue.ets b/ArkWebKit/entry/src/main/ets/pages/SupportVue.ets new file mode 100644 index 0000000..e9df9f2 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/SupportVue.ets @@ -0,0 +1,43 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web组件对H5页面、常用框架VUE、React的页面支持情况,包括本地和网络端的页面 +*/ + +// [Start SupportVue1] +// xxx.ets +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct WebComponent { + webviewController: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Button('loadUrl').onClick(() => { + try { // 点击按钮时,通过loadUrl,跳转到www.example1.com + this.webviewController.loadUrl('www.example1.com'); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + // 组件创建时,加载www.example.com + Web({ src: 'www.example.com', controller: this.webviewController }) + } + } +} +// [End SupportVue1] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/SupportVue2.ets b/ArkWebKit/entry/src/main/ets/pages/SupportVue2.ets new file mode 100644 index 0000000..d19dc1c --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/SupportVue2.ets @@ -0,0 +1,44 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web组件对H5页面、常用框架VUE、React的页面支持情况,包括本地和网络端的页面 +*/ + +// [Start SupportVue2] +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct WebComponent { + webviewController: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + // 点击按钮时,通过resource加载resources/rawfile目录下的local1.html文件 + this.webviewController.loadUrl('resource://rawfile/local1.html'); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + // 组件创建时,使用resource协议加载本地文件local.html + Web({ src: 'resource://rawfile/local.html', controller: this.webviewController }) + } + } +} +// [End SupportVue2] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/SupportVue3.ets b/ArkWebKit/entry/src/main/ets/pages/SupportVue3.ets new file mode 100644 index 0000000..a8566ea --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/SupportVue3.ets @@ -0,0 +1,48 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web组件对H5页面、常用框架VUE、React的页面支持情况,包括本地和网络端的页面 +*/ + +// [Start SupportVue3] +import { webview } from '@kit.ArkWeb'; + +@Entry +@Component +struct WebComponent { + controller: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Button('loadData') + .onClick(() => { + try { + // 点击按钮时,通过loadData,加载HTML格式的文本数据 + this.controller.loadData( + "Source:
source
", + "text/html", + "UTF-8" + ); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + // 组件创建时,加载www.example.com + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +// [End SupportVue3] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/UrlAdd.ets b/ArkWebKit/entry/src/main/ets/pages/UrlAdd.ets new file mode 100644 index 0000000..a4997c2 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/UrlAdd.ets @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web组件使用rawFile加载离线html时,如何在url后拼接参数 +*/ + +// [Start UrlAdd] +import { webview } from '@kit.ArkWeb' + +@Entry +@Component +struct WebComponent { + controller: webview.WebviewController = new webview.WebviewController() + + build() { + Column() { + Web({ src: 'resource://rawfile/LoadingURLTransferParameters.html?key=value', controller: this.controller }) + .javaScriptAccess(true) + .domStorageAccess(true) + } + .width('100%') + .height('100%') + } +} +// [End UrlAdd] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/WebUserAgent.ets b/ArkWebKit/entry/src/main/ets/pages/WebUserAgent.ets new file mode 100644 index 0000000..ce14f7e --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/WebUserAgent.ets @@ -0,0 +1,45 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何使用web中的userAgent区别当前使用的设备类型是手机还是电脑 +*/ + +// [Start WebUserAgent] +import { webview } from '@kit.ArkWeb'; +import { BusinessError } from '@kit.BasicServicesKit'; + +@Entry +@Component +export struct WebUserAgent { + controller: webview.WebviewController = new webview.WebviewController(); + + build() { + Column() { + Button('getUserAgent') + .onClick(() => { + try { + let userAgent = this.controller.getUserAgent(); + console.log("userAgent: " + userAgent); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +// [End WebUserAgent] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/ets/pages/registerFont.txt b/ArkWebKit/entry/src/main/ets/pages/registerFont.txt new file mode 100644 index 0000000..477b7c3 --- /dev/null +++ b/ArkWebKit/entry/src/main/ets/pages/registerFont.txt @@ -0,0 +1,26 @@ +/* +* 注册的自定义字体在 webview 中无效 +*/ + +// [Start registerFont] + + + + + + + Document + + + +

猫啃忘形圆

+ + +// [End registerFont] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/resources/rawfile/LoadingURLTransferParameters.html b/ArkWebKit/entry/src/main/resources/rawfile/LoadingURLTransferParameters.html new file mode 100644 index 0000000..7d5a38f --- /dev/null +++ b/ArkWebKit/entry/src/main/resources/rawfile/LoadingURLTransferParameters.html @@ -0,0 +1,29 @@ + +/* +* FAQ:Web组件使用rawFile加载离线html时,如何在url后拼接参数 +*/ + +// [Start UrlAdd2] + + + + Parameter-based HTML + + +

Welcome!

+

+ + + + +// [End UrlAdd2] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/resources/rawfile/RunJs_3.html b/ArkWebKit/entry/src/main/resources/rawfile/RunJs_3.html new file mode 100644 index 0000000..0759536 --- /dev/null +++ b/ArkWebKit/entry/src/main/resources/rawfile/RunJs_3.html @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web加载的H5页面跳转后,如何避免原有页面注册的资源被清空 +*/ + +// [Start RunJavaScript5] + + + + + + + +页面一:”Hello world! +
+点击跳转 + + + +// [End RunJavaScript5] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/resources/rawfile/RunJs_4.html b/ArkWebKit/entry/src/main/resources/rawfile/RunJs_4.html new file mode 100644 index 0000000..6907ac8 --- /dev/null +++ b/ArkWebKit/entry/src/main/resources/rawfile/RunJs_4.html @@ -0,0 +1,41 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web加载的H5页面跳转后,如何避免原有页面注册的资源被清空 +*/ + +// [Start RunJavaScript6] + + + + + + + +页面二:Hello world! +
+ + + +// [End RunJavaScript6] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/resources/rawfile/RunJs_one.html b/ArkWebKit/entry/src/main/resources/rawfile/RunJs_one.html new file mode 100644 index 0000000..567018d --- /dev/null +++ b/ArkWebKit/entry/src/main/resources/rawfile/RunJs_one.html @@ -0,0 +1,47 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web加载的H5页面跳转后,如何避免原有页面注册的资源被清空 +*/ + +// [Start RunJavaScript2] + + + + + + + +页面一:”Hello world! +
+点击跳转 + + + +// [End RunJavaScript2] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/resources/rawfile/RunJs_two.html b/ArkWebKit/entry/src/main/resources/rawfile/RunJs_two.html new file mode 100644 index 0000000..67bb832 --- /dev/null +++ b/ArkWebKit/entry/src/main/resources/rawfile/RunJs_two.html @@ -0,0 +1,35 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:Web加载的H5页面跳转后,如何避免原有页面注册的资源被清空 +*/ + +// [Start RunJavaScript3] + + + + + + + +页面二:Hello world! +
+ + + +// [End RunJavaScript3] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/resources/rawfile/details.html b/ArkWebKit/entry/src/main/resources/rawfile/details.html new file mode 100644 index 0000000..2ac2be4 --- /dev/null +++ b/ArkWebKit/entry/src/main/resources/rawfile/details.html @@ -0,0 +1,14 @@ + + +/* +* FAQ:Web组件如何访问本地的资源文件,并添加查询参数 +*/ + +// [Start GetRawfileHtml3] + + +详情页 +

欢迎来到详情页!

+

您已成功从首页跳转到此页,并在URL中添加了参数。

+ +// [End GetRawfileHtml3] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/resources/rawfile/index.html b/ArkWebKit/entry/src/main/resources/rawfile/index.html new file mode 100644 index 0000000..3638123 --- /dev/null +++ b/ArkWebKit/entry/src/main/resources/rawfile/index.html @@ -0,0 +1,16 @@ + +/* +* FAQ:Web组件如何访问本地的资源文件,并添加查询参数 +*/ + +// [Start GetRawfileHtml2] + + + + + + + + +// [End GetRawfileHtml2] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/resources/rawfile/index2.html b/ArkWebKit/entry/src/main/resources/rawfile/index2.html new file mode 100644 index 0000000..f655ded --- /dev/null +++ b/ArkWebKit/entry/src/main/resources/rawfile/index2.html @@ -0,0 +1,69 @@ + +/* +* FAQ:如何判断Web滑动到了顶部/底部,并且把滑动事件传递给页面 +*/ + +// [Start GetScroll2] + + + + + + + Document + + +
    +
  1. 欢度佳节,********************************************************
  2. +
  3. ********************************************************
  4. +
  5. 欢度佳节,********************************************************
  6. +
  7. ********************************************************
  8. +
  9. 欢度佳节,********************************************************
  10. +
  11. ********************************************************
  12. +
  13. 欢度佳节,********************************************************
  14. +
  15. ********************************************************
  16. +
  17. 欢度佳节,********************************************************
  18. +
  19. ********************************************************
  20. +
  21. 欢度佳节,********************************************************
  22. +
  23. ********************************************************
  24. +
  25. 欢度佳节,********************************************************
  26. +
  27. ********************************************************
  28. +
  29. 欢度佳节,********************************************************
  30. +
  31. ********************************************************
  32. +
  33. 欢度佳节,********************************************************
  34. +
  35. ********************************************************
  36. +
  37. 欢度佳节,********************************************************
  38. +
  39. ********************************************************
  40. +
  41. 欢度佳节,********************************************************
  42. +
  43. ********************************************************
  44. +
  45. 欢度佳节,********************************************************
  46. +
  47. ********************************************************
  48. +
  49. 欢度佳节,********************************************************
  50. +
  51. ********************************************************
  52. +
  53. 欢度佳节,********************************************************
  54. +
  55. ********************************************************
  56. +
  57. 欢度佳节,********************************************************
  58. +
  59. ********************************************************
  60. +
  61. 欢度佳节,********************************************************
  62. +
  63. ********************************************************
  64. +
  65. 欢度佳节,********************************************************
  66. +
  67. ********************************************************
  68. +
  69. 欢度佳节,********************************************************
  70. +
  71. ********************************************************
  72. +
  73. 欢度佳节,********************************************************
  74. +
  75. ********************************************************
  76. +
  77. 欢度佳节,********************************************************
  78. +
  79. ********************************************************
  80. +
  81. 欢度佳节,********************************************************
  82. +
  83. ********************************************************
  84. +
  85. 欢度佳节,********************************************************
  86. +
  87. ********************************************************
  88. +
  89. 欢度佳节,********************************************************
  90. +
  91. ********************************************************
  92. +
  93. 欢度佳节,********************************************************
  94. +
  95. ********************************************************
  96. +
+ + +// [End GetScroll2] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/resources/rawfile/local.html b/ArkWebKit/entry/src/main/resources/rawfile/local.html new file mode 100644 index 0000000..8f918e6 --- /dev/null +++ b/ArkWebKit/entry/src/main/resources/rawfile/local.html @@ -0,0 +1,15 @@ + + +/* +* FAQ:Web组件对H5页面、常用框架VUE、React的页面支持情况,包括本地和网络端的页面 +*/ + +// [Start SupportVue4] + + + + +

Hello World

+ + +// [End SupportVue4] \ No newline at end of file diff --git a/ArkWebKit/entry/src/main/resources/rawfile/local1.html b/ArkWebKit/entry/src/main/resources/rawfile/local1.html new file mode 100644 index 0000000..289085c --- /dev/null +++ b/ArkWebKit/entry/src/main/resources/rawfile/local1.html @@ -0,0 +1,14 @@ + +/* +* FAQ:Web组件对H5页面、常用框架VUE、React的页面支持情况,包括本地和网络端的页面 +*/ + +// [Start SupportVue5] + + + + +

Hello World, local1.html

+ + +// [End SupportVue5] \ No newline at end of file diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/EncryptRSA.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/EncryptRSA.ets new file mode 100644 index 0000000..a8d68fd --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/EncryptRSA.ets @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何使用服务端下发的RSA公钥(字符串)对明文数据进行加密 +*/ + +// [Start EncryptRSA] +import { buffer, util } from '@kit.ArkTS'; +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; +/** + * Encrypt using RSA asymmetric key (PKCS1 mode) + * @param message Clear text data to be encrypted + * @returns Encrypted string, encoded in base64 format + */ +export async function encryptRSA(message: string) { + // Server issues RSA public key string (base64 encoding) + let pubKeyStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDFQArGDm5BXM4jHHuZGIb/kUoqrSjXkjqPLgrDmqBFxNyYsyxvyFRO10nStQwdRkQkh5lZ5sqC1G/z6lyDPpEySTBo9S5GLZ2Tj4yinNjcMXmOwiHfyQAQo9LwdlyTedwRchg0fYewWBVTVhGcWPowT1aA+GnQhYwNmaS/iKQsNQIDAQAB"; + // Initialize Base64 tool instance + let base64Helper = new util.Base64Helper(); + // Convert the public key to Uint8Array and package it as a DataBlob type + let pubKeyBlob: cryptoFramework.DataBlob = { data: base64Helper.decodeSync(pubKeyStr) }; + // Create RSA key generator + let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); + // Convert the public key wrapper data pubKeyBlob into a key pair type KeyPair + let keyPair = await rsaGenerator.convertKey(pubKeyBlob, null); + // Create a Cipher object + let cipher = cryptoFramework.createCipher('RSA1024|PKCS1'); + // Initialize encryption mode and specify the key keyPair. pubKey + await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null); + // Packaging requires encrypted plaintext + let plainTextBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; + // Pass in plaintext and retrieve encrypted data + let encryptBlob = await cipher.doFinal(plainTextBlob); + // Return encrypted string + return base64Helper.encodeToStringSync(encryptBlob.data); +} +// [End EncryptRSA] \ No newline at end of file diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/EncryptionAndDecryption.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/EncryptionAndDecryption.ets new file mode 100644 index 0000000..37ba16b --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/EncryptionAndDecryption.ets @@ -0,0 +1,104 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何对公钥和私钥进行加解密 +*/ + +// [Start EncryptionAndDecryption] +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; +import { util } from '@kit.ArkTS'; + +let base = new util.Base64Helper(); +let pubKeyStr = uint8ArrayToHexStr(base.decodeSync('公钥')); +let priKeyStr = uint8ArrayToHexStr(base.decodeSync('私钥')); + +async function encryptionAndDecryption() { + // 根据密钥参数生成公私钥 + let pk = await convertStrToPubKey(pubKeyStr); + let sk = await convertStrToPriKey(priKeyStr); + + //加密 + let encryptText = await encryptMessagePromise(pk, '加密信息'); + //解密 + let res = await decryptMessagePromise(sk, encryptText); +} + +//根据密钥参数生成sm2公钥 +async function convertStrToPubKey(keyStr: string): Promise { + let pubKeyStr = keyStr.startsWith("04") ? keyStr.slice(2) : keyStr; + let pkPart1 = pubKeyStr.slice(0, pubKeyStr.length / 2); + let pkPart2 = pubKeyStr.slice(pubKeyStr.length / 2); + let pk: cryptoFramework.Point = { + x: BigInt("0x" + pkPart1), + y: BigInt("0x" + pkPart2), + } + let pubKeySpec: cryptoFramework.ECCPubKeySpec = { + params: cryptoFramework.ECCKeyUtil.genECCCommonParamsSpec('NID_sm2'), + pk: pk, + algName: "SM2", + specType: cryptoFramework.AsyKeySpecType.PUBLIC_KEY_SPEC + } + let keypairGenerator = cryptoFramework.createAsyKeyGeneratorBySpec(pubKeySpec); + return await keypairGenerator.generatePubKey(); +} + +//根据密钥参数生成sm2私钥 +async function convertStrToPriKey(keyStr: string): Promise { + let sk = BigInt("0x" + keyStr); + let priKeySpec: cryptoFramework.ECCPriKeySpec = { + params: cryptoFramework.ECCKeyUtil.genECCCommonParamsSpec('NID_sm2'), + sk: sk, + algName: "SM2", + specType: cryptoFramework.AsyKeySpecType.PRIVATE_KEY_SPEC + } + let keypairGenerator = cryptoFramework.createAsyKeyGeneratorBySpec(priKeySpec); + return await keypairGenerator.generatePriKey(); +} + +// 解密消息 +async function decryptMessagePromise(privateKey: cryptoFramework.PriKey, cipherText: cryptoFramework.DataBlob) { + let decoder = cryptoFramework.createCipher('SM2_256|SM3'); + await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, privateKey, null); + let decryptData = await decoder.doFinal(cipherText); + return decryptData; +} + +// 加密消息 +async function encryptMessagePromise(publicKey: cryptoFramework.PubKey, plainText: string) { + let cipher = cryptoFramework.createCipher('SM2_256|SM3'); + await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, publicKey, null); + let encryptData = await cipher.doFinal({ data: stringToUint8Array(plainText) }); + return encryptData; +} + +function uint8ArrayToHexStr(data: Uint8Array): string { + let hexString = ''; + let i: number; + for (i = 0; i < data.length; i++) { + let char = ('00' + data[i].toString(16)).slice(-2); + hexString += char; + } + return hexString; +} + +function stringToUint8Array(str: string) { + let arr = new Uint8Array(str.length); + for (let i = 0, j = str.length; i < j; ++i) { + arr[i] = str.charCodeAt(i); + } + return arr; +} +// [End EncryptionAndDecryption] \ No newline at end of file diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/GetHmac.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/GetHmac.ets new file mode 100644 index 0000000..03d5d3a --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/GetHmac.ets @@ -0,0 +1,73 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何使用SM3算法进行消息认证码计算 +*/ + +// [Start GetHmac] +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; +import { buffer } from '@kit.ArkTS'; + +@Entry +@Component +struct Hmac { + @State message: string = 'Hello World'; + + build() { + Row() { + Column() { + Button('使用SM3算法进行消息认证码计算') + .fontSize(20) + .fontWeight(FontWeight.Bold) + .onClick(() => { + getHmac('密钥') + }) + } + .width('100%') + } + .height('100%') + } +} + +// Convert understandable strings into byte streams +function stringToUint8Array(str: string) { + let arr = new Uint8Array(str.length); + for (let i = 0, j = str.length; i < j; ++i) { + arr[i] = str.charCodeAt(i); + } + return arr; +} + +async function getHmac(message:string){ + + try { + let macAlgName = 'SM3'; + let mac =cryptoFramework.createMac(macAlgName) + let arr = stringToUint8Array('30a86dc9056c44cc05420fec269270214bbb6914954e871e83771c9810ac1db0') + let KeyBlob: cryptoFramework.DataBlob = {data:arr}; + let symKeyGenerator = cryptoFramework.createSymKeyGenerator('HMAC'); + const symKey=await symKeyGenerator.convertKey(KeyBlob); + await mac.init(symKey) + await mac.update({data:stringToUint8Array(message)}); + let macOutpt= await mac.doFinal(); + const res=buffer.from(macOutpt.data).toString('hex'); + console.log('Hmac---:'+res); + }catch (err){ + console.log('err:'+err) + } + +} +// [End GetHmac] \ No newline at end of file diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/GetKey.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/GetKey.ets new file mode 100644 index 0000000..cae077f --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/GetKey.ets @@ -0,0 +1,56 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:在进行aes加密的时候,如何把字符串转换成Key对象 +*/ + +// [Start GetKey] +import { buffer, util } from '@kit.ArkTS'; +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; + + +@Entry +@Component +struct GetKey { + // Convert string to byte stream + stringToUint8Array(str: string) { + return new Uint8Array(buffer.from(str, 'utf-8').buffer); + } + + //Import key + async getKey() { + let symAlgName = 'AES128'; + let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); + let dataUint8Array = this.stringToUint8Array('294A2561FEFDF08D'); + let keyBlob: cryptoFramework.DataBlob = { data: dataUint8Array }; + console.info('keyBlob', JSON.stringify(keyBlob)) + let symKey = await symKeyGenerator.convertKey(keyBlob); + return symKey; + } + + build() { + Column({ space: 10 }) { + Button('aes加密时,字符串转换成Key对象') + .onClick(() => { + this.getKey(); + }) + } + .alignItems(HorizontalAlign.Center) + .height('100%') + .width('100%') + } +} +// [End GetKey] \ No newline at end of file diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/HMACFailed.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/HMACFailed.ets new file mode 100644 index 0000000..cdb6b65 --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/HMACFailed.ets @@ -0,0 +1,23 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; + +/* +* FAQ:HMAC加密报错:error: convert sym key failed +*/ + +// [Start HMACFailed] +let symKeyGenerator = cryptoFramework.createSymKeyGenerator('HMAC'); +// [End HMACFailed] diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/HMACFailed2.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/HMACFailed2.ets new file mode 100644 index 0000000..ac0f08a --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/HMACFailed2.ets @@ -0,0 +1,37 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; + +/* +* FAQ:HMAC加密报错:error: convert sym key failed +*/ + +// [Start HMACFailed2] +let symKeyGenerator = cryptoFramework.createSymKeyGenerator('HMAC|SHA1'); +// [End HMACFailed2] diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/PubKeysConvert.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/PubKeysConvert.ets new file mode 100644 index 0000000..a19cf6d --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/PubKeysConvert.ets @@ -0,0 +1,42 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何将公钥转为十六进制或者base64进制数据 +*/ + +// [Start PubKeysConvert] +import { buffer, util } from '@kit.ArkTS'; + +@Entry +@Component +struct PubKeysConvert { + + build() { + Column(){ + Button('公钥转十六进制').onClick(()=>{ + let pubKeyData = '公钥' + let res = buffer.from(pubKeyData).toString('hex') + console.info('公钥转十六进制',res) + }) + Button('公钥转base64').onClick(()=>{ + let pubKeyUint8Array = new Uint8Array(buffer.from('公钥','utf-8').buffer) + let res = new util.Base64Helper().encodeToStringSync(pubKeyUint8Array) + console.info('公钥转base64',res) + }) + } + } +} +// [End PubKeysConvert] \ No newline at end of file diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/PublicKeysStored.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/PublicKeysStored.ets new file mode 100644 index 0000000..9342888 --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/PublicKeysStored.ets @@ -0,0 +1,73 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何存储公钥 +*/ + +// [Start PublicKeysStored] +import { buffer, util } from '@kit.ArkTS' +import { cryptoFramework } from '@kit.CryptoArchitectureKit' + +@Entry +@Component +struct PublicKeysStored { + build() { + Row() { + Column() { + Button('公钥转为base64进制数据存储').onClick(() => { + let publicKeys = + new Uint8Array([ + 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, + 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, 0xfe, 0x1c, 0x67, 0xde, + 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c, 0xaa, 0xc5, 0xd9, 0xd2, + 0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, 0xac, 0x99, 0x3d, 0xe8, + 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f, 0x7a, 0x41, 0xe5, 0x44, + 0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e + ]); + let result = new util.Base64Helper().encodeToStringSync(publicKeys) + console.info('base64 result=',result) + let base64 = new util.Base64Helper(); + let byte = base64.decodeSync(result)// base64 + console.info('base64 byte=',byte) + // Convert the converted array into a public key object + let keyBlob: cryptoFramework.DataBlob = { data: byte } + + }) + + Button('公钥转为十六进制数据存储').onClick(() => { + let publicKeys = + new Uint8Array([ + 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, + 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc0, 0xfe, 0x1c, 0x67, 0xde, + 0x86, 0x0e, 0xfb, 0xaf, 0xb5, 0x85, 0x52, 0xb4, 0x0e, 0x1f, 0x6c, 0x6c, 0xaa, 0xc5, 0xd9, 0xd2, + 0x4d, 0xb0, 0x8a, 0x72, 0x24, 0xa1, 0x99, 0xaf, 0xfc, 0x3e, 0x55, 0x5a, 0xac, 0x99, 0x3d, 0xe8, + 0x34, 0x72, 0xb9, 0x47, 0x9c, 0xa6, 0xd8, 0xfb, 0x00, 0xa0, 0x1f, 0x9f, 0x7a, 0x41, 0xe5, 0x44, + 0x3e, 0xb2, 0x76, 0x08, 0xa2, 0xbd, 0xe9, 0x41, 0xd5, 0x2b, 0x9e + ]); + let result = buffer.from(publicKeys).toString('hex') + console.info('hex result=',result) + let byte = new Uint8Array(buffer.from(result, 'hex').buffer) + console.info('hex byte=',byte) + // Convert the converted array into a public key object + let keyBlob: cryptoFramework.DataBlob = { data: byte } + }) + } + .width('100%') + } + .height('100%') + } +} +// [End PublicKeysStored] \ No newline at end of file diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/RsaDecrypt.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/RsaDecrypt.ets new file mode 100644 index 0000000..8b67080 --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/RsaDecrypt.ets @@ -0,0 +1,138 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何实现RSA的公钥PK加密一段文字 +*/ + +// [Start RsaDecrypt] +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; +import { buffer, util } from '@kit.ArkTS'; +// 字符串转成字节流 +function stringToUint8Array(str: string) { + return new Uint8Array(buffer.from(str, 'utf-8').buffer); +} +// 字节流转成可理解的字符串 +function uint8ArrayToString(array: Uint8Array) { + // 将UTF-8编码转换成Unicode编码 + let out: string = ''; + let index: number = 0; + let len: number = array.length; + while (index < len) { + let character = array[index++]; + switch (character >> 4) { + case 0: + case 1: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + out += String.fromCharCode(character); + break; + case 12: + case 13: + out += String.fromCharCode(((character & 0x1F) << 6) | (array[index++] & 0x3F)); + break; + case 14: + out += String.fromCharCode(((character & 0x0F) << 12) | ((array[index++] & 0x3F) << 6) | + ((array[index++] & 0x3F) << 0)); + break; + default: + break; + } + } + return out; +} +export class KeyPair { + publicKey: string = ''; + privateKey: string = ''; +} +export class RSA { + private ASY_KEY_NAME_RSA_3072: string = 'RSA1024'; + private ALG_NAME_RSA_3072: string = 'RSA|PKCS1'; + static priKey: Uint8Array = new Uint8Array(); //用于临时保存 + static pubKey: Uint8Array = new Uint8Array(); //用于临时保存 + private base: util.Base64Helper = new util.Base64Helper(); + public async generateRsaKeyPair(): Promise { + let keyPair: KeyPair = new KeyPair(); + try { + let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(this.ASY_KEY_NAME_RSA_3072); + const tempKeyPair = await asyKeyGenerator.generateKeyPair(); + keyPair = { + publicKey: this.base.encodeToStringSync(tempKeyPair.pubKey.getEncoded().data), + privateKey: this.base.encodeToStringSync(tempKeyPair.priKey.getEncoded().data) + } + } catch (err) { + console.error(err); + } + return keyPair; + } + public async add(str: string, publicKey: string): Promise { + let result = ''; + try { + let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(this.ASY_KEY_NAME_RSA_3072); + //创建一个 Cipher (解密)对象 + let cipher = cryptoFramework.createCipher(this.ALG_NAME_RSA_3072); + //引入外部的公钥加密 + let keyGenPromise: cryptoFramework.KeyPair = + await asyKeyGenerator.convertKey({ data: this.base.decodeSync(publicKey) }, null); + await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyGenPromise.pubKey, null); + let put: cryptoFramework.DataBlob = { data: stringToUint8Array(str) }; + const finalRes = await cipher.doFinal(put); + result = this.base.encodeToStringSync(finalRes.data); + console.info(result); + } catch (err) { + console.log(err.message); + } + return result; + } + public async rsaDecrypt(message: string | Uint8Array, privateKey: string): Promise { + let result = ''; + try { + let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator(this.ASY_KEY_NAME_RSA_3072); + const keyPair = await asyKeyGenerator.convertKey(null, { data: this.base.decodeSync(privateKey) }); + let cipher = cryptoFramework.createCipher(this.ALG_NAME_RSA_3072); //创建一个 Cipher (解密)对象 + await cipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, keyPair.priKey, null); + let bytes: Uint8Array | string = message; + if (typeof message === 'string') { + bytes = this.base.decodeSync(message); + } else { + bytes = message; + } + const finalRes = await cipher.doFinal({ data: bytes }); + result = uint8ArrayToString(finalRes.data); + console.info(result); + } catch (err) { + console.error(err.code); + } + return result; + } +} +@Entry +@Component +struct EncryptedText { + @State word: string = '加解密文字'; + private EncryptionAndDecryption = new RSA(); + async aboutToAppear(): Promise { + let key = await this.EncryptionAndDecryption.generateRsaKeyPair(); + let result = await this.EncryptionAndDecryption.add(this.word, key.publicKey); + this.EncryptionAndDecryption.rsaDecrypt(result, key.privateKey); + } + build() { + } +} +// [End RsaDecrypt] \ No newline at end of file diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/RsaPubKeyEncrypt.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/RsaPubKeyEncrypt.ets new file mode 100644 index 0000000..8d1feb2 --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/RsaPubKeyEncrypt.ets @@ -0,0 +1,62 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +/* +* FAQ:HMAC加密报错:error: convert sym key failed +*/ + +// [Start RsaPubKeyEncrypt] +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; + +async function rsaPubKeyEncrypt(pubKey: cryptoFramework.PubKey, plainText: cryptoFramework.DataBlob) { + try { + let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); + let keyGenPromise: cryptoFramework.KeyPair = + await asyKeyGenerator.convertKey({ data: pubKey.getEncoded().data }, null); + let cipher = cryptoFramework.createCipher('RSA1024|PKCS1'); + await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyGenPromise.pubKey, null); + let encryptData = await cipher.doFinal(plainText); + return uint8ArrayToHexStr(encryptData.data); + } catch (err) { + console.info(err); + return uint8ArrayToHexStr(new Uint8Array()); + } +} +// [End RsaPubKeyEncrypt] + +// [Start RsaPubKeyEncrypt2] +function uint8ArrayToHexStr(data: Uint8Array): string { + let hexString = ''; + let i: number; + for (i = 0; i < data.length; i++) { + let char = ('00' + data[i].toString(16)).slice(-2); + hexString += char; + } + return hexString; +} +// [End RsaPubKeyEncrypt2] \ No newline at end of file diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/SM3Encrypted.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/SM3Encrypted.ets new file mode 100644 index 0000000..9c210b0 --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/SM3Encrypted.ets @@ -0,0 +1,84 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何使用SM3加密 +*/ + +// [Start SM3Encrypted] +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { util, buffer } from '@kit.ArkTS'; + +let base64 = new util.Base64Helper(); + +@Entry +@Component +struct SM3Encrypted { + stringToUint8Array(str: string) { + return new Uint8Array(buffer.from(str, 'utf-8').buffer); + } + + // Complete the summary in Promise format + doMdByPromise() { + // Summary algorithm name. + let mdAlgName = 'SM3'; + // The data to be summarized. + let message = 'Hello,world'; + let md = cryptoFramework.createMd(mdAlgName); + console.info('[Promise]: Md algName is: ' + md.algName); + let promiseMdUpdate = md.update({ data: this.stringToUint8Array(message) }); + promiseMdUpdate.then(() => { + // Call digest() to return the result. + let PromiseMdDigest = md.digest(); + return PromiseMdDigest; + }).then(digestOutput => { + let mdOutput = digestOutput.data; + //Uint8Array to base64 + let str2 = base64.encodeToStringSync(mdOutput); + //Convert to hexadecimal + let str = this.uint8ArrayToHexStr(mdOutput); + console.info('[Promise]: MD result: ' + mdOutput); + let mdLen = md.getMdLength(); + console.info('[Promise]: MD len: ' + mdLen); + }).catch((error: BusinessError) => { + console.error('[Promise]: error: ' + error.message); + }); + } + + //The summary result is Uint8Array type, converted to hexadecimal string data + uint8ArrayToHexStr(data: Uint8Array): string { + let hexString = ''; + let i: number; + for (i = 0; i < data.length; i++) { + let char = ('00' + data[i].toString(16)).slice(-2); + hexString += char; + } + return hexString; + } + + build() { + Column({ space: 10 }) { + Button('使用SM3加密') + .onClick(() => { + this.doMdByPromise(); + }) + } + .alignItems(HorizontalAlign.Center) + .height('100%') + .width('100%') + } +} +// [End SM3Encrypted] \ No newline at end of file diff --git a/CryptoArchitectureKit/entry/src/main/ets/pages/TestAesMultiUpdate.ets b/CryptoArchitectureKit/entry/src/main/ets/pages/TestAesMultiUpdate.ets new file mode 100644 index 0000000..ce4b5b1 --- /dev/null +++ b/CryptoArchitectureKit/entry/src/main/ets/pages/TestAesMultiUpdate.ets @@ -0,0 +1,99 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何对大文件进行SM4加密 +*/ + +// [Start TestAesMultiUpdate] +import { cryptoFramework } from '@kit.CryptoArchitectureKit'; +function genIvParamsSpec() { + let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; + let dataIv = new Uint8Array(arr); + let ivBlob: cryptoFramework.DataBlob = { data: dataIv }; + let ivParamsSpec: cryptoFramework.IvParamsSpec = { + algName: 'IvParamsSpec', + iv: ivBlob + }; + return ivParamsSpec; +} +function stringToUint8Array(str: string): Uint8Array { + let arr: Array = []; + for (let i = 0, j = str.length; i < j; i++) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} +async function testAesMultiUpdate(plainText: string) { + let symAlgName = 'SM4_128'; + let length = 1024; + let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgName); + let cipherAlgName = 'SM4_128|CBC|PKCS7'; + let globalCipher = cryptoFramework.createCipher(cipherAlgName); + let result = new Uint8Array(); + let data: cryptoFramework.DataBlob; + let startEecrypt = 0; + let endEecrypt = 0; + let promiseSymKey = await symKeyGenerator.generateSymKey(); + await globalCipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, promiseSymKey, genIvParamsSpec()); + let updateOutput: cryptoFramework.DataBlob; + while (plainText.length > 0) { + const contentCurr = plainText.substring(0, length); + plainText = plainText.substring(length, plainText.length); + let messageBlob: cryptoFramework.DataBlob = { data: stringToUint8Array(contentCurr) }; + updateOutput = await globalCipher.update(messageBlob); + if (updateOutput !== null) { + let mergeText = new Uint8Array(result.length + updateOutput.data.length); + mergeText.set(result); + mergeText.set(updateOutput.data, result.length); + result = mergeText; + } + } + startEecrypt = new Date().getTime(); + data = await globalCipher.doFinal(null); + endEecrypt = new Date().getTime(); + console.info('TEST加密' + (endEecrypt - startEecrypt)); + let mergeText = new Uint8Array(result.length + data.data.length); + mergeText.set(result); + mergeText.set(data.data, result.length); + result = mergeText; + let contentTemp = result; + console.info('TEST加密成功', contentTemp); + await globalCipher.init(cryptoFramework.CryptoMode.DECRYPT_MODE, promiseSymKey, genIvParamsSpec()); + console.info('TEST == 长度' + contentTemp.length); +} +@Entry +@Component +struct SM4Encryption { + @State message: string = 'Hello World'; + aboutToAppear(): void { + testAesMultiUpdate('123456789102345566478416518498454151689546549849'); + } + build() { + RelativeContainer() { + Text(this.message) + .id('SM4EncryptionHelloWorld') + .fontSize(50) + .fontWeight(FontWeight.Bold) + .alignRules({ + center: { anchor: '__container__', align: VerticalAlign.Center }, + middle: { anchor: '__container__', align: HorizontalAlign.Center } + }) + } + .height('100%') + .width('100%') + } +} +// [End TestAesMultiUpdate] diff --git a/LocalizationKit/entry/src/main/ets/pages/CurrencyDelimiter.ets b/LocalizationKit/entry/src/main/ets/pages/CurrencyDelimiter.ets new file mode 100644 index 0000000..db05d35 --- /dev/null +++ b/LocalizationKit/entry/src/main/ets/pages/CurrencyDelimiter.ets @@ -0,0 +1,23 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:数字支持货币分隔符显示吗 +*/ + +// [Start CurrencyDelimiter] +let numfmt = new Intl.NumberFormat(); +console.info(`numfmt: ${numfmt.format(1000000)}`); +// [End CurrencyDelimiter] \ No newline at end of file diff --git a/LocalizationKit/entry/src/main/ets/pages/FileToString.ets b/LocalizationKit/entry/src/main/ets/pages/FileToString.ets new file mode 100644 index 0000000..d607ec0 --- /dev/null +++ b/LocalizationKit/entry/src/main/ets/pages/FileToString.ets @@ -0,0 +1,48 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何将文件转换成字符串 +*/ + +// [Start FileToString] +import { util } from '@kit.ArkTS'; +import { BusinessError } from '@kit.BasicServicesKit'; + +@Entry +@Component +struct FileToString { + build() { + Row() { + Column() { + Button('file to string') + .onClick(() => { + getContext().resourceManager.getRawFileContent('test.txt').then((value: Uint8Array) => { + let textDecoder: util.TextDecoder = util.TextDecoder.create(); // Call the TextDecoder class of the til module + let retStr: string = textDecoder.decodeToString(value); // 对Uint8Array解码 + let strBase64 = new util.Base64Helper().encodeToStringSync(value); + console.info('retStr:', retStr); + console.info('strBase64:', strBase64); + }).catch((error: BusinessError) => { + console.error(`callback getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`); + }); + }) + } + .width('100%') + } + .height('100%') + } +} +// [End FileToString] \ No newline at end of file diff --git a/LocalizationKit/entry/src/main/ets/pages/GetRawfile.ets b/LocalizationKit/entry/src/main/ets/pages/GetRawfile.ets new file mode 100644 index 0000000..22682f2 --- /dev/null +++ b/LocalizationKit/entry/src/main/ets/pages/GetRawfile.ets @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:在多模块工程中,如何获取har/hsp中的rawfile资源 +*/ + +// [Start GetRawfile] +import { application, common } from '@kit.AbilityKit'; +import { BusinessError } from '@kit.BasicServicesKit'; +import { buffer } from '@kit.ArkTS'; + +@Entry +@Component +struct Index { + private context = getContext(this) as common.UIAbilityContext; + + build() { + Column() { + Button('get rawFile content') + .onClick(() => { + application.createModuleContext(this.context, 'hsp') + .then((data) => { + let rawFileData = data.resourceManager.getRawFileContentSync('hsp.txt'); + let hspContent: string = buffer.from(rawFileData.buffer).toString(); + }) + .catch((error: BusinessError) => { + console.error(`createModuleContext failed, error.code: ${error.code}, error.message: ${error.message}`); + }) + }) + } + .height('100%') + .width('100%') + .justifyContent(FlexAlign.Center) + } +} +// [End GetRawfile] \ No newline at end of file diff --git a/LocalizationKit/entry/src/main/ets/pages/ToPingyin.ets b/LocalizationKit/entry/src/main/ets/pages/ToPingyin.ets new file mode 100644 index 0000000..3ead4f1 --- /dev/null +++ b/LocalizationKit/entry/src/main/ets/pages/ToPingyin.ets @@ -0,0 +1,30 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* +* FAQ:如何使用实现汉字转拼音 +*/ + +// [Start toPingYin] +import { i18n } from '@kit.LocalizationKit'; + +let transliterator = i18n.Transliterator.getInstance('Any-Latn'); +let res: string = transliterator.transform('中国'); // res = 'zhōng guó' + +// Remove voice parts +let transliterator2 = i18n.Transliterator.getInstance('Latin-ASCII'); +let res2 = transliterator2.transform(res); +console.info('去除声部后拼音为:',res2); +// [End toPingYin] \ No newline at end of file -- Gitee