解决流水线构建问题

This commit is contained in:
hwx869784 2024-03-27 16:22:35 +08:00
parent 30707e89f2
commit b7de4c8887
129 changed files with 9792 additions and 22 deletions

View File

@ -0,0 +1,27 @@
/**
* Copyright (c) 2024-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.
*/
{
"apiType": 'stageMode',
"buildOption": {
},
"entryModules": [
"entry"
],
"targets": [
{
"name": "default",
}
]
}

17
CertManager/hvigorfile.js Normal file
View File

@ -0,0 +1,17 @@
/**
* Copyright (c) 2024-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.
*/
// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
module.exports = require('@ohos/hvigor-ohos-plugin').hapTasks;

View File

@ -0,0 +1,25 @@
/**
* Copyright (c) 2024-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.
*/
{
"license": "",
"devDependencies": {},
"author": "",
"name": "certmanager",
"description": "certificate manager application",
"main": "",
"version": "1.0.0",
"dependencies": {}
}

View File

@ -14,7 +14,7 @@
*/
{
"module": {
"name": "CertificateManager",
"name": "CertManager",
"type": "feature",
"srcEntry": "./ets/MainAbility/MainAbility.ts",
"description": "$string:mainability_description",
@ -106,4 +106,4 @@
}
]
}
}
}

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 356 B

After

Width:  |  Height:  |  Size: 356 B

View File

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

Before

Width:  |  Height:  |  Size: 301 B

After

Width:  |  Height:  |  Size: 301 B

View File

Before

Width:  |  Height:  |  Size: 1.3 KiB

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

Before

Width:  |  Height:  |  Size: 1.6 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

View File

Before

Width:  |  Height:  |  Size: 681 B

After

Width:  |  Height:  |  Size: 681 B

View File

Before

Width:  |  Height:  |  Size: 6.6 KiB

After

Width:  |  Height:  |  Size: 6.6 KiB

View File

@ -0,0 +1,25 @@
/**
* Copyright (c) 2022 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.
*/
{
"app": {
"bundleName": "com.ohos.certmanager",
"vendor": "example",
"versionCode": 1000000,
"versionName": "1.0.0",
"icon": "$media:app_icon",
"label": "$string:app_name",
"distributedNotificationEnabled": true
}
}

View File

@ -0,0 +1,8 @@
{
"color": [
{
"name": "color_1",
"value": "#FFFFFF"
}
]
}

View File

@ -0,0 +1,8 @@
{
"string": [
{
"name": "app_name",
"value": "CertManager"
}
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

View File

@ -0,0 +1,70 @@
# 证书管理应用
## 简介<a name="section11660541593"></a>
证书管理应用是OpenHarmony中预置的系统应用主要的功能包含系统根证书查看与启用禁用用户根证书的安装、查看、启用禁用与卸载公共业务证书的安装、查看、授权管理与卸载私有业务证书的查看等功能。
应用架构主要结合MVP和领域驱动设计思路其架构如图1所示。
图1 证书管理应用架构图
![](doc/image/image-20220727141455437.png)
## 目录<a name="section161941989596"></a>
```
/CertManagerFa/
├── AppScope # 应用配置
├── common # 公共工具类
└── product
└── phone
└── src
└── main
├── ets # 代码目录
│   ├── Application # AbilityStage类实现
│   ├── MainAbility # Ability类实现
│   ├── model # model层功能类实现
│   ├── pages # 页面展示实现
│   ├── presenter # 页面presenter层功能类实现
│   └── stub # certManager打桩代码
└── resources # 资源文件目录
```
## 说明<a name="section1312121216216"></a>
### 使用说明<a name="section1551164914237"></a>
三方应用拉起证书管理FA并执行证书安装使用方法如下
```
globalThis.context.startAbility(
{
bundleName: "com.ohos.certmanager",
abilityName: "MainAbility",
uri: "certInstall",
})
```
三方应用拉起证书管理应用并执行申请应用授权,使用方法如下:
```
//拉起应用申请应用授权
globalThis.context.startAbilityForResult(
{
bundleName: "com.ohos.certmanager",
abilityName: "MainAbility",
uri: "requestAuthorize",
parameters: {
appUid: appUid, //传入申请应用的appUid
}
})
.then((data) => {
if (!data.resultCode) {
this.authUri = data.want.parameters.authUri; //授权成功后获取返回的authUri
}
})
```
## 相关仓<a name="section1371113476307"></a>
**security_certificate_manager**

View File

@ -1,5 +1,5 @@
/**
* Copyright (c) 2024-2024 Huawei Device Co., Ltd.
* Copyright (c) 2022 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
@ -13,15 +13,42 @@
* limitations under the License.
*/
{
"apiType": 'stageMode',
"buildOption": {
"app": {
"signingConfigs": [
{
"name": "default",
"material": {
"storePassword": "000000161B64D26AFDA336B9D4E45469670FC05C21ACB86E817B3A0EBBEF557AEC2E73906C73",
"certpath": "signature/OpenHarmonyApplication.cer",
"keyAlias": "openharmony application release",
"keyPassword": "0000001669F0585B86DCE64A21563F2E7BA5320E86297F85E75F6EA4844BFB920AD864794581",
"profile": "signature/certmanager.p7b",
"signAlg": "SHA256withECDSA",
"storeFile": "signature/OpenHarmony.p12"
}
}
],
"products": [
{
"name": "default",
"signingConfig": "default",
"compileSdkVersion": 11,
"compatibleSdkVersion": 11
}
]
},
"entryModules": [
"entry"
],
"targets": [
"modules": [
{
"name": "default",
"name": "phone",
"srcPath": "./product/phone",
"targets": [
{
"name": "default",
"applyToProducts": [
"default"
]
}
]
}
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

View File

@ -0,0 +1,21 @@
/**
* Copyright (c) 2023 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.
*/
{
"hvigorVersion": "3.0.9",
"dependencies": {
"@ohos/hvigor-ohos-plugin": "3.0.9"
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,5 @@
/**
* Copyright (c) 2024-2024 Huawei Device Co., Ltd.
* Copyright (c) 2022 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
@ -14,4 +14,4 @@
*/
// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
module.exports = require('@ohos/hvigor-ohos-plugin').hapTasks;
module.exports = require('@ohos/hvigor-ohos-plugin').appTasks;

View File

@ -0,0 +1,61 @@
# Copyright (c) 2023 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.
#!/bin/bash
# ----------------------------------------------------------------------------
# Hvigor startup script, version 1.0.0
#
# Required ENV vars:
# ------------------
# NODE_HOME - location of a Node home dir
# or
# Add /usr/local/nodejs/bin to the PATH environment variable
# ----------------------------------------------------------------------------
HVIGOR_APP_HOME="`pwd -P`"
HVIGOR_WRAPPER_SCRIPT=${HVIGOR_APP_HOME}/hvigor/hvigor-wrapper.js
warn() {
echo ""
echo -e "\033[1;33m`date '+[%Y-%m-%d %H:%M:%S]'`$@\033[0m"
}
error() {
echo ""
echo -e "\033[1;31m`date '+[%Y-%m-%d %H:%M:%S]'`$@\033[0m"
}
fail() {
error "$@"
exit 1
}
# Determine node to start hvigor wrapper script
if [ -n "${NODE_HOME}" ];then
EXECUTABLE_NODE="${NODE_HOME}/bin/node"
if [ ! -x "$EXECUTABLE_NODE" ];then
fail "ERROR: NODE_HOME is set to an invalid directory,check $NODE_HOME\n\nPlease set NODE_HOME in your environment to the location where your nodejs installed"
fi
else
EXECUTABLE_NODE="node"
which ${EXECUTABLE_NODE} > /dev/null 2>&1 || fail "ERROR: NODE_HOME is not set and not 'node' command found in your path"
fi
# Check hvigor wrapper script
if [ ! -r "$HVIGOR_WRAPPER_SCRIPT" ];then
fail "ERROR: Couldn't find hvigor/hvigor-wrapper.js in ${HVIGOR_APP_HOME}"
fi
# start hvigor-wrapper script
exec "${EXECUTABLE_NODE}" \
"${HVIGOR_WRAPPER_SCRIPT}" "$@"

View File

@ -0,0 +1,77 @@
@rem Copyright (c) 2023 Huawei Device Co., Ltd.
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem http://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Hvigor startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
set WRAPPER_MODULE_PATH=%APP_HOME%\hvigor\hvigor-wrapper.js
set NODE_EXE=node.exe
goto start
:start
@rem Find node.exe
if defined NODE_HOME goto findNodeFromNodeHome
%NODE_EXE% --version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute
echo.
echo ERROR: NODE_HOME is not set and no 'node' command could be found in your PATH.
echo.
echo Please set the NODE_HOME variable in your environment to match the
echo location of your NodeJs installation.
goto fail
:findNodeFromNodeHome
set NODE_HOME=%NODE_HOME:"=%
set NODE_EXE_PATH=%NODE_HOME%/%NODE_EXE%
if exist "%NODE_EXE_PATH%" goto execute
echo.
echo ERROR: NODE_HOME is not set and no 'node' command could be found in your PATH.
echo.
echo Please set the NODE_HOME variable in your environment to match the
echo location of your NodeJs installation.
goto fail
:execute
@rem Execute hvigor
"%NODE_EXE%" "%WRAPPER_MODULE_PATH%" %*
if "%ERRORLEVEL%" == "0" goto hvigorwEnd
:fail
exit /b 1
:hvigorwEnd
if "%OS%" == "Windows_NT" endlocal
:end

View File

@ -1,5 +1,5 @@
/**
* Copyright (c) 2024-2024 Huawei Device Co., Ltd.
* Copyright (c) 2023 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
@ -15,7 +15,9 @@
{
"license": "",
"devDependencies": {},
"devDependencies": {
"@ohos/hypium": "1.0.6"
},
"author": "",
"name": "certificate manager application",
"description": "certificate manager application",

View File

@ -0,0 +1,3 @@
/node_modules
/.preview
/build

View File

@ -0,0 +1,24 @@
/**
* Copyright (c) 2022-2023 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.
*/
{
"apiType": 'stageMode',
"buildOption": {
},
"targets": [
{
"name": "default",
}
]
}

View File

@ -0,0 +1,17 @@
/**
* Copyright (c) 2022 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.
*/
// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently.
module.exports = require('@ohos/hvigor-ohos-plugin').hapTasks;

View File

@ -0,0 +1,25 @@
/**
* Copyright (c) 2023 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.
*/
{
"license": "",
"devDependencies": {},
"author": "",
"name": "certificate manager application",
"description": "certificate manager application",
"main": "",
"version": "1.0.0",
"dependencies": {}
}

View File

@ -0,0 +1,192 @@
/*
* Copyright (c) 2022 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.
*/
export interface AsyncCallback<T, E = void> {
(err: BusinessError<E>, data: T): void;
}
export interface BusinessError<T = void> extends Error {
code: number;
data?: T;
}
declare namespace CertManagerFunc {
function getSystemTrustedCertificateList(callback: AsyncCallback<CMResult>) : void;
function getSystemTrustedCertificateList() : Promise<CMResult>;
function getSystemTrustedCertificate(certUri: string, callback: AsyncCallback<CMResult>) : void;
function getSystemTrustedCertificate(certUri: string) : Promise<CMResult>;
function setCertificateStatus(certUri: string, store: number, status: boolean, callback: AsyncCallback<boolean>) : void;
function setCertificateStatus(certUri: string, store: number, status: boolean) : Promise<boolean>;
function installUserTrustedCertificate(certificate: CertBlob, callback: AsyncCallback<CMResult>) : void;
function installUserTrustedCertificate(certificate: CertBlob,) : Promise<CMResult>;
function uninstallAllUserTrustedCertificate(callback: AsyncCallback<boolean>) : void;
function uninstallAllUserTrustedCertificate() : Promise<boolean>;
function uninstallUserTrustedCertificate(certUri: string, callback: AsyncCallback<boolean>) : void;
function uninstallUserTrustedCertificate(certUri: string) : Promise<boolean>;
function getUserTrustedCertificateList(callback: AsyncCallback<CMResult>) : void;
function getUserTrustedCertificateList() : Promise<CMResult>;
function getUserTrustedCertificate(certUri: string, callback: AsyncCallback<CMResult>) : void;
function getUserTrustedCertificate(certUri: string) : Promise<CMResult>;
function installAppCertificate(keystore: Uint8Array, keystorePwd: string, certAlias: string, callback: AsyncCallback<CMResult>) : void;
function installAppCertificate(keystore: Uint8Array, keystorePwd: string, certAlias: string) : Promise<CMResult>;
function installPrivateCertificate(keystore: Uint8Array, keystorePwd: string, certAlias: string, callback: AsyncCallback<CMResult>) : void;
function installPrivateCertificate(keystore: Uint8Array, keystorePwd: string, certAlias: string) : Promise<CMResult>;
function generatePrivateCertificate(keyAlias: string, keyProperties: CMKeyProperties, callback: AsyncCallback<CMResult>) : void;
function generatePrivateCertificate(keyAlias: string, keyProperties: CMKeyProperties) : Promise<CMResult>;
function updatePrivateCertificate(type: string, keyUri: string, certificate: CertBlob, callback: AsyncCallback<boolean>) : void;
function updatePrivateCertificate(type: string, keyUri: string, certificate: CertBlob) : Promise<boolean>;
function uninstallAllAppCertificate(callback: AsyncCallback<boolean>) : void;
function uninstallAllAppCertificate() : Promise<boolean>;
function uninstallAppCertificate(keyUri: string, callback: AsyncCallback<boolean>) : void;
function uninstallAppCertificate(keyUri: string) : Promise<boolean>;
function uninstallPrivateCertificate(keyUri: string, callback: AsyncCallback<boolean>) : void;
function uninstallPrivateCertificate(keyUri: string) : Promise<boolean>;
function getAppCertificateList(callback: AsyncCallback<CMResult>) : void;
function getAppCertificateList() : Promise<CMResult>;
function getPrivateCertificateList(callback: AsyncCallback<CMResult>) : void;
function getPrivateCertificateList() : Promise<CMResult>;
function getAppCertificate(keyUri: string, callback: AsyncCallback<CMResult>) : void;
function getAppCertificate(keyUri: string, ) : Promise<CMResult>;
function getPrivateCertificate(keyUri: string, callback: AsyncCallback<CMResult>) : void;
function getPrivateCertificate(keyUri: string) : Promise<CMResult>;
function grantAppCertificate(keyUri: string, clientAppUid: string, callback: AsyncCallback<CMResult>) : void;
function grantAppCertificate(keyUri: string, clientAppUid: string) : Promise<CMResult>;
function isAuthorizedApp(keyUri: string, callback: AsyncCallback<boolean>) : void;
function isAuthorizedApp(keyUri: string) : Promise<boolean>;
function getAuthorizedAppList(keyUri: string, callback: AsyncCallback<CMResult>) : void;
function getAuthorizedAppList(keyUri: string) : Promise<CMResult>;
function removeGrantedAppCertificate(keyUri: string, clientAppUid: string, callback: AsyncCallback<boolean>) : void;
function removeGrantedAppCertificate(keyUri: string, clientAppUid: string) : Promise<boolean>;
function init(authUri: string, spec: CMSignatureSpec, callback: AsyncCallback<CMHandle>) : void;
function init(authUri: string, spec: CMSignatureSpec) : Promise<CMHandle>;
function update(handle: Uint8Array, data: Uint8Array, callback: AsyncCallback<boolean>) : void;
function update(handle: Uint8Array, data: Uint8Array) : Promise<boolean>;
function finish(handle: Uint8Array, callback: AsyncCallback<CMResult>) : void;
function finish(handle: Uint8Array, signature: Uint8Array, callback: AsyncCallback<CMResult>) : void;
function finish(handle: Uint8Array, signature?: Uint8Array) : Promise<CMResult>;
function abort(handle: Uint8Array, callback: AsyncCallback<boolean>) : void;
function abort(handle: Uint8Array) : Promise<boolean>;
export interface CertInfo {
uri: string;
certAlias: string;
status: boolean;
issuerName: string;
subjectName: string;
serial: string;
notBefore: string;
notAfter: string;
fingerprintSha256: string;
cert: Uint8Array;
}
export interface CertAbstract {
uri: string;
certAlias: string;
status: boolean;
subjectName: string;
}
export interface Credential {
type: string;
alias: string;
keyUri: string;
certNum: number;
keyNum: number;
credData:Uint8Array;
}
export interface CredentialAbstract {
type: string;
alias: string;
keyUri: string;
}
export interface CertBlob {
inData: Uint8Array;
alias: string;
}
export interface CMResult {
certList?: Array<CertAbstract>;
certInfo?: CertInfo;
credentialList?: Array<CredentialAbstract>;
credential?: Credential;
appUidList?: Array<string>;
uri?: string;
outData?: Uint8Array;
isAuth?: boolean;
}
export interface CMKeyProperties {
type: string;
alg: string;
size: number;
padding: string;
purpose: string;
digest: string;
authType: string;
authTimeout: string;
}
export enum CmKeyPurpose {
CM_KEY_PURPOSE_SIGN = 4,
CM_KEY_PURPOSE_VERIFY = 8,
}
export interface CMSignatureSpec {
purpose: CmKeyPurpose;
}
export interface CMHandle {
handle: Uint8Array;
}
export enum CMErrorCode {
CM_SUCCESS = 0,
CM_ERROR_INNER_ERROR = 17500001,
CM_ERROR_NO_PERMISSION = 17500002,
CM_ERROR_NO_FOUND = 17500003,
CM_ERROR_X509_FORMATE = 17500004,
}
}
export default CertManagerFunc;

View File

@ -0,0 +1,22 @@
/**
* Copyright (c) 2022 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 AbilityStage from '@ohos.app.ability.AbilityStage';
export default class MyAbilityStage extends AbilityStage {
onCreate(): void {
console.log('[Demo] MyAbilityStage onCreate');
}
}

View File

@ -0,0 +1,64 @@
/**
* Copyright (c) 2022 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 Ability from '@ohos.app.ability.UIAbility';
import type Want from '@ohos.app.ability.Want';
import type Window from '@ohos.window';
import { GlobalContext, PwdStore } from '../common/GlobalContext';
export default class MainAbility extends Ability {
onCreate(want: Want, launchParam): void {
console.log('[Demo] MainAbility onCreate');
let pwdStore = new PwdStore();
GlobalContext.getContext().setCmContext(this.context);
GlobalContext.getContext().setPwdStore(pwdStore);
GlobalContext.getContext().setAbilityWant(want);
}
onDestroy(): void {
console.log('[Demo] MainAbility onDestroy');
}
onWindowStageCreate(windowStage: Window.WindowStage): void {
// Main window is created, set main page for this ability
console.log('[Demo] MainAbility onWindowStageCreate');
windowStage.loadContent('pages/certManagerFa', (err, data) => {
if (err.code) {
console.error('onWindowStageCreate failed, cause:' + JSON.stringify(err));
return;
}
});
}
onWindowStageDestroy(): void {
// Main window is destroyed, release UI related resources
console.log('[Demo] MainAbility onWindowStageDestroy');
}
onForeground(): void {
// Ability has brought to foreground
console.log('[Demo] MainAbility onForeground');
}
onBackground(): void {
// Ability has back to background
console.log('[Demo] MainAbility onBackground');
}
onNewWant(want: Want): void {
console.log('[Demo] MainAbility onNewWant');
GlobalContext.getContext().setAbilityWant(want);
}
};

View File

@ -0,0 +1,75 @@
/*
* Copyright (c) 2023 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 type Want from '@ohos.app.ability.Want';
import type UIAbilityContext from 'application/UIAbilityContext';
export class PwdStore {
private certPwd: string = '';
setCertPwd(pwd: string): void {
this.certPwd = pwd;
}
getCertPwd(): string {
return this.certPwd;
}
clearCertPwd(): void {
this.certPwd = '';
}
}
export class GlobalContext {
private constructor() {};
private static instance: GlobalContext;
private context: UIAbilityContext;
private want: Want;
private pwdStore: PwdStore;
public static getContext(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
getCmContext(): UIAbilityContext {
return this.context;
}
getPwdStore(): PwdStore {
return this.pwdStore;
}
getAbilityWant(): Want {
return this.want;
}
setCmContext(context: UIAbilityContext): void {
this.context = context;
}
setPwdStore(pwdStore: PwdStore): void {
this.pwdStore = pwdStore;
}
setAbilityWant(want: Want): void {
this.want = want;
}
clearAbilityWantUri(): void {
this.want.uri = '';
}
}

View File

@ -0,0 +1,37 @@
/**
* Copyright (c) 2022-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.
*/
export class ComponentConfig {
public WH_100_100 = '100%';
public WH_30_100 = '30%';
public WH_33_100 = '33%';
public WH_35_100 = '35%';
public WH_40_100 = '40%';
public WH_45_100 = '45%';
public WH_50_100 = '50%';
public WH_55_100 = '55%';
public WH_83_100 = '83%';
public WH_90_100 = '90%';
public value_20 = 20;
public font_20 = 20;
public MAX_LINES_1 = 1;
public MAX_LINES_2 = 2;
public MAX_LINES_3 = 3;
public DURATION_TIME = 200;
}
let componentConfig = new ComponentConfig();
export default componentConfig as ComponentConfig;

View File

@ -0,0 +1,74 @@
/**
* Copyright (c) 2022-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 ComponentConfig from './ComponentConfig';
import Router from '@ohos.router';
import { GlobalContext } from '../GlobalContext';
const TAG = 'CertManager HeadComponent: ';
/**
* head custom component
*/
@Component
export default struct HeadComponent {
private icBackIsVisibility: boolean = true;
private headName: string | Resource = '';
@State isTouch: boolean = false;
build() {
Row() {
Stack({ alignContent: Alignment.Center }) {
Image($r('app.media.ic_back'))
.width($r('app.float.wh_value_24'))
.height($r('app.float.wh_value_24'))
.fillColor($r('sys.color.ohos_id_color_primary'))
}
.margin({ right: $r('app.float.wh_value_16') })
.backgroundColor(this.isTouch ? $r('app.color.color_E3E3E3_grey') : $r('app.color.color_00000000_transparent'))
.visibility(this.icBackIsVisibility ? Visibility.Visible : Visibility.None)
.onClick(() => {
let length = Router.getLength();
console.log(TAG + 'router length: ' + Number(length));
Number(length) == 1 ? GlobalContext.getContext().getCmContext().terminateSelf() : Router.back();
})
.onTouch((event?: TouchEvent) => {
if (event !== undefined) {
if (event.type === TouchType.Down) {
this.isTouch = true;
}
if (event.type === TouchType.Up) {
this.isTouch = false;
}
}
});
Text(this.headName)
.fontSize($r('app.float.head_font_20'))
.lineHeight($r('app.float.wh_value_33'))
.fontFamily('HarmonyHeiTi-Bold')
.fontWeight(FontWeight.Regular)
.fontColor($r('app.color.font_color_182431'))
.maxLines(ComponentConfig.MAX_LINES_1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.textAlign(TextAlign.Start)
.margin({ top: $r('app.float.wh_value_13'), bottom: $r('app.float.wh_value_15') });
}
.width(ComponentConfig.WH_100_100)
.padding({ left: $r('app.float.wh_value_12') })
.height($r('app.float.wh_value_56'))
.alignItems(VerticalAlign.Center)
.align(Alignment.Start)
}
}

View File

@ -0,0 +1,144 @@
/**
* Copyright (c) 2022-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 ComponentConfig from './ComponentConfig';
/**
* Sub-Page Entry Component
*/
@Component
export struct SubEntryComponent {
private targetPage: string = '';
private title: string | Resource = '';
@State isTouched: boolean = false;
build() {
Navigator({ target: this.targetPage }) {
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
Row() {
Text(this.title)
.fontSize($r('app.float.font_16'))
.lineHeight($r('app.float.wh_value_22'))
.fontColor($r('app.color.font_color_182431'))
.fontWeight(FontWeight.Medium)
.margin({ left: $r('app.float.wh_value_8') })
.textAlign(TextAlign.Start);
}
Image($r('app.media.ic_settings_arrow'))
.width($r('app.float.wh_value_12'))
.height($r('app.float.wh_value_24'))
.fillColor($r('sys.color.ohos_id_color_primary'))
.opacity($r('app.float.opacity_0_2'))
.margin({ right: $r('app.float.wh_value_8') });
}
.borderRadius($r('app.float.radius_20'))
.height(ComponentConfig.WH_100_100)
.width(ComponentConfig.WH_100_100)
.linearGradient(this.isTouched ? {
angle: 90,
direction: GradientDirection.Right,
colors: [[$r('app.color.DCEAF9'), 0.0], [$r('app.color.FAFAFA'), 1.0]]
} : {
angle: 90,
direction: GradientDirection.Right,
colors: [[$r('sys.color.ohos_id_color_foreground_contrary'), 1],
[$r('sys.color.ohos_id_color_foreground_contrary'), 1]]
})
.onTouch((event?: TouchEvent) => {
if (event !== undefined) {
if (event.type === TouchType.Down) {
this.isTouched = true;
}
if (event.type === TouchType.Up) {
this.isTouched = false;
}
}
})
}
.height($r('app.float.wh_value_48'))
.backgroundColor($r('sys.color.ohos_id_color_foreground_contrary'));
}
}
/**
* Sub-Page Entry Component with EndText
*/
@Component
export struct SubEntryComponentWithEndText {
@State isTouched: boolean = false;
@Prop endText: string = '';
private targetPage: string = '';
private title: string | Resource = '';
build() {
Navigator({ target: this.targetPage }) {
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
Row() {
Text(this.title)
.fontSize($r('app.float.font_16'))
.lineHeight($r('app.float.wh_value_22'))
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.font_color_182431'))
.margin({ left: $r('app.float.distance_8') })
.textAlign(TextAlign.Start);
}
Row() {
Text(this.endText)
.fontSize($r('app.float.font_14'))
.lineHeight($r('app.float.wh_value_19'))
.fontWeight(FontWeight.Regular)
.fontColor($r('sys.color.ohos_id_color_text_secondary'))
.margin({ right: $r('app.float.distance_4') })
.textAlign(TextAlign.End);
Image('/res/image/ic_settings_arrow.svg')
.width($r('app.float.wh_value_12'))
.height($r('app.float.wh_value_24'))
.margin({ right: $r('app.float.distance_8') })
.fillColor($r('sys.color.ohos_id_color_primary'))
.opacity($r('app.float.opacity_0_2'))
}
}
.height(ComponentConfig.WH_100_100)
.width(ComponentConfig.WH_100_100)
.borderRadius($r('app.float.radius_20'))
.linearGradient(this.isTouched ? {
angle: 90,
direction: GradientDirection.Right,
colors: [[$r('app.color.DCEAF9'), 0.0], [$r('app.color.FAFAFA'), 1.0]]
} : {
angle: 90,
direction: GradientDirection.Right,
colors: [[$r('sys.color.ohos_id_color_foreground_contrary'), 1],
[$r('sys.color.ohos_id_color_foreground_contrary'), 1]]
})
.onTouch((event?: TouchEvent) => {
if (event !== undefined) {
if (event.type === TouchType.Down) {
this.isTouched = true;
}
if (event.type === TouchType.Up) {
this.isTouched = false;
}
}
});
}
.padding($r('app.float.distance_4'))
.height($r('app.float.wh_value_56'))
.borderRadius($r('app.float.radius_24'))
.backgroundColor($r('sys.color.ohos_id_color_foreground_contrary'));
}
}

View File

@ -0,0 +1,55 @@
/**
* Copyright (c) 2022-2023 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.
*/
export enum WidthPercent {
WH_100_100 = '100%',
WH_3_100 = '3%',
WH_4_100 = '4%',
WH_20_100 = '20%',
WH_25_100 = '25%',
WH_30_100 = '30%',
WH_33_100 = '33%',
WH_35_100 = '35%',
WH_40_100 = '40%',
WH_43_100 = '43%',
WH_45_100 = '45%',
WH_50_100 = '50%',
WH_53_100 = '53%',
WH_55_100 = '55%',
WH_60_100 = '60%',
WH_65_100 = '65%',
WH_70_100 = '70%',
WH_75_100 = '75%',
WH_80_100 = '80%',
WH_85_100 = '85%',
WH_88_100 = '88%',
WH_90_100 = '90%',
WH_92_100 = '92%',
WH_93_100 = '93%',
WH_94_100 = '94%'
};
export enum LocationChoice {
SWITCH_BUTTON_X_OFFSET = '-4vp',
DIALOG_DY_OFFSET = '-16vp'
};
export enum ConfigValue {
PWD_MAX_LENGTH = 64,
ALIAS_MAX_LENGTH = 64,
APP_AUTH_MAX_LENGTH = 4,
REQUEST_AUTH_MAX_LENGTH = 5,
VERTICAL_DIVIDER_WIDTH = 1
};

View File

@ -0,0 +1,53 @@
/**
* Copyright (c) 2022-2023 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 bundleManager from '@ohos.bundle.bundleManager';
import bundleResManager from '@ohos.bundle.bundleResourceManager';
import { CMModelErrorCode } from '../model/CertMangerModel';
import { AppInfoVo } from './CertManagerVo/AppInfoVo';
import { BusinessError } from '@ohos.base';
const TAG = 'certManager BUNDLE:';
export class BundleNameModel {
async getAppInfoList(appUid: number, callback: Function): Promise<void> {
console.log(TAG + 'getAppInfoList enter uid: ' + appUid);
try {
let appInfo: AppInfoVo = {
appImage: '',
appName: '',
};
let appBundleName = await bundleManager.getBundleNameByUid(appUid);
console.log(TAG + 'appBundleName: ' + appBundleName);
let bundleFlags = bundleResManager.ResourceFlag.GET_RESOURCE_INFO_ALL;
let resourceInfo = bundleResManager.getBundleResourceInfo(appBundleName, bundleFlags);
appInfo.appName = resourceInfo.label;
appInfo.appImage = resourceInfo.icon;
console.log(TAG + 'get bundle info success');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS, appInfo);
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'getAppInfoList failed, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION, undefined);
}
}
}
let bundleNameModel = new BundleNameModel();
export default bundleNameModel as BundleNameModel;

View File

@ -0,0 +1,28 @@
/**
* Copyright (c) 2022-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.
*/
export class AppAuthorVo {
public appImage: string;
public uid: string;
public appName: string;
public status: boolean;
constructor(appImage: string, uid: string, appName: string, status: boolean) {
this.appImage = appImage;
this.uid = uid;
this.appName = appName;
this.status = status;
}
}

View File

@ -0,0 +1,19 @@
/**
* Copyright (c) 2023-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.
*/
export class AppInfoVo {
public appImage: string = '';
public appName: string = '';
}

View File

@ -0,0 +1,30 @@
/**
* Copyright (c) 2022-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.
*/
export class CertAbstractVo {
public uri: string;
public certAlias: string;
public status: boolean;
public subjectName: string;
public subjectNameCN : string;
constructor(uri: string, certAlias: string, status: boolean, subjectName: string, subjectNameCN: string) {
this.uri = uri;
this.certAlias = certAlias;
this.status = status;
this.subjectName = subjectName;
this.subjectNameCN = subjectNameCN;
}
}

View File

@ -0,0 +1,75 @@
/**
* Copyright (c) 2022-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.
*/
export class CertInfoVo {
public uri: string;
public certAlias: string;
public status: boolean;
public issuerName: string;
public subjectName: string;
public serial: string;
public notBefore: string;
public notAfter: string;
public fingerprintSha256: string;
public cert: Uint8Array;
public subjectNameMap :Map<string, string>;
public issuerNameMap :Map<string, string>;
public dateMap :Map<string, string>;
constructor(
uri: string,
certAlias: string,
status: boolean,
issuerName: string,
subjectName: string,
serial: string,
notBefore: string,
notAfter: string,
fingerprintSha256: string,
cert: Uint8Array,
subjectNameMap: Map<string, string>,
issuerNameMap :Map<string, string>,
dateMap :Map<string, string>) {
this.uri = uri;
this.certAlias = certAlias;
this.status = status;
this.issuerName = issuerName;
this.subjectName = subjectName;
this.serial = serial;
this.notBefore = notBefore;
this.notAfter = notAfter;
this.fingerprintSha256 = fingerprintSha256;
this.cert = cert;
this.subjectNameMap = subjectNameMap;
this.issuerNameMap = issuerNameMap;
this.dateMap = dateMap;
}
clearCertInfoVo(): void {
this.uri = '';
this.certAlias = '';
this.status = false;
this.issuerName = '';
this.subjectName = '';
this.serial = '';
this.notBefore = '';
this.notAfter = '';
this.fingerprintSha256 = '';
this.cert = new Uint8Array();
this.subjectNameMap.clear();
this.issuerNameMap.clear();
this.dateMap.clear();
}
}

View File

@ -0,0 +1,26 @@
/**
* Copyright (c) 2022-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.
*/
export class CredentialAbstractVo {
public credType: string;
public alias: string;
public keyUri: string;
constructor(credType: string, alias: string, keyUri: string) {
this.credType = credType;
this.alias = alias;
this.keyUri = keyUri;
}
}

View File

@ -0,0 +1,41 @@
/**
* Copyright (c) 2022-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.
*/
export class CredentialVo {
public credType: string;
public alias: string;
public keyUri: string;
public certNum: number;
public keyNum: number;
public credData: Uint8Array;
constructor(credType: string, alias: string, keyUri: string, certNum: number, keyNum: number, credData: Uint8Array) {
this.credType = credType;
this.alias = alias;
this.keyUri = keyUri;
this.certNum = certNum;
this.keyNum = keyNum;
this.credData = credData;
}
clearCredentialVo(): void {
this.credType = '';
this.alias = '';
this.keyUri = '';
this.certNum = 0;
this.keyNum = 0;
this.credData = new Uint8Array();
}
}

View File

@ -0,0 +1,32 @@
/**
* 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.
*/
export class RouterAppUidVo {
public appUid: string;
constructor(appUid: string) {
this.appUid = appUid;
}
}
export class RouterFileVo {
public uri: string;
public suffix: string;
constructor(uri: string, suffix: string) {
this.uri = uri;
this.suffix = suffix;
}
}

View File

@ -0,0 +1,676 @@
/**
* Copyright (c) 2022-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 { CertAbstractVo } from './CertManagerVo/CertAbstractVo';
import { CertInfoVo } from './CertManagerVo/CertInfoVo';
import { CredentialAbstractVo } from './CertManagerVo/CredentialAbstractVo';
import { CredentialVo } from './CertManagerVo/CredentialVo';
import { BusinessError } from '@ohos.base';
import CertManager from '@ohos.security.certManager';
const TAG = 'CertManager Model: ';
export enum CMModelErrorCode {
CM_MODEL_ERROR_SUCCESS = 0,
CM_MODEL_ERROR_FAILED = -1,
CM_MODEL_ERROR_EXCEPTION = -2,
CM_MODEL_ERROR_UNKNOWN_OPT = -3,
CM_MODEL_ERROR_NOT_SUPPORT = -4,
}
export enum CMModelOptType {
CM_MODEL_OPT_UNKNOWN = 0,
CM_MODEL_OPT_SYSTEM_CA = 1,
CM_MODEL_OPT_USER_CA = 2,
CM_MODEL_OPT_APP_CRED = 3,
CM_MODEL_OPT_PRIVATE_CRED = 4,
}
export enum CertManagerStore {
/* credential certificate store for end entity certificates. */
CERT_MANAGER_CREDENTIAL_STORE = 0,
/* read only, updated by system only. */
CERT_MANAGER_SYSTEM_TRUSTED_STORE = 1,
/* modifiable by applications and user. */
CERT_MANAGER_USER_TRUSTED_STORE = 2,
/* application specific trusted certificate store; modifiable by the application only. */
CERT_MANAGER_APPLICATION_TRUSTED_STORE = 3,
}
export class CertMangerModel {
getCertOrCredList(optType: CMModelOptType, callback: Function): void {
console.log(TAG + 'getCertOrCredList start');
switch (optType) {
case CMModelOptType.CM_MODEL_OPT_SYSTEM_CA:
this.getSystemTrustedCertificateList((errCode:CMModelErrorCode, certList: Array<CertAbstractVo>) => {
callback(errCode, certList);
});
break;
case CMModelOptType.CM_MODEL_OPT_USER_CA:
this.getUserTrustedCertificateList((errCode: CMModelErrorCode, certList: Array<CertAbstractVo>) => {
callback(errCode, certList);
});
break;
case CMModelOptType.CM_MODEL_OPT_APP_CRED:
this.getAppCredList((errCode: CMModelErrorCode, credList: Array<CredentialAbstractVo>) => {
callback(errCode, credList);
});
break;
case CMModelOptType.CM_MODEL_OPT_PRIVATE_CRED:
this.getPrivateCredList((errCode: CMModelErrorCode, credList: Array<CredentialAbstractVo>) => {
callback(errCode, credList);
});
break;
default:
callback(CMModelErrorCode.CM_MODEL_ERROR_UNKNOWN_OPT, undefined);
break;
}
}
getCertOrCred(optType: CMModelOptType, uri: string, callback: Function): void {
console.log(TAG + 'getCertOrCred start');
switch (optType) {
case CMModelOptType.CM_MODEL_OPT_SYSTEM_CA:
this.getSystemTrustedCertificate(uri, (errCode: CMModelErrorCode, certInfo: CertInfoVo) => {
console.info('getSystemTrustedCertificate certInfo is' + JSON.stringify(certInfo));
callback(errCode, certInfo);
});
break;
case CMModelOptType.CM_MODEL_OPT_USER_CA:
this.getUserTrustedCertificate(uri, (errCode: CMModelErrorCode, certInfo: CertInfoVo) => {
callback(errCode, certInfo);
});
break;
case CMModelOptType.CM_MODEL_OPT_APP_CRED:
this.getAppCredential(uri, (errCode: CMModelErrorCode, credInfo: CredentialVo) => {
callback(errCode, credInfo);
});
break;
case CMModelOptType.CM_MODEL_OPT_PRIVATE_CRED:
this.getPrivateCred(uri, (errCode: CMModelErrorCode, credInfo: CredentialVo) => {
callback(errCode, credInfo);
});
break;
default:
callback(CMModelErrorCode.CM_MODEL_ERROR_UNKNOWN_OPT, undefined);
break;
}
}
deleteCertOrCred(optType: CMModelOptType, uri: string, callback: Function): void {
console.log(TAG + 'deleteCertOrCred start');
switch (optType) {
case CMModelOptType.CM_MODEL_OPT_USER_CA:
this.deleteUserTrustedCertificate(uri, (errCode: CMModelErrorCode) => {
callback(errCode);
});
break;
case CMModelOptType.CM_MODEL_OPT_APP_CRED:
this.deleteAppCredential(uri, (errCode: CMModelErrorCode) => {
callback(errCode);
});
break;
case CMModelOptType.CM_MODEL_OPT_SYSTEM_CA:
case CMModelOptType.CM_MODEL_OPT_PRIVATE_CRED:
callback(CMModelErrorCode.CM_MODEL_ERROR_NOT_SUPPORT);
break;
default:
callback(CMModelErrorCode.CM_MODEL_ERROR_UNKNOWN_OPT);
break;
}
}
setCertStatus(optType: CMModelOptType, uri: string, status: boolean, callback: Function): void {
console.log(TAG + 'setCertStatus start');
switch (optType) {
case CMModelOptType.CM_MODEL_OPT_USER_CA:
this.setCertificateStatus(uri, CertManagerStore.CERT_MANAGER_USER_TRUSTED_STORE, status,
(errCode: CMModelErrorCode) => {
callback(errCode);
});
break;
case CMModelOptType.CM_MODEL_OPT_SYSTEM_CA:
this.setCertificateStatus(uri, CertManagerStore.CERT_MANAGER_SYSTEM_TRUSTED_STORE, status,
(errCode: CMModelErrorCode) => {
callback(errCode);
});
break;
case CMModelOptType.CM_MODEL_OPT_APP_CRED:
case CMModelOptType.CM_MODEL_OPT_PRIVATE_CRED:
callback(CMModelErrorCode.CM_MODEL_ERROR_NOT_SUPPORT);
break;
default:
callback(CMModelErrorCode.CM_MODEL_ERROR_UNKNOWN_OPT);
break;
}
}
delAllCertOrCred(optType: CMModelOptType, callback: Function): void {
console.log(TAG + 'delAllCertOrCred start');
switch (optType) {
case CMModelOptType.CM_MODEL_OPT_USER_CA:
this.delAllUserCertificate((errCode: CMModelErrorCode) => {
callback(errCode);
});
break;
case CMModelOptType.CM_MODEL_OPT_APP_CRED:
this.delAllAppCredential((errCode: CMModelErrorCode) => {
callback(errCode);
});
break;
case CMModelOptType.CM_MODEL_OPT_SYSTEM_CA:
case CMModelOptType.CM_MODEL_OPT_PRIVATE_CRED:
callback(CMModelErrorCode.CM_MODEL_ERROR_NOT_SUPPORT);
break;
default:
callback(CMModelErrorCode.CM_MODEL_ERROR_UNKNOWN_OPT);
break;
}
}
getAuthAppList(optType: CMModelOptType, uri: string, callback: Function): void {
console.log(TAG + 'getAuthAppList start');
switch (optType) {
case CMModelOptType.CM_MODEL_OPT_APP_CRED:
this.getAuthorizedAppList(uri, (errCode: CMModelErrorCode, appUidList: Array<string>) => {
callback(errCode, appUidList);
});
break;
case CMModelOptType.CM_MODEL_OPT_USER_CA:
case CMModelOptType.CM_MODEL_OPT_SYSTEM_CA:
case CMModelOptType.CM_MODEL_OPT_PRIVATE_CRED:
callback(CMModelErrorCode.CM_MODEL_ERROR_NOT_SUPPORT);
break;
default:
callback(CMModelErrorCode.CM_MODEL_ERROR_UNKNOWN_OPT);
break;
}
}
setAppAuthPromise(optType: CMModelOptType, uri: string, appUid: string, status: boolean): Promise<void> {
console.log(TAG + 'setAppAuth start');
switch (optType) {
case CMModelOptType.CM_MODEL_OPT_APP_CRED:
return new Promise((resolve, reject)=>{
this.setAuthorizedAppStatus(uri, appUid, status, (errCode: CMModelErrorCode, data: string) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
resolve(void(data));
} else {
reject(errCode);
}
});
});
default:
return new Promise((resolve, reject) => {
reject(CMModelErrorCode.CM_MODEL_ERROR_UNKNOWN_OPT);
});
}
}
setAppAuth(optType: CMModelOptType, uri: string, appUid: string, status: boolean, callback: Function): void {
console.log(TAG + 'setAppAuth start');
switch (optType) {
case CMModelOptType.CM_MODEL_OPT_APP_CRED:
this.setAuthorizedAppStatus(uri, appUid, status, (errCode: CMModelErrorCode, data: string) => {
callback(errCode, data);
});
break;
case CMModelOptType.CM_MODEL_OPT_USER_CA:
case CMModelOptType.CM_MODEL_OPT_SYSTEM_CA:
case CMModelOptType.CM_MODEL_OPT_PRIVATE_CRED:
callback(CMModelErrorCode.CM_MODEL_ERROR_NOT_SUPPORT);
break;
default:
callback(CMModelErrorCode.CM_MODEL_ERROR_UNKNOWN_OPT);
break;
}
}
installCertOrCred(optType: CMModelOptType, alias: string, data: Uint8Array, pwd: string, callback: Function): void {
console.log(TAG + 'installCertOrCred start');
console.info(TAG + 'installCert optType: ' + optType + ',alias: ' + alias);
switch (optType) {
case CMModelOptType.CM_MODEL_OPT_USER_CA:
this.installUserCertificate(data, alias, (errCode: CMModelErrorCode) => {
callback(errCode);
});
break;
case CMModelOptType.CM_MODEL_OPT_APP_CRED:
this.installAppCertificate(data, alias, pwd, (errCode: CMModelErrorCode) => {
callback(errCode);
});
break;
case CMModelOptType.CM_MODEL_OPT_PRIVATE_CRED:
case CMModelOptType.CM_MODEL_OPT_SYSTEM_CA:
callback(CMModelErrorCode.CM_MODEL_ERROR_NOT_SUPPORT);
break;
default:
callback(CMModelErrorCode.CM_MODEL_ERROR_UNKNOWN_OPT);
break;
}
}
private async getSystemTrustedCertificateList(callback: Function): Promise<void> {
console.log(TAG + 'getSystemTrustedCertificateList start');
try {
let subjectNameCN: string = '';
let result = await CertManager.getSystemTrustedCertificateList();
let certList: CertAbstractVo[] = [];
let regex: RegExp = new RegExp('(?<=CN=).*?(?=,)', 'g');
if (result.certList !== undefined) {
console.log(TAG + 'certManager::getSystemTrustedCertificateList result: ' + JSON.stringify(result));
for (let i = 0; i < result.certList.length; i++) {
if (result.certList[i].subjectName.length !== 0) {
let temp = result.certList[i].subjectName.match(regex);
subjectNameCN = (temp !== undefined) ? String(temp) : '';
console.info('subjectNameCN is:' + subjectNameCN);
}
certList.push(new CertAbstractVo(String(result.certList[i].uri), String(result.certList[i].certAlias),
Boolean(result.certList[i].status), String(result.certList[i].subjectName), String(subjectNameCN)));
}
console.log(TAG + 'getSystemTrustedCertificateList end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS, certList);
} else {
console.error(TAG + 'getSystemTrustedCertificateList failed, undefined');
callback(CMModelErrorCode.CM_MODEL_ERROR_FAILED, undefined);
}
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'getSystemTrustedCertificateList err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION, undefined);
}
}
private async getSystemTrustedCertificate(certUri: string, callback: Function): Promise<void> {
console.log(TAG + 'getSystemTrustedCertificate start');
try {
let result = await CertManager.getSystemTrustedCertificate(certUri);
let subjectNameMap: Map<string, string> = new Map();
let issuerNameMap: Map<string, string> = new Map();
let dateMap: Map<string, string> = new Map();
let regex1: RegExp = new RegExp('(?<=CN=).*?(?=,)', 'g');
let regex2: RegExp = new RegExp('(?<=OU=).*?(?=,)', 'g');
let regex3: RegExp = new RegExp('(?<=O=).*', 'g');
if (result.certInfo !== undefined) {
if (result.certInfo.subjectName.length !== 0) {
let subjectNameCN = result.certInfo.subjectName.match(regex1);
console.info('subjectNameCN is:' + subjectNameCN);
let subjectNameOU = result.certInfo.subjectName.match(regex2);
console.info('subjectNameOU is:' + subjectNameOU);
let subjectNameO = result.certInfo.subjectName.match(regex3);
console.info('subjectNameO is:' + subjectNameO);
subjectNameMap.set('常用名称:', String(subjectNameCN));
subjectNameMap.set('组织:', String(subjectNameO));
subjectNameMap.set('组织单位:', String(subjectNameOU));
subjectNameMap.set('序列号:', String(result.certInfo.serial));
}
if (result.certInfo.issuerName.length !== 0) {
let issuerNameCN = result.certInfo.issuerName.match(regex1);
console.info('issuerNameCN is:' + issuerNameCN);
let issuerNameOU = result.certInfo.issuerName.match(regex2);
console.info('issuerNameOU is:' + issuerNameOU);
let issuerNameO = result.certInfo.issuerName.match(regex3);
console.info('issuerNameO is:' + issuerNameO);
issuerNameMap.set('常用名称:', String(issuerNameCN));
issuerNameMap.set('组织:', String(issuerNameO));
issuerNameMap.set('组织单位:', String(issuerNameOU));
}
dateMap.set('颁发时间:', String(result.certInfo.notBefore));
dateMap.set('有效期至:', String(result.certInfo.notAfter));
let certData: Uint8Array = result.certInfo.cert;
let certInfo = new CertInfoVo(String(result.certInfo.uri), String(result.certInfo.certAlias),
Boolean(result.certInfo.status), String(result.certInfo.issuerName), String(result.certInfo.subjectName),
String(result.certInfo.serial), String(result.certInfo.notBefore),
String(result.certInfo.notAfter), String(result.certInfo.fingerprintSha256),
certData, subjectNameMap, issuerNameMap, dateMap);
console.log(TAG + 'getSystemTrustedCertificate end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS, certInfo);
} else {
console.error(TAG + 'getSystemTrustedCertificate failed, undefined');
callback(CMModelErrorCode.CM_MODEL_ERROR_FAILED, undefined);
}
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'getSystemTrustedCertificate err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION, undefined);
}
}
private async getUserTrustedCertificateList(callback: Function): Promise<void> {
console.log(TAG + 'getUserTrustedCertificateList start');
try {
let subjectNameCN: string = '';
let result = await CertManager.getUserTrustedCertificateList();
let certList: CertAbstractVo[] = [];
let regex: RegExp = new RegExp('(?<=CN=).*?(?=,)', 'g');
if (result.certList !== undefined) {
console.log(TAG + 'getUserTrustedCertificateList result: ' + JSON.stringify(result));
for (let i = 0; i < result.certList.length; i++) {
if (result.certList[i].subjectName.length !== 0) {
let temp = result.certList[i].subjectName.match(regex);
subjectNameCN = (temp !== undefined) ? String(temp) : '';
console.info('subjectNameCN is:' + subjectNameCN);
}
if (String(result.certList[i].uri).indexOf('u=0;') === -1) {
certList.push(new CertAbstractVo(String(result.certList[i].uri), String(result.certList[i].certAlias),
Boolean(result.certList[i].status), String(result.certList[i].subjectName), String(subjectNameCN)));
}
}
console.log(TAG + 'getUserTrustedCertificateList end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS, certList);
} else {
console.error(TAG + 'getUserTrustedCertificateList failed, undefined');
callback(CMModelErrorCode.CM_MODEL_ERROR_FAILED, undefined);
}
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'getUserTrustedCertificateList err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION);
}
}
private async getUserTrustedCertificate(certUri: string, callback: Function): Promise<void> {
console.log(TAG + 'getUserTrustedCertificate start');
try {
let result = await CertManager.getUserTrustedCertificate(certUri);
let subjectNameMap: Map<string, string> = new Map();
let issuerNameMap: Map<string, string> = new Map();
let dateMap: Map<string, string> = new Map();
let regex1: RegExp = new RegExp('(?<=CN=).*?(?=,)', 'g');
let regex2: RegExp = new RegExp('(?<=OU=).*?(?=,)', 'g');
let regex3: RegExp = new RegExp('(?<=O=).*', 'g');
if (result.certInfo !== undefined) {
if (result.certInfo.subjectName.length !== 0) {
let subjectNameCN = result.certInfo.subjectName.match(regex1);
console.info('subjectNameCN is:' + subjectNameCN);
let subjectNameOU = result.certInfo.subjectName.match(regex2);
console.info('subjectNameOU is:' + subjectNameOU);
let subjectNameO = result.certInfo.subjectName.match(regex3);
console.info('SubjectNameO is:' + subjectNameO);
subjectNameMap.set('常用名称:', String(subjectNameCN));
subjectNameMap.set('组织:', String(subjectNameO));
subjectNameMap.set('组织单位:', String(subjectNameOU));
subjectNameMap.set('序列号:', String(result.certInfo.serial));
}
if (result.certInfo.issuerName.length !== 0) {
let issuerNameCN = result.certInfo.issuerName.match(regex1);
console.info('issuerNameCN is:' + issuerNameCN);
let issuerNameOU = result.certInfo.issuerName.match(regex2);
console.info('issuerNameOU is:' + issuerNameOU);
let issuerNameO = result.certInfo.issuerName.match(regex3);
console.info('issuerNameO is:' + issuerNameO);
issuerNameMap.set('常用名称:', String(issuerNameCN));
issuerNameMap.set('组织:', String(issuerNameO));
issuerNameMap.set('组织单位:', String(issuerNameOU));
}
dateMap.set('颁发时间:', String(result.certInfo.notBefore));
dateMap.set('有效期至:', String(result.certInfo.notAfter));
let certData:Uint8Array = result.certInfo.cert;
let certInfo = new CertInfoVo(String(result.certInfo.uri), String(result.certInfo.certAlias),
Boolean(result.certInfo.status), String(result.certInfo.issuerName), String(result.certInfo.subjectName),
String(result.certInfo.serial), String(result.certInfo.notBefore),
String(result.certInfo.notAfter), String(result.certInfo.fingerprintSha256),
certData, subjectNameMap, issuerNameMap, dateMap);
console.log(TAG + 'getUserTrustedCertificate end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS, certInfo);
} else {
console.error(TAG + 'getUserTrustedCertificate failed, undefined');
callback(CMModelErrorCode.CM_MODEL_ERROR_FAILED, undefined);
}
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'getUserTrustedCertificate err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION, undefined);
}
}
private async deleteUserTrustedCertificate(certUri: string, callback: Function): Promise<void> {
console.log(TAG + 'deleteUserTrustedCertificate start');
try {
await CertManager.uninstallUserTrustedCertificate(certUri);
console.log(TAG + 'deleteUserTrustedCertificate end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS);
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'deleteUserTrustedCertificate err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION);
}
}
private async setCertificateStatus(certUri: string, store: number,
status: boolean, callback: Function): Promise<void> {
console.log(TAG + 'setCertificateStatus start');
try {
await CertManager.setCertificateStatus(certUri, store, status);
console.log(TAG + 'setCertificateStatus end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS);
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'setCertificateStatus failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION);
}
}
private async getAppCredList(callback: Function): Promise<void> {
console.log(TAG + 'getAppCredList start');
try {
let result = await CertManager.getAppCertificateList();
let credList: CredentialAbstractVo[] = [];
if (result.credentialList !== undefined) {
for (let i = 0; i < result.credentialList.length; i++) {
credList.push(new CredentialAbstractVo(String(result.credentialList[i].type),
String(result.credentialList[i].alias), String(result.credentialList[i].keyUri)));
}
console.log(TAG + 'getAppCredList end credList: ' + JSON.stringify(credList));
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS, credList);
} else {
console.error(TAG + 'getAppCredList failed, undefined.');
callback(CMModelErrorCode.CM_MODEL_ERROR_FAILED, undefined);
}
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'getAppCredList failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION);
}
}
private async getAppCredential(certUri: string, callback: Function): Promise<void> {
console.log(TAG + 'getAppCredential start');
try {
let result = await CertManager.getAppCertificate(certUri);
if (result.credential !== undefined) {
let certData:Uint8Array = result.credential.credData;
let credInfo = new CredentialVo(String(result.credential.type), String(result.credential.alias),
String(result.credential.keyUri), Number(result.credential.certNum),
Number(result.credential.keyNum), certData);
console.log(TAG + 'getAppCredential end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS, credInfo);
} else {
console.error(TAG + 'getAppCredential failed, undefined');
callback(CMModelErrorCode.CM_MODEL_ERROR_FAILED, undefined);
}
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'getAppCredential failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION, undefined);
}
}
private async deleteAppCredential(certUri: string, callback: Function): Promise<void> {
console.log(TAG + 'deleteAppCredential start');
try {
await CertManager.uninstallAppCertificate(certUri);
console.log(TAG + 'deleteAppCredential end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS);
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'deleteAppCredential failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION);
}
}
private async getPrivateCredList(callback: Function): Promise<void> {
console.log(TAG + 'getPrivateCredList start');
try {
let result = await CertManager.getPrivateCertificateList();
let credList: CredentialAbstractVo[] = [];
if (result.credentialList !== undefined) {
for (let i = 0; i < result.credentialList.length; i++) {
credList.push(new CredentialAbstractVo(String(result.credentialList[i].type),
String(result.credentialList[i].alias), String(result.credentialList[i].keyUri)));
}
console.log(TAG + 'getPrivateCredList end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS, credList);
} else {
console.error(TAG + 'getPrivateCredList failed, undefined');
callback(CMModelErrorCode.CM_MODEL_ERROR_FAILED);
}
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'getPrivateCredList failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION);
}
}
private async getPrivateCred(certUri: string, callback: Function): Promise<void> {
console.log(TAG + 'getPrivateCred start');
try {
let result = await CertManager.getPrivateCertificate(String(certUri));
if (result.credential !== undefined) {
let certData:Uint8Array = result.credential.credData;
let credInfo = new CredentialVo(String(result.credential.type), String(result.credential.alias),
String(result.credential.keyUri), Number(result.credential.certNum),
Number(result.credential.keyNum), certData);
console.log(TAG + 'getPrivateCred end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS, credInfo);
} else {
console.error(TAG + 'getPrivateCred failed, undefined');
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION, undefined);
}
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'getPrivateCred failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION, undefined);
}
}
private async delAllUserCertificate(callback: Function): Promise<void> {
console.log(TAG + 'delAllUserCertificate start');
try {
await CertManager.uninstallAllUserTrustedCertificate();
console.log(TAG + 'delAllUserCertificate end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS);
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'delAllUserCertificate failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION);
}
}
private async delAllAppCredential(callback: Function): Promise<void> {
console.log(TAG + 'delAllAppCredential start');
try {
await CertManager.uninstallAllAppCertificate();
console.log(TAG + 'delAllAppCredential end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS);
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'delAllAppCredential failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION);
}
}
private async getAuthorizedAppList(uri: string, callback: Function): Promise<void> {
console.log(TAG + 'getAuthorizedAppList start');
try {
let result = await CertManager.getAuthorizedAppList(uri);
console.log(TAG + 'getAuthorizedAppList end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS, result.appUidList);
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'getAuthorizedAppList failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION, undefined);
}
}
private async setAuthorizedAppStatus(uri: string, appUid: string,
status: boolean, callback: Function): Promise<void> {
console.log(TAG + 'setAuthorizedAppStatus start');
try {
if (status) {
let result = await CertManager.grantAppCertificate(uri, appUid);
console.log(TAG + 'setAuthorizedAppStatus true end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS, result.uri);
} else {
console.log(TAG + 'appId:' + appUid + 'uri:' + uri);
await CertManager.removeGrantedAppCertificate(uri, appUid);
console.log(TAG + 'setAuthorizedAppStatus false end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS);
}
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'setAuthorizedAppStatus failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION);
}
}
private async installUserCertificate(data: Uint8Array, alias: string, callback: Function): Promise<void> {
console.info(TAG + 'installUserCertificate start alias: ' + alias + 'data' + JSON.stringify(data));
try {
await CertManager.installUserTrustedCertificate({
inData: data,
alias: alias
});
console.info(TAG + 'installUserCertificate end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS);
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'installUserCertificate failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION);
}
}
private async installAppCertificate(data: Uint8Array, alias: string,
pwd: string, callback: Function): Promise<void> {
console.info(TAG + 'installAppCertificate start');
try {
await CertManager.installAppCertificate(data, pwd, alias);
console.info(TAG + 'installAppCertificate end');
callback(CMModelErrorCode.CM_MODEL_ERROR_SUCCESS);
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'installAppCertificate failed with err, message: ' + e.message + ', code: ' + e.code);
callback(CMModelErrorCode.CM_MODEL_ERROR_EXCEPTION);
}
}
}
let certMangerModel = new CertMangerModel();
export default certMangerModel as CertMangerModel;

View File

@ -0,0 +1,54 @@
/**
* Copyright (c) 2022-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 fileUri from '@ohos.file.fileuri';
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
export class FileIoModel {
getMediaFileData(mediaUri: string, callback: Function): void {
console.log('CertManager FA getMediaFile start');
try {
let file = fs.openSync(mediaUri, fs.OpenMode.READ_ONLY);
let stat = fs.statSync(file.fd);
let buf = new ArrayBuffer(Number(stat.size));
let num = fs.readSync(file.fd, buf);
fs.closeSync(file.fd);
console.log('CertManager FA getMediaFile success');
callback(new Uint8Array(buf));
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error('CertManager FA getMediaFileData failed with err, message: ' + e.message + ', code: ' + e.code);
callback(undefined);
}
}
getMediaFileSuffix(mediaUri: string, callback: Function): void {
try {
console.log('CertManager FA getMediaFileSuffix start uri: ' + mediaUri);
let uri = new fileUri.FileUri(mediaUri);
let suffix = uri.name.substring(uri.name.lastIndexOf('.') + 1);
callback(suffix);
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error('CertManager FA getMediaFileSuffix failed with err, message: ' + e.message + ', code: ' + e.code);
callback(undefined);
}
}
}
let fileIoModel = new FileIoModel();
export default fileIoModel as FileIoModel;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,159 @@
/**
* Copyright (c) 2022-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 HeadComponent from '../common/component/headComponent';
import { WidthPercent, LocationChoice, ConfigValue } from '../common/util/ConfigData';
import router from '@ohos.router';
import CmInstallPresenter from '../presenter/CmInstallPresenter';
import CmFaPresenter from '../presenter/CmFaPresenter';
import { GlobalContext } from '../common/GlobalContext';
import { RouterFileVo } from '../model/CertManagerVo/RouterInfoVo';
@Entry
@Component
struct CertInstallAliasInput {
@State mAppCredAuthPresenter: CmInstallPresenter = CmInstallPresenter.getInstance();
@State mFaPresenter: CmFaPresenter = CmFaPresenter.getInstance();
@State certAlias: string = '';
onPageShow() {
let uri = GlobalContext.getContext().getAbilityWant().uri;
GlobalContext.getContext().clearAbilityWantUri();
if (uri === 'certInstall') {
this.mFaPresenter.startInstall();
} else if (uri === 'requestAuthorize') {
this.mFaPresenter.startRequestAuth(GlobalContext.getContext().getAbilityWant().parameters?.appUid as string);
}
}
build() {
Column() {
Column() {
HeadComponent({ headName: $r('app.string.certificateAliasTab') });
Text($r('app.string.certificateAliasInfo'))
.fontColor($r('sys.color.ohos_id_color_text_primary'))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontWeight(FontWeight.Medium)
.margin({
top: $r('app.float.distance_24'),
left: $r('app.float.distance_24')
})
.alignSelf(ItemAlign.Start)
TextInput()
.type(InputType.Normal)
.backgroundColor($r('sys.color.ohos_id_color_sub_background'))
.enterKeyType(EnterKeyType.Done)
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontWeight(FontWeight.Medium)
.fontColor($r('sys.color.ohos_id_color_text_primary'))
.onChange((value: string) => {
this.certAlias = value;
})
.maxLength(ConfigValue.ALIAS_MAX_LENGTH)
.margin({
left: $r('app.float.distance_24'),
right: $r('app.float.distance_24')
})
.height($r('app.float.distance_48'))
Row() {
Divider().color($r('app.color.CertManager_Divider_Color_182431'))
}
.margin({
left: $r('app.float.distance_24'),
right: $r('app.float.distance_24'),
})
Text($r('app.string.installAliasInputInfo'))
.fontColor($r('sys.color.ohos_id_color_text_primary'))
.fontWeight(FontWeight.Regular)
.fontSize($r('sys.float.ohos_id_text_size_body2'))
.margin({
left: $r('app.float.distance_24'),
top: $r('app.float.distance_16')
})
.alignSelf(ItemAlign.Start)
.opacity($r('app.float.opacity_100_60'))
}
.width(WidthPercent.WH_100_100)
.height(WidthPercent.WH_75_100);
Column() {
Row() {
Button() {
Text($r('app.string.installAliasInputCancel'))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontWeight(FontWeight.Medium)
.fontColor($r('sys.color.ohos_id_color_text_hyperlink'))
}
.type(ButtonType.Capsule)
.backgroundColor($r('app.color.install_cancel_bt_bg_color'))
.width($r('app.float.component_button_width_phone'))
.height($r('app.float.application_button_height'))
.margin({
left: $r('app.float.distance_24'),
})
.onClick(() => {
router.back();
})
if ((this.certAlias.length > 0) && (this.certAlias[0] != ' ')) {
Button() {
Text($r('app.string.installAliasInputConfirm'))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.install_confirm_bt_font_color'))
}
.type(ButtonType.Capsule)
.backgroundColor($r('app.color.install_confirm_bt_bg_color'))
.width($r('app.float.component_button_width_phone'))
.height($r('app.float.application_button_height'))
.margin({
left: $r('app.float.distance_16'),
right: $r('app.float.distance_24'),
})
.onClick(() => {
let fileInfo: RouterFileVo = router.getParams() as RouterFileVo;
this.mAppCredAuthPresenter.installCert(fileInfo.uri, this.certAlias, fileInfo.suffix);
})
} else {
Button() {
Text($r('app.string.installAliasInputConfirm'))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.install_confirm_bt_font_color'))
}
.type(ButtonType.Capsule)
.backgroundColor($r('app.color.install_confirm_bt_bg_disable_color'))
.width($r('app.float.component_button_width_phone'))
.height($r('app.float.application_button_height'))
.margin({
left: $r('app.float.distance_16'),
right: $r('app.float.distance_24'),
})
}
}
.margin({ bottom: $r('app.float.wh_value_24') })
}
.justifyContent(FlexAlign.End)
.height(WidthPercent.WH_25_100);
}
.backgroundColor($r('sys.color.ohos_id_color_sub_background'))
.width(WidthPercent.WH_100_100)
.height(WidthPercent.WH_100_100);
}
}

View File

@ -0,0 +1,347 @@
/**
* Copyright (c) 2022-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 { WidthPercent, LocationChoice, ConfigValue } from '../common/util/ConfigData';
import HeadComponent from '../common/component/headComponent';
import { SubEntryComponent } from '../common/component/subEntryComponent';
import CmFaPresenter from '../presenter/CmFaPresenter';
import { GlobalContext } from '../common/GlobalContext';
class CertListItem {
public targetPage: string = '';
public title: Resource = $r('app.string.trustedEvidence');
};
@Entry
@Component
struct CertificateComponent {
@State touchedItem: boolean = false;
@State columnMargin: string = '12vp';
@State mFaPresenter: CmFaPresenter = CmFaPresenter.getInstance();
private listItems: Array<CertListItem> = [
{ targetPage: 'pages/trustedCa', title: $r('app.string.trustedEvidence') },
{ targetPage: 'pages/cerEvidenceFa', title: $r('app.string.userEvidence') }
];
build() {
Column() {
GridContainer({
columns: 12,
sizeType: SizeType.Auto,
gutter: vp2px(1) === 2 ? '12vp' : '0vp',
margin: vp2px(1) === 2 ? '24vp' : '0vp'
}) {
Row({}) {
Column() {
}
.width(WidthPercent.WH_100_100)
.height(WidthPercent.WH_100_100)
.useSizeType({
xs: { span: 0, offset: 0 }, sm: { span: 0, offset: 0 },
md: { span: 0, offset: 0 }, lg: { span: 2, offset: 0 }
});
Column({ space: this.columnMargin }) {
HeadComponent({ headName: $r('app.string.certificateTab') })
Column({ space: this.columnMargin }) {
List() {
ForEach(this.listItems, (item: CertListItem) => {
ListItem() {
SubEntryComponent({ targetPage: item.targetPage, title: item.title })
}
}, (item: CertListItem) => JSON.stringify(item))
}
.padding($r('app.float.wh_value_4'))
.divider({
strokeWidth: $r('app.float.sys_list_divider_strokeWidth_value'),
color: $r('app.color.sys_list_divider_color_000000'),
startMargin: '8vp',
endMargin: '8vp'
})
.borderRadius($r('app.float.user_list_divider_borderRadius_value'))
.backgroundColor($r('app.color.user_list_backgroundColor_FFFFFF'))
CertInstallComponent({ mFaPresenter: $mFaPresenter })
DeleteAll({ mFaPresenter: $mFaPresenter })
}
.width(WidthPercent.WH_100_100)
}
.backgroundColor($r('sys.color.ohos_id_color_sub_background'))
.padding({ left: $r('app.float.wh_value_12'), right: $r('app.float.wh_value_12') })
.width(WidthPercent.WH_100_100)
.height(WidthPercent.WH_100_100)
.useSizeType({
xs: { span: 12, offset: 0 }, sm: { span: 12, offset: 0 },
md: { span: 12, offset: 0 }, lg: { span: 8, offset: 2 }
});
Column() {
}
.width(WidthPercent.WH_100_100)
.height(WidthPercent.WH_100_100)
.useSizeType({
xs: { span: 0, offset: 12 }, sm: { span: 0, offset: 12 },
md: { span: 0, offset: 12 }, lg: { span: 2, offset: 10 }
})
}
.width(WidthPercent.WH_100_100)
.height(WidthPercent.WH_100_100);
}
.width(WidthPercent.WH_100_100)
.height(WidthPercent.WH_100_100);
}
.backgroundColor($r('sys.color.ohos_id_color_sub_background'))
.width(WidthPercent.WH_100_100)
.height(WidthPercent.WH_100_100);
}
onPageShow() {
let uri = GlobalContext.getContext().getAbilityWant().uri;
GlobalContext.getContext().clearAbilityWantUri();
if (uri === 'certInstall') {
this.mFaPresenter.startInstall();
} else if (uri === 'requestAuthorize') {
this.mFaPresenter.startRequestAuth(GlobalContext.getContext().getAbilityWant().parameters?.appUid as string);
}
}
}
@CustomDialog
@Component
struct CustomDialogExampleDeleteAll {
controller?: CustomDialogController;
@Link deleteAll: CmFaPresenter;
build() {
Column() {
GridContainer({
columns: 12,
sizeType: SizeType.Auto,
gutter: vp2px(1) === 2 ? '12vp' : '0vp',
margin: vp2px(1) === 2 ? '24vp' : '0vp'
}) {
Row({}) {
Column() {
}
.width(WidthPercent.WH_100_100)
.useSizeType({
xs: { span: 0, offset: 0 }, sm: { span: 0, offset: 0 },
md: { span: 0, offset: 0 }, lg: { span: 2, offset: 0 }
});
Column() {
Text($r('app.string.deleteAllCredDialogTitle'))
.height($r('app.float.wh_value_56'))
.fontSize($r('sys.float.ohos_id_text_size_dialog_tittle'))
.fontColor($r('sys.color.ohos_id_color_text_primary'))
.fontWeight(FontWeight.Medium)
.margin({
left: $r('app.float.wh_value_24'),
right: $r('app.float.wh_value_24')
})
.alignSelf(ItemAlign.Start)
Text($r('app.string.deleteAllCredDialogMessage'))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontWeight(FontWeight.Regular)
.fontColor($r('sys.color.ohos_id_color_text_primary'))
.margin({
top: $r('app.float.wh_value_16'),
left: $r('app.float.wh_value_24'),
right: $r('app.float.wh_value_24')
})
.alignSelf(ItemAlign.Start)
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center,
justifyContent: FlexAlign.SpaceAround }) {
Button($r('app.string.deleteAllCredCancel'))
.onClick(() => {
if (this.controller !== undefined) {
this.controller.close()
}
})
.backgroundColor($r('app.color.credentials_app_finish_backgroundColor'))
.fontSize($r('sys.float.ohos_id_text_size_button1'))
.fontColor($r('sys.color.ohos_id_color_text_hyperlink'))
.width($r('app.float.wh_value_152'))
.height($r('app.float.wh_value_40'))
Divider()
.strokeWidth(ConfigValue.VERTICAL_DIVIDER_WIDTH)
.color($r('sys.color.ohos_id_color_list_separator'))
.vertical(true)
.height($r('app.float.wh_value_40'))
.opacity($r('app.float.opacity_0_2'))
Button($r('app.string.deleteAllCredDelete'))
.onClick(() => {
this.deleteAll.uninstallAllCert();
if (this.controller !== undefined) {
this.controller.close()
}
})
.backgroundColor($r('app.color.credentials_app_finish_backgroundColor'))
.fontSize($r('sys.float.ohos_id_text_size_button1'))
.fontColor($r('sys.color.ohos_id_color_warning'))
.width($r('app.float.wh_value_152'))
.height($r('app.float.wh_value_40'))
}
.height($r('app.float.wh_value_64'))
.padding({
bottom: $r('app.float.wh_value_16')
})
.margin({
top: $r('app.float.wh_value_16'),
left: $r('app.float.wh_value_24'),
right: $r('app.float.wh_value_24')
})
}
.width(WidthPercent.WH_100_100)
.borderRadius($r('app.float.user_list_divider_borderRadius_value'))
.backgroundColor($r('sys.color.ohos_id_color_foreground_contrary'))
.useSizeType({
xs: { span: 12, offset: 0 }, sm: { span: 12, offset: 0 },
md: { span: 12, offset: 0 }, lg: { span: 8, offset: 2 }
});
Column() {
}
.width(WidthPercent.WH_100_100)
.useSizeType({
xs: { span: 0, offset: 12 }, sm: { span: 0, offset: 12 },
md: { span: 0, offset: 12 }, lg: { span: 2, offset: 10 }
});
}
}
}
.margin({
bottom: $r('sys.float.ohos_id_dialog_margin_bottom'),
left: $r('sys.float.ohos_id_dialog_margin_start'),
right: $r('sys.float.ohos_id_dialog_margin_end'),
})
}
}
@Component
struct DeleteAll {
@State isTouched: boolean = false;
@Link mFaPresenter: CmFaPresenter;
deleteWarnDialog: CustomDialogController = new CustomDialogController({
builder: CustomDialogExampleDeleteAll({ deleteAll: $mFaPresenter }),
autoCancel: true,
customStyle: true,
alignment: DialogAlignment.Bottom,
})
build() {
Row() {
Text($r('app.string.deleteAllCred'))
.fontSize($r('app.float.font_16'))
.lineHeight($r('app.float.wh_value_22'))
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.cm_del_all_font_color'))
.padding({ left: $r('app.float.distance_8') })
.linearGradient(this.isTouched ? {
angle: 90,
direction: GradientDirection.Right,
colors: [[$r('app.color.DCEAF9'), 0.0], [$r('app.color.FAFAFA'), 1.0]]
} : {
angle: 90,
direction: GradientDirection.Right,
colors: [[$r('sys.color.ohos_id_color_foreground_contrary'), 1],
[$r('sys.color.ohos_id_color_foreground_contrary'), 1]]
})
.height(WidthPercent.WH_100_100)
.borderRadius($r('app.float.radius_20'))
.width(WidthPercent.WH_100_100)
.textAlign(TextAlign.Start);
}
.padding($r('app.float.distance_4'))
.height($r('app.float.wh_value_56'))
.width(WidthPercent.WH_100_100)
.borderRadius($r('app.float.radius_24'))
.onTouch((event?: TouchEvent) => {
if (event !== undefined) {
if (event.type === TouchType.Down) {
this.isTouched = true;
}
if (event.type === TouchType.Up) {
this.isTouched = false;
}
}
})
.backgroundColor($r('sys.color.ohos_id_color_foreground_contrary'))
.onClick(() => {
this.deleteWarnDialog.open();
})
}
}
@Component
export struct CertInstallComponent {
@State isTouched: boolean = false;
@Link mFaPresenter: CmFaPresenter;
build() {
Column() {
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
Row() {
Text($r('app.string.installInStorageDevice'))
.fontSize($r('app.float.font_16'))
.lineHeight($r('app.float.wh_value_22'))
.fontColor($r('app.color.font_color_182431'))
.fontWeight(FontWeight.Medium)
.margin({ left: $r('app.float.wh_value_8') });
}
Image($r('app.media.ic_settings_arrow'))
.width($r('app.float.wh_value_12'))
.height($r('app.float.wh_value_24'))
.fillColor($r('sys.color.ohos_id_color_primary'))
.opacity($r('app.float.opacity_0_2'))
.margin({ right: $r('app.float.wh_value_8') });
}
.borderRadius($r('app.float.radius_20'))
.height(WidthPercent.WH_100_100)
.width(WidthPercent.WH_100_100)
.linearGradient(this.isTouched ? {
angle: 90,
direction: GradientDirection.Right,
colors: [[$r('app.color.DCEAF9'), 0.0], [$r('app.color.FAFAFA'), 1.0]]
} : {
angle: 90,
direction: GradientDirection.Right,
colors: [[$r('sys.color.ohos_id_color_foreground_contrary'), 1],
[$r('sys.color.ohos_id_color_foreground_contrary'), 1]]
})
.onTouch((event?: TouchEvent) => {
if (event !== undefined) {
if (event.type === TouchType.Down) {
this.isTouched = true;
}
if (event.type === TouchType.Up) {
this.isTouched = false;
}
}
})
}
.backgroundColor($r('sys.color.ohos_id_color_foreground_contrary'))
.padding($r('app.float.distance_4'))
.height($r('app.float.wh_value_56'))
.borderRadius($r('app.float.radius_24'))
.onClick(() => {
this.mFaPresenter.startInstall()
});
}
}

View File

@ -0,0 +1,119 @@
/**
* Copyright (c) 2022-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 HeadComponent from '../common/component/headComponent';
import { WidthPercent, LocationChoice, ConfigValue } from '../common/util/ConfigData';
import router from '@ohos.router';
import CmFaPresenter from '../presenter/CmFaPresenter';
import { GlobalContext } from '../common/GlobalContext';
@Entry
@Component
struct CertPwdInput {
certPwd: string = '';
@State mFaPresenter: CmFaPresenter = CmFaPresenter.getInstance();
onPageShow() {
let uri = GlobalContext.getContext().getAbilityWant().uri;
GlobalContext.getContext().clearAbilityWantUri();
if (uri === 'certInstall') {
this.mFaPresenter.startInstall();
} else if (uri === 'requestAuthorize') {
this.mFaPresenter.startRequestAuth(GlobalContext.getContext().getAbilityWant().parameters?.appUid as string);
}
}
build() {
Column() {
Column() {
HeadComponent({ headName: $r('app.string.certificatePwdTab') });
Text($r('app.string.certificatePwdInfo'))
.fontColor($r('sys.color.ohos_id_color_text_primary'))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontWeight(FontWeight.Medium)
.margin({
top: $r('app.float.distance_24'),
left: $r('app.float.distance_24')
})
.alignSelf(ItemAlign.Start);
TextInput()
.type(InputType.Password)
.onChange((value: string) => {
this.certPwd = value;
})
.maxLength(ConfigValue.PWD_MAX_LENGTH)
.margin({
top: $r('app.float.distance_16'),
left: $r('app.float.distance_24'),
right: $r('app.float.distance_24')
})
.height('40vp')
}
.width(WidthPercent.WH_100_100)
.height(WidthPercent.WH_75_100);
Column() {
Row() {
Button() {
Text($r('app.string.installPwdInputCancel'))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontWeight(FontWeight.Medium)
.fontColor($r('sys.color.ohos_id_color_text_hyperlink'))
}
.type(ButtonType.Capsule)
.backgroundColor($r('app.color.install_cancel_bt_bg_color'))
.width($r('app.float.component_button_width_phone'))
.height($r('app.float.application_button_height'))
.margin({
left: $r('app.float.distance_24'),
})
.onClick(() => {
router.back();
})
Button() {
Text($r('app.string.installPwdInputConfirm'))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.install_confirm_bt_font_color'))
}
.type(ButtonType.Capsule)
.backgroundColor($r('app.color.install_confirm_bt_bg_color'))
.width($r('app.float.component_button_width_phone'))
.height($r('app.float.application_button_height'))
.margin({
left: $r('app.float.distance_16'),
right: $r('app.float.distance_24'),
})
.onClick(() => {
GlobalContext.getContext().getPwdStore().setCertPwd(this.certPwd)
router.pushUrl({
url: 'pages/certInstallAliasInput',
params: router.getParams()
})
})
}
.margin({ bottom: $r('app.float.wh_value_24') })
}
.justifyContent(FlexAlign.End)
.height(WidthPercent.WH_25_100);
}
.backgroundColor($r('sys.color.ohos_id_color_sub_background'))
.width(WidthPercent.WH_100_100)
.height(WidthPercent.WH_100_100);
}
}

View File

@ -0,0 +1,306 @@
/**
* Copyright (c) 2022-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 CmAppCredAuthPresenter from '../presenter/CmAppCredAuthPresenter';
import router from '@ohos.router';
import { WidthPercent, LocationChoice, ConfigValue } from '../common/util/ConfigData';
import { CredentialAbstractVo } from '../model/CertManagerVo/CredentialAbstractVo';
import { RouterAppUidVo } from '../model/CertManagerVo/RouterInfoVo';
@CustomDialog
@Component
struct CustomDialogAuthForApp {
controller?: CustomDialogController
@State mAppCredAuthPresenter: CmAppCredAuthPresenter = CmAppCredAuthPresenter.getInstance();
selectUri: string = '';
private authScroller: Scroller = new Scroller();
aboutToAppear(): void {
console.info('certPwdInput about to appear');
let appUidInfo: RouterAppUidVo = router.getParams() as RouterAppUidVo;
this.mAppCredAuthPresenter.updateAppNameFromUid(appUidInfo.appUid as string);
this.mAppCredAuthPresenter.updateAppCredList();
}
build() {
Column() {
GridContainer({
columns: 12,
sizeType: SizeType.Auto,
gutter: vp2px(1) === 2 ? '12vp' : '0vp',
margin: vp2px(1) === 2 ? '24vp' : '0vp'
}) {
Row({}) {
Column() {
}
.width(WidthPercent.WH_100_100)
.useSizeType({
xs: { span: 0, offset: 0 }, sm: { span: 0, offset: 0 },
md: { span: 0, offset: 0 }, lg: { span: 2, offset: 0 }
});
Column() {
Text($r('app.string.pickCredToAuth'))
.fontSize($r('sys.float.ohos_id_text_size_dialog_tittle'))
.height($r('app.float.wh_value_56'))
.fontColor($r('sys.color.ohos_id_color_text_primary'))
.fontWeight(FontWeight.Medium)
.margin({
left: $r('app.float.wh_value_24'),
right: $r('app.float.wh_value_24')
})
.alignSelf(ItemAlign.Start)
Text($r('app.string.requestAuthMsg', this.mAppCredAuthPresenter.appName))
.fontSize($r('sys.float.ohos_id_text_size_body1'))
.fontColor($r('sys.color.ohos_id_color_text_primary'))
.fontWeight(FontWeight.Regular)
.margin({
top: $r('app.float.wh_value_8'),
left: $r('app.float.wh_value_24'),
right: $r('app.float.wh_value_24')
})
.alignSelf(ItemAlign.Start)
if (this.mAppCredAuthPresenter.credList.length > ConfigValue.REQUEST_AUTH_MAX_LENGTH) {
Stack({ alignContent: Alignment.End }) {
Scroll(this.authScroller) {
List() {
ForEach(this.mAppCredAuthPresenter.credList, (item: CredentialAbstractVo) => {
ListItem() {
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
Column() {
Text(item.alias)
.fontSize($r('app.float.font_18'))
.fontColor($r('app.color.request_auth_font_color'))
.fontWeight(FontWeight.Medium)
.textAlign(TextAlign.Start);
}
.alignItems(HorizontalAlign.Start)
Column() {
Radio({ value: item.alias, group: 'appCredGroup' })
.checked(false)
.onChange((value: boolean) => {
console.log(item.alias + ' status is ' + value)
if (value) {
this.selectUri = item.keyUri;
console.log('selectUri is ' + this.selectUri)
}
})
}
.alignItems(HorizontalAlign.End)
}
.width(WidthPercent.WH_100_100)
}
.height($r('app.float.wh_value_64'))
}, (item: CredentialAbstractVo) => JSON.stringify(item))
}
.scrollBar(BarState.Off)
.divider({
strokeWidth: $r('app.float.request_auth_strokeWidth'),
color: $r('app.color.request_auth_color'),
endMargin: $r('app.float.request_auth_divider_endMargin') })
.backgroundColor($r('app.color.request_auth_background_color'))
.visibility(this.mAppCredAuthPresenter.credList.length > 0 ? Visibility.Visible : Visibility.None)
}
.scrollBar(BarState.Off)
.margin({
left: $r('app.float.wh_value_24'),
right: $r('app.float.wh_value_24')
})
ScrollBar({ scroller: this.authScroller, direction: ScrollBarDirection.Vertical,
state: BarState.Auto }) {
Text()
.width($r('app.float.wh_value_3'))
.height($r('app.float.wh_value_50'))
.borderRadius($r('app.float.wh_value_10'))
.backgroundColor($r('sys.color.ohos_id_color_foreground'))
.opacity(0.4)
}
.width($r('app.float.wh_value_3'))
.margin({
right: $r('app.float.wh_value_3')
})
}
.height(WidthPercent.WH_50_100)
} else {
List() {
ForEach(this.mAppCredAuthPresenter.credList, (item: CredentialAbstractVo) => {
ListItem() {
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
Column() {
Text(item.alias)
.fontSize($r('app.float.font_18'))
.fontColor($r('app.color.request_auth_font_color'))
.fontWeight(FontWeight.Medium)
.textAlign(TextAlign.Start);
}
.alignItems(HorizontalAlign.Start)
Column() {
Radio({ value: item.alias, group: 'appCredGroup' })
.checked(false)
.onChange((value: boolean) => {
console.log(item.alias + ' status is ' + value)
if (value) {
this.selectUri = item.keyUri;
console.log('selectUri is ' + this.selectUri)
}
})
}
.alignItems(HorizontalAlign.End)
}
.width(WidthPercent.WH_100_100)
}
.height($r('app.float.wh_value_64'))
}, (item: CredentialAbstractVo) => JSON.stringify(item))
ListItem() {
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
Column() {
Text()
}
.alignItems(HorizontalAlign.Start)
Column() {
Radio({ value: 'null', group: 'appCredGroup' })
.checked(false)
.onChange((value: boolean) => {
if (value) {
this.selectUri = 'null';
console.log('selectUri is ' + this.selectUri)
}
})
}
}
.visibility(Visibility.None)
}
}
.margin({
left: $r('app.float.wh_value_24'),
right: $r('app.float.wh_value_24')
})
.scrollBar(BarState.Off)
.divider({
strokeWidth: $r('app.float.request_auth_strokeWidth'),
color: $r('app.color.request_auth_color'),
endMargin: $r('app.float.request_auth_divider_endMargin') })
.backgroundColor($r('app.color.request_auth_background_color'))
.visibility(this.mAppCredAuthPresenter.credList.length > 0 ? Visibility.Visible : Visibility.None)
}
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center,
justifyContent: FlexAlign.SpaceAround }) {
Button($r('app.string.requestAuthCancel'))
.onClick(() => {
this.mAppCredAuthPresenter.cancelProcess();
if (this.controller !== undefined) {
this.controller.close();
}
})
.backgroundColor($r('app.color.request_auth_background_color'))
.fontColor($r('sys.color.ohos_id_color_text_hyperlink'))
.fontSize($r('sys.float.ohos_id_text_size_button1'))
.width($r('app.float.wh_value_152'))
.height($r('app.float.wh_value_40'))
Divider()
.strokeWidth(ConfigValue.VERTICAL_DIVIDER_WIDTH)
.color($r('sys.color.ohos_id_color_list_separator'))
.vertical(true)
.height($r('app.float.wh_value_40'))
.opacity($r('app.float.opacity_0_2'))
Button($r('app.string.requestAuthFinish'))
.onClick(() => {
console.info('requestAuthorize uri: ' + this.selectUri);
let appUidInfo: RouterAppUidVo = router.getParams() as RouterAppUidVo;
if (appUidInfo !== undefined && appUidInfo.appUid != undefined) {
console.info('requestAuthorize appUid: ' + appUidInfo.appUid);
this.mAppCredAuthPresenter.requestAuthorize(this.selectUri, appUidInfo.appUid);
if (this.controller !== undefined) {
this.controller.close();
}
} else {
console.info('requestAuthorize fail');
}
})
.backgroundColor($r('app.color.request_auth_background_color'))
.fontColor($r('sys.color.ohos_id_color_text_hyperlink'))
.fontSize($r('sys.float.ohos_id_text_size_button1'))
.width($r('app.float.wh_value_152'))
.height($r('app.float.wh_value_40'))
}
.height($r('app.float.wh_value_64'))
.padding({
bottom: $r('app.float.wh_value_16')
})
.margin({
left: $r('app.float.wh_value_24'),
right: $r('app.float.wh_value_24')
})
}
.width(WidthPercent.WH_100_100)
.borderRadius($r('app.float.user_list_divider_borderRadius_value'))
.backgroundColor($r('sys.color.ohos_id_color_foreground_contrary'))
.useSizeType({
xs: { span: 12, offset: 0 }, sm: { span: 12, offset: 0 },
md: { span: 12, offset: 0 }, lg: { span: 8, offset: 2 }
});
Column() {
}
.width(WidthPercent.WH_100_100)
.useSizeType({
xs: { span: 0, offset: 12 }, sm: { span: 0, offset: 12 },
md: { span: 0, offset: 12 }, lg: { span: 2, offset: 10 }
});
}
}
}
.margin({
bottom: $r('sys.float.ohos_id_dialog_margin_bottom'),
left: $r('sys.float.ohos_id_dialog_margin_start'),
right: $r('sys.float.ohos_id_dialog_margin_end'),
})
}
}
@Entry
@Component
struct RadioAuth {
dialogController: CustomDialogController = new CustomDialogController({
builder: CustomDialogAuthForApp(),
autoCancel: false,
alignment: DialogAlignment.Bottom,
customStyle: true,
})
aboutToAppear() {
console.info('RadioAuth aboutToAppear');
let appUidInfo: RouterAppUidVo = router.getParams() as RouterAppUidVo;
if (appUidInfo !== undefined && appUidInfo.appUid != undefined) {
this.dialogController.open();
} else {
console.error('request auth appear failed');
router.replaceUrl({ url: 'pages/certManagerFa' });
}
}
build() {
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,123 @@
/**
* Copyright (c) 2022-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 certManagerModel from '../model/CertMangerModel';
import BundleModel from '../model/BundleModel';
import { CMModelErrorCode, CMModelOptType } from '../model/CertMangerModel';
import { CredentialAbstractVo } from '../model/CertManagerVo/CredentialAbstractVo';
import router from '@ohos.router';
import { GlobalContext } from '../common/GlobalContext';
import { AppInfoVo } from '../model/CertManagerVo/AppInfoVo';
import { BusinessError } from '@ohos.base';
import Common from '@ohos.app.ability.common'
const TAG = 'CMAppCredAuthPresenter Presenter: ';
const SUCCESS = 0;
const FAIL = -1;
export default class CmAppCredAuthPresenter {
private static sInstance: CmAppCredAuthPresenter;
public credList: CredentialAbstractVo[] = [];
public appName: string = '';
public static getInstance(): CmAppCredAuthPresenter {
if (CmAppCredAuthPresenter.sInstance == null) {
CmAppCredAuthPresenter.sInstance = new CmAppCredAuthPresenter();
}
return CmAppCredAuthPresenter.sInstance;
}
onAboutToAppear(): void {
}
aboutToDisappear(): void {
this.credList = [];
}
updateAppNameFromUid(uid: string): void {
try {
console.log('getAppNameFromUid start uid = ' + uid);
BundleModel.getAppInfoList(Number(uid), (errCode: CMModelErrorCode, appInfo: AppInfoVo) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
this.appName = appInfo.appName;
console.log('getAppNameFromUid success, appName = ' + this.appName);
} else {
console.error('getAppNameFromUid fail, uid = ' + uid);
}
});
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error('updateAppNameFromUid failed with err, message: ' + e.message + ', code: ' + e.code);
}
}
updateAppCredList(): void {
certManagerModel.getCertOrCredList(CMModelOptType.CM_MODEL_OPT_APP_CRED,
(errCode: CMModelErrorCode, credList: Array<CredentialAbstractVo>) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
this.credList = credList;
console.log('updateSystemTrustedCertificateList success, list: ' + JSON.stringify(credList));
} else {
console.error('updateSystemTrustedCertificateList failed');
}
});
}
requestAuthorize(uri: string, appUid: string): void {
console.log(TAG + 'requestAuthorize start uri :' + uri + 'appUid: ' + appUid);
let want = GlobalContext.getContext().getAbilityWant();
certManagerModel.setAppAuth(CMModelOptType.CM_MODEL_OPT_APP_CRED, uri, appUid,
true, (errCode: CMModelErrorCode, data: string) => {
router.clear();
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
console.log('requestAuthorize success data: ' + data);
if (want.parameters != undefined) {
want.parameters.authUri = data;
let ret1: Common.AbilityResult = {
resultCode: SUCCESS,
want: want
};
GlobalContext.getContext().getCmContext().terminateSelfWithResult(ret1);
} else {
let ret2: Common.AbilityResult = {
resultCode: FAIL,
want: want
};
console.error(TAG + 'requestAuthorize failed, undefined');
GlobalContext.getContext().getCmContext().terminateSelfWithResult(ret2);
}
} else {
console.error('requestAuthorize fail');
let ret3: Common.AbilityResult = {
resultCode: FAIL,
want: want
};
GlobalContext.getContext().getCmContext().terminateSelfWithResult(ret3);
}
});
}
cancelProcess(): void {
console.log('cancelProcess start');
router.clear();
let ret: Common.AbilityResult = {
resultCode: FAIL,
want: GlobalContext.getContext().getAbilityWant()
};
GlobalContext.getContext().getCmContext().terminateSelfWithResult(ret);
}
}

View File

@ -0,0 +1,111 @@
/**
* Copyright (c) 2022-2023 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 picker from '@ohos.file.picker';
import router from '@ohos.router';
import certManagerModel from '../model/CertMangerModel';
import FileIoModel from '../model/FileIoModel';
import { CMModelErrorCode, CMModelOptType } from '../model/CertMangerModel';
import { BusinessError } from '@ohos.base';
import { RouterFileVo, RouterAppUidVo } from '../model/CertManagerVo/RouterInfoVo';
const TAG = 'CMFaPresenter: ';
const PAGE_URI_PWD_INPUT = 'pages/certPwdInput';
const PAGE_URI_ALIAS_INPUT = 'pages/certInstallAliasInput';
export default class CmFaPresenter {
private static sInstance: CmFaPresenter;
public static getInstance(): CmFaPresenter {
if (CmFaPresenter.sInstance == null) {
CmFaPresenter.sInstance = new CmFaPresenter();
}
return CmFaPresenter.sInstance;
}
onAboutToAppear(): void {
}
aboutToDisappear(): void {
}
routeToNext(fileUri: string): void {
console.info(TAG + 'routeToNext fileUri: ' + fileUri);
FileIoModel.getMediaFileSuffix(fileUri, (suffix: string | undefined) => {
console.info(TAG + 'suffix ' + suffix);
if (suffix !== undefined) {
let fileInfo = new RouterFileVo(fileUri, suffix);
if ((suffix === 'cer') || (suffix === 'pem')) {
router.pushUrl({
url: PAGE_URI_ALIAS_INPUT,
params: fileInfo
});
} else {
router.pushUrl({
url: PAGE_URI_PWD_INPUT,
params: fileInfo
});
}
}
});
}
startInstall(): void {
try {
let documentSelectOptions = new picker.DocumentSelectOptions();
let documentPicker = new picker.DocumentViewPicker();
console.info(TAG + 'start documentPicker.select');
documentPicker.select(documentSelectOptions).then((documentSelectResult) => {
if (documentSelectResult.length >= 1) {
this.routeToNext(String(documentSelectResult[0]));
} else {
console.error(TAG + 'documentPicker.select length invalid:' + documentSelectResult.length);
}
}).catch((err: BusinessError) => {
console.error(TAG + 'documentPicker.select failed with err, message: ' + err.message + ', code: ' + err.code);
});
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(TAG + 'DocumentViewPicker failed with err, message: ' + e.message + ', code: ' + e.code);
}
}
startRequestAuth(uri: string): void {
let appUidInfo = new RouterAppUidVo(uri);
router.replaceUrl({
url: 'pages/requestAuth',
params: appUidInfo
});
}
uninstallAllCert(): void {
certManagerModel.delAllCertOrCred(CMModelOptType.CM_MODEL_OPT_USER_CA, (errCode: CMModelErrorCode) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
console.log(TAG + 'uninstallAllCert CM_MODEL_OPT_USER_CA success');
} else {
console.error(TAG + 'uninstallAllCert CM_MODEL_OPT_USER_CA failed');
}
});
certManagerModel.delAllCertOrCred(CMModelOptType.CM_MODEL_OPT_APP_CRED, (errCode: CMModelErrorCode) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
console.log(TAG + 'uninstallAllCert CM_MODEL_OPT_APP_CRED success');
} else {
console.error(TAG + 'uninstallAllCert CM_MODEL_OPT_APP_CRED failed');
}
});
}
}

View File

@ -0,0 +1,76 @@
/**
* Copyright (c) 2022-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 certManagerModel from '../model/CertMangerModel';
import FileIoModel from '../model/FileIoModel';
import { CMModelErrorCode, CMModelOptType } from '../model/CertMangerModel';
import router from '@ohos.router';
import { GlobalContext } from '../common/GlobalContext';
const TAG = 'CMInstallPresenter: ';
export default class CmInstallPresenter {
private static sInstance: CmInstallPresenter;
private optType: CMModelOptType = CMModelOptType.CM_MODEL_OPT_UNKNOWN;
public static getInstance(): CmInstallPresenter {
if (CmInstallPresenter.sInstance == null) {
CmInstallPresenter.sInstance = new CmInstallPresenter();
}
return CmInstallPresenter.sInstance;
}
onAboutToAppear(): void {
}
aboutToDisappear(): void {
this.optType = CMModelOptType.CM_MODEL_OPT_UNKNOWN;
}
updateCertFileType(suffix: string): void {
console.info(TAG + 'updateCertFileType suffix: ' + suffix);
if ((suffix === 'cer') || (suffix === 'pem')) {
this.optType = CMModelOptType.CM_MODEL_OPT_USER_CA;
} else if ((suffix === 'p12') || (suffix === 'jks') || (suffix === 'pfx')) {
this.optType = CMModelOptType.CM_MODEL_OPT_APP_CRED;
}
}
getFileDataFromUri(uri: string, callback: Function): void {
FileIoModel.getMediaFileData(uri, (data: Uint8Array) => {
callback(data);
});
}
installCert(uri: string, alias: string, suffix: string): void {
this.updateCertFileType(suffix);
this.getFileDataFromUri(uri, (data: Uint8Array) => {
certManagerModel.installCertOrCred(this.optType, alias, data,
GlobalContext.getContext().getPwdStore().getCertPwd(), (errCode: CMModelErrorCode) => {
console.info(TAG + 'installCertOrCred result: ' + JSON.stringify(errCode));
GlobalContext.getContext().getPwdStore().clearCertPwd();
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
console.info(TAG + 'installCert success');
} else {
console.error(TAG + 'installCert failed');
}
router.clear();
router.replaceUrl({ url: 'pages/certManagerFa' });
});
});
}
}

View File

@ -0,0 +1,148 @@
/**
* Copyright (c) 2022-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 certManagerModel from '../model/CertMangerModel';
import bundleModel from '../model/BundleModel';
import { CMModelErrorCode, CMModelOptType } from '../model/CertMangerModel';
import { CredentialAbstractVo } from '../model/CertManagerVo/CredentialAbstractVo';
import { CredentialVo } from '../model/CertManagerVo/CredentialVo';
import { AppAuthorVo } from '../model/CertManagerVo/AppAuthorVo';
import { AppInfoVo } from '../model/CertManagerVo/AppInfoVo';
import { BusinessError } from '@ohos.base';
export default class CmShowAppCredPresenter {
private static sInstance: CmShowAppCredPresenter;
public credList: CredentialAbstractVo[] = [];
public appInfoList: AppAuthorVo[] = [];
public credInfo: CredentialVo = new CredentialVo('', '', '', 0, 0, new Uint8Array());
public static getInstance(): CmShowAppCredPresenter {
if (CmShowAppCredPresenter.sInstance == null) {
CmShowAppCredPresenter.sInstance = new CmShowAppCredPresenter();
}
return CmShowAppCredPresenter.sInstance;
}
aboutToDisappear(): void {
this.credList = [];
this.credInfo = new CredentialVo('', '', '', 0, 0, new Uint8Array());
this.appInfoList = [];
}
updateAppCredListCallback(callback: Function): void {
certManagerModel.getCertOrCredList(CMModelOptType.CM_MODEL_OPT_APP_CRED,
(errCode: CMModelErrorCode, credList: Array<CredentialAbstractVo>) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
credList.sort((certAbs, certAbsOther): number => {
let certAlias = certAbs.alias;
let certAliasOther = certAbsOther.alias;
if (certAlias <= certAliasOther) {
return -1;
} else {
return 1;
}
});
this.credList = credList;
callback();
} else {
console.error('updateAppCredList error :' + JSON.stringify(errCode));
this.credList = [];
callback();
}
});
}
updateAppCredList(): void {
certManagerModel.getCertOrCredList(CMModelOptType.CM_MODEL_OPT_APP_CRED,
(errCode: CMModelErrorCode, credList: Array<CredentialAbstractVo>) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
credList.sort((certAbs, certAbsOther): number => {
let certAlias = certAbs.alias;
let certAliasOther = certAbsOther.alias;
if (certAlias <= certAliasOther) {
return -1;
} else {
return 1;
}
});
this.credList = credList;
} else {
console.error('updateAppCredList error :' + JSON.stringify(errCode));
this.credList = [];
}
});
}
getAppCred(uri: string, callback: Function): void {
certManagerModel.getCertOrCred(CMModelOptType.CM_MODEL_OPT_APP_CRED, uri,
(errCode: CMModelErrorCode, credInfo: CredentialVo) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
this.credInfo = credInfo;
} else {
console.error('getAppCred error :' + JSON.stringify(errCode));
this.credInfo.clearCredentialVo();
}
callback();
});
}
deleteAppCred(uri: string): void {
certManagerModel.deleteCertOrCred(CMModelOptType.CM_MODEL_OPT_APP_CRED, uri, (errCode: CMModelErrorCode) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
this.updateAppCredList();
} else {
console.error('deleteAppCred error :' + JSON.stringify(errCode));
}
});
}
getAuthorizedAppList(uri: string): void {
this.appInfoList = [];
certManagerModel.getAuthAppList(CMModelOptType.CM_MODEL_OPT_APP_CRED, uri,
(errCode: CMModelErrorCode, appUidList: Array<string>) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
for (let i = 0; i < appUidList.length; i++) {
bundleModel.getAppInfoList(Number(appUidList[i]), (errCode: CMModelErrorCode, appInfo: AppInfoVo) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
this.appInfoList.push(
new AppAuthorVo(String(appInfo.appImage), String(appUidList[i]), String(appInfo.appName), true));
console.log('appInfoList: ' + JSON.stringify(this.appInfoList));
}
});
}
} else {
console.error('getAuthorizedAppList error :' + JSON.stringify(errCode));
this.appInfoList = [];
}
});
}
async removeGrantedAppList(uri: string): Promise<void> {
console.log('enter removeGrantedAppList');
for (let i = 0; i < this.appInfoList.length; i++) {
if (!this.appInfoList[i].status) {
try {
let res = await certManagerModel.setAppAuthPromise(CMModelOptType.CM_MODEL_OPT_APP_CRED, uri,
this.appInfoList[i].uid, false);
console.log('removeGrantedAppList succeed' + JSON.stringify(res));
} catch (error) {
let e: BusinessError = error as BusinessError;
console.error('removeGrantedAppList error, message: ' + e.message + ', code: ' + e.code);
}
}
}
console.log('leave removeGrantedAppList');
}
}

View File

@ -0,0 +1,71 @@
/**
* Copyright (c) 2022-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 certManagerModel from '../model/CertMangerModel';
import { CMModelErrorCode, CMModelOptType } from '../model/CertMangerModel';
import { CredentialAbstractVo } from '../model/CertManagerVo/CredentialAbstractVo';
import { CredentialVo } from '../model/CertManagerVo/CredentialVo';
export default class CmShowPrivateCredPresenter {
private static sInstance: CmShowPrivateCredPresenter;
public credList: CredentialAbstractVo[] = [];
public credInfo: CredentialVo = new CredentialVo('', '', '', 0, 0, new Uint8Array());
public static getInstance(): CmShowPrivateCredPresenter {
if (CmShowPrivateCredPresenter.sInstance == null) {
CmShowPrivateCredPresenter.sInstance = new CmShowPrivateCredPresenter();
}
return CmShowPrivateCredPresenter.sInstance;
}
aboutToDisappear(): void {
this.credList = [];
this.credInfo = new CredentialVo('', '', '', 0, 0, new Uint8Array());
}
updatePrivateCredList(): void {
certManagerModel.getCertOrCredList(CMModelOptType.CM_MODEL_OPT_PRIVATE_CRED,
(errCode: CMModelErrorCode, credList: Array<CredentialAbstractVo>) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
credList.sort((certAbs, certAbsOther) => {
let certAlias = certAbs.alias;
let certAliasOther = certAbsOther.alias;
if (certAlias <= certAliasOther) {
return -1;
} else {
return 1;
}
});
this.credList = credList;
} else {
console.error('updatePrivateCredList error :' + JSON.stringify(errCode));
this.credList = [];
}
});
}
getPrivateCred(uri: string, callback: Function): void {
certManagerModel.getCertOrCred(CMModelOptType.CM_MODEL_OPT_PRIVATE_CRED, uri,
(errCode: CMModelErrorCode, credInfo: CredentialVo) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
this.credInfo = credInfo;
} else {
console.error('getPrivateCred error :' + JSON.stringify(errCode));
this.credInfo.clearCredentialVo();
}
callback();
});
}
}

View File

@ -0,0 +1,95 @@
/**
* Copyright (c) 2022-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 certManagerModel from '../model/CertMangerModel';
import { CMModelErrorCode, CMModelOptType } from '../model/CertMangerModel';
import { CertAbstractVo } from '../model/CertManagerVo/CertAbstractVo';
import { CertInfoVo } from '../model/CertManagerVo/CertInfoVo';
const TAG = 'CMShowSysCa Presenter: ';
export default class CmShowSysCaPresenter {
private static sInstance: CmShowSysCaPresenter;
public certList: CertAbstractVo[] = [];
public certInfo: CertInfoVo = new CertInfoVo('', '', false, '', '', '', '', '', '',
new Uint8Array(), new Map(), new Map(), new Map());
public static getInstance(): CmShowSysCaPresenter {
if (CmShowSysCaPresenter.sInstance == null) {
CmShowSysCaPresenter.sInstance = new CmShowSysCaPresenter();
}
return CmShowSysCaPresenter.sInstance;
}
onAboutToAppear(): void {
this.updateSystemTrustedCertificateList();
}
aboutToDisappear(): void {
this.certList = [];
this.certInfo = new CertInfoVo('', '', false, '', '', '', '', '', '',
new Uint8Array(), new Map(), new Map(), new Map());
}
updateSystemTrustedCertificateList(): void {
certManagerModel.getCertOrCredList(CMModelOptType.CM_MODEL_OPT_SYSTEM_CA,
(errCode: CMModelErrorCode, certList: Array<CertAbstractVo>) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
certList.sort((certAbs, certAbsOther): number => {
let certAlias = certAbs.certAlias;
let certAliasOther = certAbsOther.certAlias;
if (certAlias <= certAliasOther) {
return -1;
} else {
return 1;
}
});
this.certList = certList;
console.log('updateSystemTrustedCertificateList success, list: ' + JSON.stringify(certList));
} else {
console.error(TAG + 'updateSystemTrustedCertificateList fail,errCode is' + errCode);
this.certList = [];
}
});
}
getSystemTrustedCertificate(uri: string, callback: Function): void {
certManagerModel.getCertOrCred(CMModelOptType.CM_MODEL_OPT_SYSTEM_CA, uri,
(errCode: CMModelErrorCode, certInfo: CertInfoVo) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
console.info(TAG + 'getSystemTrustedCertificate success,errCode is ' + errCode + ' certInfo is' +
JSON.stringify(certInfo));
this.certInfo = certInfo;
callback();
} else {
console.error(TAG + 'getSystemTrustedCertificate fail,errCode is' + errCode);
this.certInfo.clearCertInfoVo();
callback();
}
});
}
setSystemCertificateStatus(uri: string, status: boolean): void {
certManagerModel.setCertStatus(CMModelOptType.CM_MODEL_OPT_SYSTEM_CA, uri, status,
(errCode: CMModelErrorCode) => {
if (errCode === CMModelErrorCode.CM_MODEL_ERROR_SUCCESS) {
console.info(TAG + 'setSystemCertificateStatus success,errCode is' + errCode);
this.updateSystemTrustedCertificateList();
} else {
console.error(TAG + 'setSystemCertificateStatus fail,errCode is' + errCode);
}
});
}
}

Some files were not shown because too many files have changed in this diff Show More