diff --git a/README.md b/README.md index 9038579086ea7e16a90c2ee2c908b10495a476a7..04a052a4c0aa121b15ced6b456cc391123347bc7 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,8 @@ # hapsigner - - #### Introduction -To ensure the integrity and secure source of applications, the applications must be signed during the build process. Only signed applications can be installed, run, and debugged on real devices. This repository provides the source code of the HAP signing tool - hapsigner. This tool can be used to generate key pairs, certificate signing requests (CSRs), certificates, profile signatures, and HAP signatures. +To ensure the integrity and secure source of OpenHarmony applications, the applications must be signed during the build process. Only signed applications can be installed, run, and debugged on real devices. This repository provides the source code of the HAP signing tool - hapsigner. This tool can be used to generate key pairs, certificate signing requests (CSRs), certificates, profile signatures, and HAP signatures. #### Directory Structure @@ -37,6 +35,25 @@ The scripts, such as the one-click signature script, are developed in Python, an **** #### Usage +##### Usage of Signature-related Files + +When signing an application using the IDE, you will obtain the following files from the SDK: + +``` +KeyStore (KS) file: OpenHarmony.p12 +Profile signing certificates: OpenHarmonyProfileRelease.pem and OpenHarmonyProfileDebug.pem +Profile templates: UnsgnedReleasedProfileTemplate.json and UnsgnedDebugProfileTemplate.json +Signature tool: hap-sign-tool.jar +``` +The figures below illustrate how these files are used. + +**Signing a Profile** + +![signprofile.png](figures/signprofile_en.png) + +**Signing an App** + +![signapp.png](figures/signapp_en.png) ##### Note In the following, the JAR package used is the binary files generated during the build process. @@ -59,7 +76,7 @@ The parameters in the command are described as follows: ├── -profileCertFile # Profile signing certificate (certificate chain, in the end-entity certificate, intermediate CA certificate, and root certificate order). It is mandatory. ├── -inFile # Raw provisioning profile. It is mandatory. ├── -signAlg # Signature algorithm, which can be SHA256withECDSA or SHA384withECDSA. It is mandatory. - ├── -keystoreFile # KeyStore (KS) file, in JKS or P12 format. It is mandatory if the signing mode is localSign. + ├── -keystoreFile # KS file, in JKS or P12 format. It is mandatory if the signing mode is localSign. ├── -keystorePwd # KS password. It is optional. ├── -outFile # Signed provisioning profile to generate, in p7b format. It is mandatory. @@ -73,7 +90,7 @@ java -jar hap-sign-tool.jar sign-app -keyAlias "oh-app1-key-v1" -signAlg "SHA256 ``` The parameters in the command are described as follows: - sign-app: HAP signature. + sign-app: Sign a HAP. ├── -mode # Signing mode, which can be localSign or remoteSign. It is mandatory. ├── -keyAlias # Key alias. It is mandatory. ├── -keyPwd # Key password. It is optional. @@ -174,7 +191,7 @@ Procedure: ├── -issuerKeystorePwd # KS password of the issuer. It is optional. ├── -outForm # Format of the certificate to generate. It is optional. The value can be cert or certChain. The default value is certChain. ├── -rootCaCertFile # Root CA certificate, which is mandatory when outForm is certChain. - ├── -subCaCertFile # Intermediate CA certificate, which is mandatory when outForm is certChain. + ├── -subCaCertFile # Intermediate CA certificate file, which is mandatory when outForm is certChain. ├── -outFile # Certificate file (certificate or certificate chain) to generate. It is optional. The file is output to the console if this parameter is not specified. 5.Generate a profile debug or release certificate. @@ -194,7 +211,7 @@ Procedure: ├── -issuerKeystorePwd # KS password of the issuer. It is optional. ├── -outForm # Format of the certificate to generate. It is optional. The value can be cert or certChain. The default value is certChain. ├── -rootCaCertFile # Root CA certificate, which is mandatory when outForm is certChain. - ├── -subCaCertFile # Intermediate CA certificate, which is mandatory when outForm is certChain. + ├── -subCaCertFile # Intermediate CA certificate file, which is mandatory when outForm is certChain. ├── -outFile # Certificate file (certificate or certificate chain) to generate. It is optional. The file is output to the console if this parameter is not specified. 6.Generate a common certificate, which can be used to generate a custom certificate. @@ -207,12 +224,12 @@ Procedure: ├── -issuerKeyPwd # Key password of the issuer. It is optional. ├── -subject # Certificate subject. It is mandatory. ├── -validity # Validity period of the certificate. It is optional. The default value is 1095 days. - ├── -keyUsage # Usages of the key. It is mandatory. The key usages include digitalSignature, nonRepudiation, - ├ keyEncipherment, dataEncipherment, keyAgreement, certificateSignature, crlSignature, - ├ encipherOnly, and decipherOnly. Use a comma (,) to separate multiple values. + ├── -keyUsage # Usages of the key. It is mandatory. The key usages include digitalSignature, nonRepudiation, keyEncipherment, + ├ dataEncipherment, keyAgreement, certificateSignature, crlSignature, encipherOnly, and decipherOnly. + ├ Use a comma (,) to separate multiple values. ├── -keyUsageCritical # Whether keyUsage is a critical option. It is optional. The default value is true. - ├── -extKeyUsage # Extended key usages. It is optional. The extended key usages include clientAuthentication, - ├ serverAuthentication, codeSignature, emailProtection, smartCardLogin, timestamp, and ocspSignature. + ├── -extKeyUsage # Extended key usages. It is optional. The extended key usages include clientAuthentication, serverAuthentication, + ├ codeSignature, emailProtection, smartCardLogin, timestamp, and ocspSignature. ├── -extKeyUsageCritical # Whether extKeyUsage is a critical option. It is optional. The default value is false. ├── -signAlg # Signature algorithm, which can be SHA256withRSA, SHA384withRSA, SHA256withECDSA, or SHA384withECDSA. It is mandatory. ├── -basicConstraints # Whether basicConstraints is contained. It is optional. The default value is false. @@ -227,7 +244,7 @@ Procedure: 7.Sign a provisioning profile. - sign-profile: Generate a provisioning profile signature. + sign-profile: Sign a provisioning profile. ├── -mode # Signing mode, which can be localSign or remoteSign. It is mandatory. ├── -keyAlias # Key alias. It is mandatory. ├── -keyPwd # Key password. It is optional. @@ -241,7 +258,7 @@ Procedure: 8.Verify the provisioning profile signature. verify-profile: Verify the provisioning profile signature. - ├── -inFile # Signed provisioning profile, in p7b format. It is mandatory. + ├── -inFile # Signed provisioning profile, in p7b format. It is mandatory. ├── -outFile # Verification result file (including the verification result and profile content), in json format. It is optional. The file is output to the console if this parameter is not specified. 9.Sign a HAP. @@ -249,7 +266,7 @@ Procedure: sign-app: Sign a HAP ├── -mode # Signing mode, which can be localSign, remoteSign, or remoteResign. It is mandatory. ├── -keyAlias # Key alias. It is mandatory. - ├── -keyPwd # Key password. It is optional. + ├── -keyPwd # Key password. It is optional. ├── -appCertFile # Application signing certificate (certificate chain, in the end-entity certificate, intermediate CA certificate, and root certificate order). It is mandatory. ├── -profileFile # Name of the signed provisioning profile. The profile is in p7b format if profileSigned is 1 and in json format if profileSigned is 0. It is mandatory. ├── -profileSigned # Whether the profile is signed. The value 1 means signed, and value 0 means unsigned. The default value is 1. It is optional. @@ -264,7 +281,7 @@ Procedure: verify-app: Verify the HAP signature. ├── -inFile # Signed application file, in .zip or .bin format. It is mandatory. - ├── -outCertchain # Signed certificate chain file. It is mandatory. + ├── -outCertChain # Signed certificate chain file. It is mandatory. ├── -outProfile # Profile of the application. It is mandatory. diff --git a/README_ZH.md b/README_ZH.md index bdb6261a273608857a6b47e039d1ab1ea5d1f0b3..85de2b83b762953ffcf24023334543a308bece6f 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -5,6 +5,7 @@ * 约束 * 编译构建 * 说明 + * 签名相关文件用法说明 * 使用说明 * 接口说明 * 相关仓 @@ -44,6 +45,25 @@ Hap包签名工具基于Java语言开发,需要在Java8以上Java环境运行 **** #### 说明 +##### 签名相关文件用法说明 + +开发者通过IDE进行应用签名时,可在SDK中会获得如下签名相关文件: + +``` +签名密钥库文件:OpenHarmony.p12 +Profile签名证书:OpenHarmonyProfileRelease.pem、OpenHarmonyProfileDebug.pem +Profile模板文件:UnsgnedReleasedProfileTemplate.json、UnsgnedDebugProfileTemplate.json +签名工具:hap-sign-tool.jar +``` +上述文件的使用场景如下图所示。 + +**Profile签名场景:** + +![signprofile.png](figures/signprofile_zh.png) + +**应用签名场景:** + +![signapp.png](figures/signapp_zh.png) ##### 使用说明 以下说明中使用jar包为编译构建中生成的二进制文件 @@ -249,14 +269,14 @@ java -jar hap-sign-tool.jar sign-app -keyAlias "oh-app1-key-v1" -signAlg "SHA256 verify-profile : ProvisionProfile文件验签 ├── -inFile # 已签名的Provision Profile文件,p7b格式,必填项 - ├── -outFil # 验证结果文件(包含验证结果和profile内容),json格式,可选项;如果不填,则直接输出到控制台 + ├── -outFile # 验证结果文件(包含验证结果和profile内容),json格式,可选项;如果不填,则直接输出到控制台 9.hap应用包签名 sign-app : hap应用包签名 ├── -mode # 签名模式,必填项,包括localSign,remoteSign,remoteResign ├── -keyAlias # 密钥别名,必填项 - ├──-keyPwd # 密钥口令,可选项 + ├── -keyPwd # 密钥口令,可选项 ├── -appCertFile # 应用签名证书文件(证书链,顺序为最终实体证书-中间CA证书-根证书),必填项 ├── -profileFile # 签名后的Provision Profile文件名,profileSigned为1时为p7b格式,profileSigned为0时为json格式,必填项 ├── -profileSigned # 指示profile文件是否带有签名,1表示有签名,0表示没有签名,默认为1。可选项 @@ -271,7 +291,7 @@ java -jar hap-sign-tool.jar sign-app -keyAlias "oh-app1-key-v1" -signAlg "SHA256 verify-app : hap应用包文件验签 ├── -inFile # 已签名的应用包文件,zip格式或bin格式,必填项 - ├── -outCertchain # 签名的证书链文件,必填项 + ├── -outCertChain # 签名的证书链文件,必填项 ├── -outProfile # 应用包中的profile文件,必填项 diff --git a/autosign/UnsgnedReleasedProfileTemplate.json b/autosign/UnsgnedReleasedProfileTemplate.json index 71c39a35b3241f68d63f12c8842351e53baa4332..cb8e0b7e0c8d9db8db5c57621ad616bf23ab2833 100644 --- a/autosign/UnsgnedReleasedProfileTemplate.json +++ b/autosign/UnsgnedReleasedProfileTemplate.json @@ -1 +1,27 @@ -{"version-name": "1.0.0", "version-code": 1, "app-distribution-type": "os_integration", "uuid": "5027b99e-5f9e-465d-9508-a9e0134ffe18", "validity": {"not-before": 1594865258, "not-after": 1689473258}, "type": "release", "bundle-info": {"developer-id": "OpenHarmony", "distribution-certificate": "-----BEGIN CERTIFICATE-----\nMIICSTCCAc+gAwIBAgIFAJV7uNUwCgYIKoZIzj0EAwIwYzELMAkGA1UEBhMCQ04x\nFDASBgNVBAoMC09wZW5IYXJtb255MRkwFwYDVQQLDBBPcGVuSGFybW9ueSBUZWFt\nMSMwIQYDVQQDDBpPcGVuSGFybW9ueSBBcHBsaWNhdGlvbiBDQTAeFw0yMjAxMjkw\nNTU0MTRaFw0yMzAxMjkwNTU0MTRaMGgxCzAJBgNVBAYTAkNOMRQwEgYDVQQKDAtP\ncGVuSGFybW9ueTEZMBcGA1UECwwQT3Blbkhhcm1vbnkgVGVhbTEoMCYGA1UEAwwf\nT3Blbkhhcm1vbnkgQXBwbGljYXRpb24gUmVsZWFzZTBZMBMGByqGSM49AgEGCCqG\nSM49AwEHA0IABAW8pFu7tHGUuWtddD5wvazc1qN8ts9UPZH4pecbb/bSFWKh7X7R\n/eTVaRrCTSSdovI1dhoV5GjuFsKW+jT2TwSjazBpMB0GA1UdDgQWBBScyywAaAMj\nI7HcuIS42lvZx0Lj+zAJBgNVHRMEAjAAMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUE\nDDAKBggrBgEFBQcDAzAYBgwrBgEEAY9bAoJ4AQMECDAGAgEBCgEAMAoGCCqGSM49\nBAMCA2gAMGUCMFfNidGo6uK6KGT9zT1T5bY1NCHTH3P3muy5X1xudOgxWoOqIbnk\ntmQYB78dxWEHLQIxANfApAlXAD/0hnyNC8RDzfLOPEeay6jU9FXJj3AoR90rwZpR\noN9sYD6Oks4VGRw6yQ==\n-----END CERTIFICATE-----\n", "bundle-name": "com.OpenHarmony.app.test", "app-feature": "hos_system_app"}, "permissions": {"restricted-permissions": []}, "issuer": "pki_internal"} \ No newline at end of file +{ + "version-name": "2.0.0", + "version-code": 2, + "app-distribution-type": "os_integration", + "uuid": "5027b99e-5f9e-465d-9508-a9e0134ffe18", + "validity": { + "not-before": 1594865258, + "not-after": 1689473258 + }, + "type": "release", + "bundle-info": { + "developer-id": "OpenHarmony", + "distribution-certificate": "-----BEGIN CERTIFICATE-----\nMIICSTCCAc+gAwIBAgIFAJV7uNUwCgYIKoZIzj0EAwIwYzELMAkGA1UEBhMCQ04x\nFDASBgNVBAoMC09wZW5IYXJtb255MRkwFwYDVQQLDBBPcGVuSGFybW9ueSBUZWFt\nMSMwIQYDVQQDDBpPcGVuSGFybW9ueSBBcHBsaWNhdGlvbiBDQTAeFw0yMjAxMjkw\nNTU0MTRaFw0yMzAxMjkwNTU0MTRaMGgxCzAJBgNVBAYTAkNOMRQwEgYDVQQKDAtP\ncGVuSGFybW9ueTEZMBcGA1UECwwQT3Blbkhhcm1vbnkgVGVhbTEoMCYGA1UEAwwf\nT3Blbkhhcm1vbnkgQXBwbGljYXRpb24gUmVsZWFzZTBZMBMGByqGSM49AgEGCCqG\nSM49AwEHA0IABAW8pFu7tHGUuWtddD5wvazc1qN8ts9UPZH4pecbb/bSFWKh7X7R\n/eTVaRrCTSSdovI1dhoV5GjuFsKW+jT2TwSjazBpMB0GA1UdDgQWBBScyywAaAMj\nI7HcuIS42lvZx0Lj+zAJBgNVHRMEAjAAMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUE\nDDAKBggrBgEFBQcDAzAYBgwrBgEEAY9bAoJ4AQMECDAGAgEBCgEAMAoGCCqGSM49\nBAMCA2gAMGUCMFfNidGo6uK6KGT9zT1T5bY1NCHTH3P3muy5X1xudOgxWoOqIbnk\ntmQYB78dxWEHLQIxANfApAlXAD/0hnyNC8RDzfLOPEeay6jU9FXJj3AoR90rwZpR\noN9sYD6Oks4VGRw6yQ==\n-----END CERTIFICATE-----\n", + "bundle-name": "com.OpenHarmony.app.test", + "apl": "normal", + "app-feature": "hos_system_app" + }, + "acls": { + "allowed-acls": [ + "" + ] + }, + "permissions": { + "restricted-permissions": [] + }, + "issuer": "pki_internal" +} \ No newline at end of file diff --git a/autosign/autosign.py b/autosign/autosign.py index efe2e744b45f2d1a019818dc0edb447481cb6a83..f7efd367a2814dfc90a973602d36e9a24b002966 100644 --- a/autosign/autosign.py +++ b/autosign/autosign.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python +# coding=utf-8 ############################################## # Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); @@ -36,13 +38,13 @@ templates = { 'basicConstraintsPathLen'] }, 'generate-app-cert': { - 'required': ['keyAlias', 'signAlg', 'keyAlg', 'keySize', 'issuer', 'issuerKeyAlias', 'subject', 'keystoreFile', + 'required': ['keyAlias', 'signAlg', 'issuer', 'issuerKeyAlias', 'subject', 'keystoreFile', 'subCaCertFile', 'rootCaCertFile', 'outForm', 'outFile'], 'others': ['keyPwd', 'keystorePwd', 'issuerKeyPwd', 'validity', 'basicConstraintsPathLen'] }, 'generate-profile-cert': { - 'required': ['keyAlias', 'signAlg', 'keyAlg', 'keySize', 'issuer', 'issuerKeyAlias', 'subject', 'keystoreFile', + 'required': ['keyAlias', 'signAlg', 'issuer', 'issuerKeyAlias', 'subject', 'keystoreFile', 'subCaCertFile', 'rootCaCertFile', 'outForm', 'outFile'], 'others': ['keyPwd', 'keystorePwd', 'issuerKeyPwd', 'validity', 'basicConstraintsPathLen'] diff --git a/autosign/create_appcert_sign_profile.bat b/autosign/create_appcert_sign_profile.bat index 0cb6e4af45fb59676bb27cd594b1628dc0ce7270..8827300060fca01bfae3440328049d154e91311f 100644 --- a/autosign/create_appcert_sign_profile.bat +++ b/autosign/create_appcert_sign_profile.bat @@ -11,5 +11,7 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. +@echo off python autosign.py createAppCertAndProfile -pause \ No newline at end of file +pause +@echo on \ No newline at end of file diff --git a/autosign/create_root.bat b/autosign/create_root.bat index 9d21ab903862957c35568ce753c8f23d5a035222..31ab05992dfd665e36a8b45ced011691274e629d 100644 --- a/autosign/create_root.bat +++ b/autosign/create_root.bat @@ -11,5 +11,7 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. +@echo off python autosign.py createRootAndSubCert -pause \ No newline at end of file +pause +@echo on \ No newline at end of file diff --git a/autosign/sign_hap.bat b/autosign/sign_hap.bat index afca3f3b43d453ae5e7482607ca2530557d9f098..9973fd2ecc68aa23d490661cec9171afdd89f612 100644 --- a/autosign/sign_hap.bat +++ b/autosign/sign_hap.bat @@ -11,5 +11,7 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. +@echo off python autosign.py signHap -pause \ No newline at end of file +pause +@echo on \ No newline at end of file diff --git a/dist/UnsgnedReleasedProfileTemplate.json b/dist/UnsgnedReleasedProfileTemplate.json index 0aee5458ce5b96d21cd255e86ccab86ec6847b1b..4d1499bbb96c9d859cc87b3945c798f2f4009e9a 100644 --- a/dist/UnsgnedReleasedProfileTemplate.json +++ b/dist/UnsgnedReleasedProfileTemplate.json @@ -13,8 +13,8 @@ * limitations under the License. */ { - "version-name": "1.0.0", - "version-code": 1, + "version-name": "2.0.0", + "version-code": 2, "app-distribution-type": "os_integration", "uuid": "5027b99e-5f9e-465d-9508-a9e0134ffe18", "validity": { @@ -26,8 +26,14 @@ "developer-id": "OpenHarmony", "distribution-certificate": "-----BEGIN CERTIFICATE-----\nMIICMzCCAbegAwIBAgIEaOC/zDAMBggqhkjOPQQDAwUAMGMxCzAJBgNVBAYTAkNO\nMRQwEgYDVQQKEwtPcGVuSGFybW9ueTEZMBcGA1UECxMQT3Blbkhhcm1vbnkgVGVh\nbTEjMCEGA1UEAxMaT3Blbkhhcm1vbnkgQXBwbGljYXRpb24gQ0EwHhcNMjEwMjAy\nMTIxOTMxWhcNNDkxMjMxMTIxOTMxWjBoMQswCQYDVQQGEwJDTjEUMBIGA1UEChML\nT3Blbkhhcm1vbnkxGTAXBgNVBAsTEE9wZW5IYXJtb255IFRlYW0xKDAmBgNVBAMT\nH09wZW5IYXJtb255IEFwcGxpY2F0aW9uIFJlbGVhc2UwWTATBgcqhkjOPQIBBggq\nhkjOPQMBBwNCAATbYOCQQpW5fdkYHN45v0X3AHax12jPBdEDosFRIZ1eXmxOYzSG\nJwMfsHhUU90E8lI0TXYZnNmgM1sovubeQqATo1IwUDAfBgNVHSMEGDAWgBTbhrci\nFtULoUu33SV7ufEFfaItRzAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0OBBYEFPtxruhl\ncRBQsJdwcZqLu9oNUVgaMAwGCCqGSM49BAMDBQADaAAwZQIxAJta0PQ2p4DIu/ps\nLMdLCDgQ5UH1l0B4PGhBlMgdi2zf8nk9spazEQI/0XNwpft8QAIwHSuA2WelVi/o\nzAlF08DnbJrOOtOnQq5wHOPlDYB4OtUzOYJk9scotrEnJxJzGsh/\n-----END CERTIFICATE-----\n", "bundle-name": "com.OpenHarmony.app.test", + "apl": "normal", "app-feature": "hos_system_app" }, + "acls": { + "allowed-acls": [ + "" + ] + }, "permissions": { "restricted-permissions": [] }, diff --git a/dist/hap-sign-tool.jar b/dist/hap-sign-tool.jar index 0b6624bdafa3478eb0280d379017716ee22cc196..3edaa44b21a994604582ee35ffcc8e40416fa3c3 100644 Binary files a/dist/hap-sign-tool.jar and b/dist/hap-sign-tool.jar differ diff --git a/figures/signapp_en.png b/figures/signapp_en.png new file mode 100644 index 0000000000000000000000000000000000000000..cb4451a08ed183dc02c008b39130686a0a1a1860 Binary files /dev/null and b/figures/signapp_en.png differ diff --git a/figures/signapp_zh.png b/figures/signapp_zh.png new file mode 100644 index 0000000000000000000000000000000000000000..2d7b1ab5b921454e1b04d54167d6d7858d4a2da6 Binary files /dev/null and b/figures/signapp_zh.png differ diff --git a/figures/signprofile_en.png b/figures/signprofile_en.png new file mode 100644 index 0000000000000000000000000000000000000000..8ec98a504ec518fba3bc752328a50d6d5fc0e2ab Binary files /dev/null and b/figures/signprofile_en.png differ diff --git a/figures/signprofile_zh.png b/figures/signprofile_zh.png new file mode 100644 index 0000000000000000000000000000000000000000..d53e9ae389ceca4a1a03976234903258dd275c2a Binary files /dev/null and b/figures/signprofile_zh.png differ diff --git a/hapsigntool/hap_sign_tool/build.gradle b/hapsigntool/hap_sign_tool/build.gradle index 58498a33872a8fd2b6b27485e16eb39614bfbe40..3993a1ee6b97cd6739382523c5938d35f133d100 100644 --- a/hapsigntool/hap_sign_tool/build.gradle +++ b/hapsigntool/hap_sign_tool/build.gradle @@ -31,7 +31,7 @@ dependencies { testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.2' implementation group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.17.1' implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.17.1' - implementation 'com.google.code.gson:gson:2.8.6' + implementation 'com.google.code.gson:gson:2.9.0' implementation project(':hap_sign_tool_lib') } diff --git a/hapsigntool/hap_sign_tool/src/main/java/com/ohos/hapsigntool/HapSignTool.java b/hapsigntool/hap_sign_tool/src/main/java/com/ohos/hapsigntool/HapSignTool.java index 970def29cf67f2362caf413d6d613e5a290e05eb..4c8d7fb1804ad21e74816a6290a97f97d9dab36c 100644 --- a/hapsigntool/hap_sign_tool/src/main/java/com/ohos/hapsigntool/HapSignTool.java +++ b/hapsigntool/hap_sign_tool/src/main/java/com/ohos/hapsigntool/HapSignTool.java @@ -72,7 +72,7 @@ public final class HapSignTool { /** * Main entry. * - * @param args args + * @param args arguments */ public static void main(String[] args) { try { @@ -89,9 +89,9 @@ public final class HapSignTool { /** * Process command. * - * @param args args - * @return result - * @throws CustomException Failed exception + * @param args arguments + * @return command processing result + * @throws CustomException custom exception for command execution failure */ public static boolean processCmd(String[] args) throws CustomException { if (args.length == 0 || StringUtils.isEmpty(args[0])) { @@ -139,7 +139,7 @@ public final class HapSignTool { result = runProfileCert(params.getOptions(), api); break; default: - CustomException.throwException(ERROR.COMMAND_ERROR, "Not support cmd"); + CustomException.throwException(ERROR.COMMAND_ERROR, "Unsupported cmd"); break; } return result; diff --git a/hapsigntool/hap_sign_tool/src/main/java/com/ohos/hapsigntoolcmd/CmdUtil.java b/hapsigntool/hap_sign_tool/src/main/java/com/ohos/hapsigntoolcmd/CmdUtil.java index 9ec34c54c45e3737d3dd6431d0a542e3d3a81a15..b3c7aeffce8212246929470cef49bc6ab7fbcace 100644 --- a/hapsigntool/hap_sign_tool/src/main/java/com/ohos/hapsigntoolcmd/CmdUtil.java +++ b/hapsigntool/hap_sign_tool/src/main/java/com/ohos/hapsigntoolcmd/CmdUtil.java @@ -23,6 +23,7 @@ import com.ohos.hapsigntool.utils.ValidateUtils; import java.util.Arrays; import java.util.List; import java.util.Locale; +import java.util.Optional; import java.util.regex.Pattern; /** @@ -45,7 +46,7 @@ public final class CmdUtil { } /** - * Analysis and convert args to Params object. + * Analyze and convert args to Params object. * * @param args Command line args * @return Params @@ -56,10 +57,17 @@ public final class CmdUtil { Params params = new Params(); params.setMethod(args[0]); String keyStandBy = null; + List trustList = ParamsTrustlist.getTrustList(args[0]); + if (trustList.size() == 0) { + CustomException.throwException(ERROR.COMMAND_ERROR, "Unsupported cmd"); + } for (int i = 1; i < args.length; i++) { String value = args[i]; // prepare key if (value != null && (value.startsWith("-"))) { + boolean isTrust = trustList.contains(value); + ValidateUtils.throwIfNotMatches(isTrust, + ERROR.COMMAND_PARAM_ERROR, "Not support command param:" + value); keyStandBy = value.substring(1); } else { // prepare value @@ -107,9 +115,10 @@ public final class CmdUtil { } /** - * Alg size must in below scope. + * Check whether the algorithm size is within specified scope. * - * @param alg Incoming string + * @param size algorithm size + * @param alg algorithm */ public static void judgeSize(String size, String alg) { String[] array = {"2048", "3072", "4096", "NIST-P-256", "NIST-P-384"}; @@ -132,9 +141,9 @@ public final class CmdUtil { } /** - * Sign alg must in the scope. + * Check whether the signature algorithm is within specified scope. * - * @param signAlg sign alg + * @param signAlg signature algorithm */ public static void judgeSignAlgType(String signAlg) { List arrayList = Arrays.asList("SHA256withRSA", "SHA384withRSA", "SHA256withECDSA", @@ -146,9 +155,9 @@ public final class CmdUtil { } /** - * Sign alg must in the scope. + * Check whether the signature algorithm is within specified scope. * - * @param signAlg sign alg + * @param signAlg signature algorithm */ public static void judgeEndSignAlgType(String signAlg) { List arrayList = Arrays.asList("SHA256withECDSA", "SHA384withECDSA"); @@ -159,7 +168,7 @@ public final class CmdUtil { } /** - * verifyType. + * Verify target type. * * @param inputType Types with ',' * @param supportTypes Target types with ',' diff --git a/hapsigntool/hap_sign_tool/src/main/java/com/ohos/hapsigntoolcmd/ParamsTrustlist.java b/hapsigntool/hap_sign_tool/src/main/java/com/ohos/hapsigntoolcmd/ParamsTrustlist.java new file mode 100644 index 0000000000000000000000000000000000000000..e1bbf407b1cbab99fa63e06839c6e11fba670bce --- /dev/null +++ b/hapsigntool/hap_sign_tool/src/main/java/com/ohos/hapsigntoolcmd/ParamsTrustlist.java @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2021-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. + */ + +package com.ohos.hapsigntoolcmd; + +import com.ohos.hapsigntool.error.CustomException; +import com.ohos.hapsigntool.error.ERROR; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Optional; + +/** + * 入参白名单获取类 + * + * @since 2022/06/01 + */ +public final class ParamsTrustlist { + /** + * Define generic string + */ + public static final String OPTIONS = " [options]:"; + /** + * Define commond list + */ + private static final List COMMONDS = new ArrayList(); + /** + * Define trust map + */ + private static HashMap> trustMap = new HashMap<>(); + + static { + COMMONDS.add(CmdUtil.Method.GENERATE_KEYPAIR + OPTIONS); + COMMONDS.add(CmdUtil.Method.GENERATE_CSR + OPTIONS); + COMMONDS.add(CmdUtil.Method.GENERATE_CERT + OPTIONS); + COMMONDS.add(CmdUtil.Method.GENERATE_CA + OPTIONS); + COMMONDS.add(CmdUtil.Method.GENERATE_APP_CERT + OPTIONS); + COMMONDS.add(CmdUtil.Method.GENERATE_PROFILE_CERT + OPTIONS); + COMMONDS.add(CmdUtil.Method.SIGN_PROFILE + OPTIONS); + COMMONDS.add(CmdUtil.Method.VERIFY_PROFILE + OPTIONS); + COMMONDS.add(CmdUtil.Method.SIGN_APP + OPTIONS); + COMMONDS.add(CmdUtil.Method.VERIFY_APP + OPTIONS); + } + + private ParamsTrustlist() { + } + + /** + * Generate Trustlist + */ + public static void generateTrustlist() { + ClassLoader classLoader = ParamsTrustlist.class.getClassLoader(); + if (classLoader == null) { + return ; + } + String page = "help.txt"; + String str = ""; + try (InputStream inputStream = classLoader.getResourceAsStream(page)) { + if (inputStream == null) { + return ; + } + InputStreamReader isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8); + BufferedReader br = new BufferedReader(isr); + String cmdStandBy = null; + while ((str = br.readLine()) != null) { + String param = str.trim(); + if (COMMONDS.contains(param)) { + cmdStandBy = param; + } else { + boolean success = putTrustMap(cmdStandBy, param); + if (!success && cmdStandBy != null) { + cmdStandBy = null; + } + } + } + } catch (IOException ioe) { + CustomException.throwException(ERROR.READ_FILE_ERROR, "Failed to read " + page + " resource"); + } + + } + + /** + * Put trustlist map + * + * @param cmdStandBy command as key + * @param param commond as value + * @return boolean + */ + private static boolean putTrustMap(String cmdStandBy, String param) { + if (cmdStandBy != null && param.startsWith("-")) { + String subParam = param.substring(0, param.indexOf(":")).trim(); + List trustLists = Optional.ofNullable( + trustMap.get(cmdStandBy)).orElse(new ArrayList<>()); + trustLists.add(subParam); + trustMap.put(cmdStandBy, trustLists); + return true; + } + return false; + } + + /** + * Get Trustlist + * + * @param commond commond + * @return TrustList + */ + public static List getTrustList(String commond) { + generateTrustlist(); + String keyParam = commond + OPTIONS; + List list = Optional.ofNullable(trustMap.get(keyParam)).orElse(new ArrayList<>()); + return list; + } + +} diff --git a/hapsigntool/hap_sign_tool/src/main/resources/help.txt b/hapsigntool/hap_sign_tool/src/main/resources/help.txt index a34d71a98b13daca6d99244da5325714a93d5fd7..04c6466f040ba55d904878a4ae4a896c5c2c0c8a 100644 --- a/hapsigntool/hap_sign_tool/src/main/resources/help.txt +++ b/hapsigntool/hap_sign_tool/src/main/resources/help.txt @@ -23,6 +23,7 @@ USAGE: [options] -keySize : key size, required fields, the size of the RSA algorithm is 2048/3072/4096, and the size of the ECC algorithm is NIST-P-256/NIST-P-384; -keystoreFile : keystore file, required fields, JKS or P12 format; -keystorePwd : keystore password, optional fields; + -extCfgFile : Extend Profile, optional fields; EXAMPLE: generate-keypair -keyAlias "oh-app1-key-v1" -keyPwd ****** -keyAlg ECC -keySize NIST-P-256 -keystoreFile "D:\OH\app-keypair.jks" -keystorePwd ****** @@ -36,6 +37,7 @@ USAGE: [options] -keystoreFile : keystore file, required fields, JKS or P12 format; -keystorePwd : keystore password, optional fields; -outFile : output file, optional fields, if not filled, it will be directly output to the console; + -extCfgFile : Extend Profile, optional fields; EXAMPLE: generate-csr -keyAlias "oh-app1-key-v1" -keyPwd ****** -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=App1 Release" -signAlg SHA256withECDSA -keystoreFile "D:\OH\app-keypair.jks" -keystorePwd ****** -outFile "D:\OH\oh-app1-key-v1.csr" @@ -60,6 +62,9 @@ USAGE: [options] -keystoreFile : keystore file, required fields, JKS or P12 format; -keystorePwd : keystore password, optional fields; -outFile : output file, optional fields, if not filled, it will be directly output to the console; + -extCfgFile : Extend Profile, optional fields; + -issuerKeystoreFile : issuer keystore file, optional fields, JKS or P12 format; + -issuerKeystorePwd : issuer keystore password, optional fields; EXAMPLE: generate-cert -keyAlias "oh-app1-key-v1" -keyPwd ****** -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Application Signature Service CA" -issuerKeyAlias "oh-app-sign-srv-ca-key-v1" -issuerKeyPwd ****** -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=App1 Release" -validity 365 -keyUsage digitalSignature -extKeyUsage codeSignature -signAlg SHA256withECDSA -keystoreFile "D:\OH\app-keypair.jks" -keystorePwd ****** -outFile "D:\OH\app1.cer" @@ -79,6 +84,9 @@ USAGE: [options] -keystoreFile : keystore file, required fields, JKS or P12 format; -keystorePwd : keystore password, optional fields; -outFile : output file, optional fields, if not filled, it will be directly output to the console; + -extCfgFile : Extend Profile, optional fields; + -issuerKeystoreFile : issuer keystore file, optional fields, JKS or P12 format; + -issuerKeystorePwd : issuer keystore password, optional fields; EXAMPLE: generate-ca -keyAlias "oh-root-ca-key-v1" -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -validity 365 -signAlg SHA384withECDSA -keystoreFile "D:\OH\app-keypair.jks" -keystorePwd ****** -outFile "D:\OH\root-ca.cer" -keyAlg RSA -keySize 2048 @@ -100,6 +108,9 @@ USAGE: [options] -rootCaCertFile : root CA certificate file, required when outForm is certChain; -subCaCertFile : secondary sub-CA certificate file, required when outForm is certChain; -outFile : output certificate file (certificate or certificate chain), optional fields, if not filled, it will be directly output to the console; + -extCfgFile : Extend Profile, optional fields; + -issuerKeystoreFile : issuer keystore file, optional fields, JKS or P12 format; + -issuerKeystorePwd : issuer keystore password, optional fields; EXAMPLE: generate-app-cert -keyAlias "oh-app1-key-v1" -keyPwd ****** -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Application Debug Signature Service CA" -issuerKeyAlias "oh-app-sign-debug-srv-ca-key-v1" -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=App1 Debug" -validity 365 -signAlg SHA256withECDSA -rootCaCertFile "D:\OH\root-ca.cer" -subCaCertFile "D:\OH\sub-app-sign-srv-ca.cer" -keystoreFile "D:\OH\app-keypair.jks" -keystorePwd ****** -outForm certChain -outFile "D:\OH\app-debug-cert.cer" @@ -120,6 +131,9 @@ USAGE: [options] -rootCaCertFile : root CA certificate file, required when outForm is certChain; -subCaCertFile : secondary sub-CA certificate file, required when outForm is certChain; -outFile : output file, optional fields, if not filled, it will be directly output to the console; + -extCfgFile : Extend Profile, optional fields; + -issuerKeystoreFile : issuer keystore file, optional fields, JKS or P12 format; + -issuerKeystorePwd : issuer keystore password, optional fields; EXAMPLE: generate-profile-cert -keyAlias "oh-profile-key-v1" -keyPwd ****** -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Provision Profile Debug Signature Service CA" -issuerKeyAlias "oh-profile-sign-debug-srv-ca-key-v1" -issuerKeyPwd ****** -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Provision Profile Debug" -validity 365 -signAlg SHA256withECDSA -rootCaCertFile "D:\OH\root-ca.cer" -subCaCertFile "D:\OH\sub-profile-sign-srv-ca.cer" -keystoreFile "D:\OH\profile-keypair.jks" -keystorePwd ****** -outForm certChain -outFile "D:\OH\provision-profile-debug.cer" @@ -135,6 +149,7 @@ USAGE: [options] -keystoreFile : keystore file, if signature mode is localSign, required fields, JKS or P12 format; -keystorePwd : keystore password, optional fields; -outFile : output the signed Provision Profile file, p7b format, required fields; + -extCfgFile : Extend Profile, optional fields; EXAMPLE: sign-profile -mode localSign -keyAlias "oh-profile-key-v1" -keyPwd ****** -profileCertFile "D:\OH\provision-profile-release.cer" -inFile "D:\OH\app1-profile-release.json" -signAlg SHA256withECDSA -keystoreFile "D:\OH\profile-keypair.jks" -keystorePwd ****** -outFile "D:\OH\signed-profile.p7b" @@ -142,6 +157,7 @@ USAGE: [options] verify-profile [options]: -inFile : signed Provision Profile file, p7b format, required fields; -outFile : Verification result file (including verification result and profile content), json format, optional; if not filled, it will be directly output to the console; + -extCfgFile : Extend Profile, optional fields; EXAMPLE: verify-profile -inFile "D:\OH\signed-profile.p7b" -outFile "D:\OH\VerifyResult.json" @@ -150,13 +166,16 @@ USAGE: [options] -mode : signature mode, required fields, including localSign/remoteSign/remoteResign; -keyAlias : key alias, required fields; -keyPwd : key password, optional fields; - -appCertFIle : application signature certificate file, required fields; + -appCertFile : application signature certificate file, required fields; -profileFile : signed Provision Profile file, p7b format, required fields; + -profileSigned : indicates whether the profile file has a signture.The options are as follows: 1:yes; 0:no; defalut value:1. optional fields; -inFile : input original application package file, hap or bin format, required fields; -signAlg : signature algorithm, required fields, including SHA256withRSA/SHA384withRSA/SHA256withECDSA/SHA384withECDSA; -keystoreFile : keystore file, if signature mode is localSign, required fields, JKS or P12 format; -keystorePwd : keystore password, optional fields; -outFile : output the signed Provision Profile file, required fields; + -extCfgFile : Extend Profile, optional fields; + -inForm : enter the format of the origianl file, the format is .zip or .bin; EXAMPLE: sign-app -mode localSign -keyAlias "oh-app1-key-v1" -appCertFile "D:\OH\app-release-cert.cer" -profileFile "D:\OH\signed-profile.p7b" -inFile "D:\OH\app1-unsigned.hap" -signAlg SHA256withECDSA -keystoreFile "D:\OH\app-keypair.jks" -keystorePwd ****** -outFile "D:\OH\app1-signed.hap" @@ -165,6 +184,7 @@ USAGE: [options] -inFile : signed application package file, hap or bin format, required fields; -outCertchain : signed certificate chain file, required fields; -outProfile : profile file in application package, required fields; + -extCfgFile : Extend Profile, optional fields; EXAMPLE: verify-app -inFile "D:\OH\app1-signed.hap" -outcertchain "outCertchain.cer" -outProfile "outprofile.p7b" diff --git a/hapsigntool/hap_sign_tool_lib/build.gradle b/hapsigntool/hap_sign_tool_lib/build.gradle index c601bca86ef4b0db7b54ec973bf3ebf8d8333ccf..38786419bfe12242d5439d94de7aea8f55b8e7c6 100644 --- a/hapsigntool/hap_sign_tool_lib/build.gradle +++ b/hapsigntool/hap_sign_tool_lib/build.gradle @@ -31,7 +31,7 @@ dependencies { implementation group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.17.1' implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.17.1' implementation 'org.bouncycastle:bcpkix-jdk15on:1.69' - implementation 'com.google.code.gson:gson:2.8.6' + implementation 'com.google.code.gson:gson:2.9.0' } test { diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/api/LocalizationAdapter.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/api/LocalizationAdapter.java index b3df06bde38251020d5e6eeac193a6207ca07770..a60a38fe784ea6ed9c2c101d3645172b1407c33d 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/api/LocalizationAdapter.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/api/LocalizationAdapter.java @@ -46,7 +46,7 @@ import java.util.List; */ public class LocalizationAdapter { /** - * check cert chain size + * Check cert chain size */ private static final int MIN_CERT_CHAIN_SIZE = 2; private static final int MAX_CERT_CHAIN_SIZE = 3; @@ -134,9 +134,9 @@ public class LocalizationAdapter { } /** - * getIssuerAliasKey. + * Get the alias of issuer key. * - * @return param of issuerKeyAlias + * @return param of issuer alias key . */ public KeyPair getIssuerAliasKey() { return getKeyPair(options.getString(Options.ISSUER_KEY_ALIAS), @@ -144,9 +144,9 @@ public class LocalizationAdapter { } /** - * Keystore has alias or not. + * Check whether the keystore has alias or not. * - * @param alias alias + * @param alias alias of key * @return true or false */ public boolean hasAlias(String alias) { @@ -196,16 +196,16 @@ public class LocalizationAdapter { keyStoreHelper.store(alias, keyPwd, keyPair, null); } } - ValidateUtils.throwIfNotMatches(keyPair != null, ERROR.NOT_SUPPORT_ERROR, + ValidateUtils.throwIfNotMatches(keyPair != null, ERROR.PARAM_NOT_EXIST_ERROR, String.format("%s: '%s' is not exist in %s", Options.KEY_ALIAS, alias, keyStoreHelper.getKeyStorePath())); return keyPair; } /** - * getProfileCert. + * Get profile cert. * - * @return profile cert + * @return profile cert. */ public List getSignCertChain() { String certPath = options.getString(Options.PROFILE_CERT_FILE); @@ -222,9 +222,9 @@ public class LocalizationAdapter { } /** - * getSubCaCertFile. + * Get the cert file of sub ca. * - * @return sub ca cert + * @return the cert file of sub ca. */ public X509Certificate getSubCaCertFile() { String certPath = options.getString(Options.SUB_CA_CERT_FILE); @@ -232,9 +232,9 @@ public class LocalizationAdapter { } /** - * getCaCertFile. + * Get the cert file of root ca. * - * @return root ca cert + * @return the cert file of root ca. */ public X509Certificate getCaCertFile() { String certPath = options.getString(Options.CA_CERT_FILE); @@ -242,9 +242,9 @@ public class LocalizationAdapter { } /** - * isOutFormChain. + * Check whether the form is cert chain. * - * @return is out form chain + * @return result indicating whether the form is cert chain. */ public boolean isOutFormChain() { String outForm = options.getString(Options.OUT_FORM, "certChain"); @@ -254,17 +254,17 @@ public class LocalizationAdapter { /** * Get certificates from file. * - * @param certPath certPath - * @param logTitle logTitle + * @param certPath the path of cert + * @param logTitle log title * @return certificates */ public List getCertsFromFile(String certPath, String logTitle) { - ValidateUtils.throwIfNotMatches(!StringUtils.isEmpty(certPath), ERROR.NOT_SUPPORT_ERROR, - String.format("Params '%s' is not exist", logTitle)); + ValidateUtils.throwIfNotMatches(!StringUtils.isEmpty(certPath), ERROR.PARAM_NOT_EXIST_ERROR, + String.format("Params '%s' not exist", logTitle)); File certFile = new File(certPath); ValidateUtils.throwIfNotMatches(certFile.exists(), ERROR.FILE_NOT_FOUND, - String.format("%s: '%s' is not exist", logTitle, certPath)); + String.format("%s: '%s' not exist", logTitle, certPath)); List certificates = null; try { certificates = CertUtils.generateCertificates(FileUtils.readFile(certFile)); @@ -278,81 +278,81 @@ public class LocalizationAdapter { } /** - * getSignAlg. + * Get signature algorithm. * - * @return sign alg + * @return signature algorithm. */ public String getSignAlg() { return options.getString(Options.SIGN_ALG); } /** - * isKeyUsageCritical. + * Check whether the key usage is critical. * - * @return isKeyUsageCritical + * @return result indicating whether the key usage is critical. */ public boolean isKeyUsageCritical() { return options.getBoolean(Options.KEY_USAGE_CRITICAL, true); } /** - * isExtKeyUsageCritical. + * Check whether the external key usage is critical. * - * @return isExtKeyUsageCritical + * @return result indicating whether the external key usage is critical. */ public boolean isExtKeyUsageCritical() { return options.getBoolean(Options.EXT_KEY_USAGE_CRITICAL, true); } /** - * isBasicConstraintsCa. + * Check whether the basic constraints is ca. * - * @return isBasicConstraintsCa + * @return result indicating whether the basic constraints is ca. */ public boolean isBasicConstraintsCa() { return options.getBoolean(Options.BASIC_CONSTRAINTS_CA, false); } /** - * isBasicConstraintsCritical + * Check whether the basic constraints is critical. * - * @return isBasicConstraintsCritical + * @return result indicating whether the basic constraints is critical. */ public boolean isBasicConstraintsCritical() { return options.getBoolean(Options.BASIC_CONSTRAINTS_CRITICAL, false); } /** - * getBasicConstraintsPathLen. + * Get the path length of basic constraints. * - * @return BasicConstraintsPathLen + * @return the path length of basic constraints. */ public int getBasicConstraintsPathLen() { return options.getInt(Options.BASIC_CONSTRAINTS_PATH_LEN); } /** - * getExtKeyUsage. + * Get the external key usage. * - * @return KeyPurposeId[] of ExtKeyUsage + * @return KeyPurposeId[] of ExtKeyUsage. */ public KeyPurposeId[] getExtKeyUsage() { return CertUtils.parseExtKeyUsage(options.getString(Options.EXT_KEY_USAGE)); } /** - * getKeyUsage. + * Get the key usage. * - * @return KeyUsage + * @return the key usage. */ public KeyUsage getKeyUsage() { return new KeyUsage(CertUtils.parseKeyUsage(options.getString(Options.KEY_USAGE))); } /** - * getSubject. + * Get the subject of cert. * - * @return Subject + * @return the subject of cert. */ public X500Name getSubject() { String subject = options.getString(Options.SUBJECT); @@ -360,8 +360,9 @@ public class LocalizationAdapter { } /** - * getIssuer. - * @return Issuer + * Get the subject of issuer. + * + * @return the subject of issuer. */ public X500Name getIssuer() { String issuer = options.getString(Options.ISSUER, options.getString(Options.SUBJECT)); @@ -369,18 +370,18 @@ public class LocalizationAdapter { } /** - * getOutFile. + * Get the output file. * - * @return OutFile + * @return the string of output file. */ public String getOutFile() { return options.getString(Options.OUT_FILE); } /** - * getInFile. + * Get the input file. * - * @return InFile + * @return the string of input file. */ public String getInFile() { String file = options.getString(Options.IN_FILE); @@ -390,9 +391,9 @@ public class LocalizationAdapter { } /** - * isRemoteSigner. + * Check if it is a remote signature. * - * @return isRemoteSigner + * @return result indicating whether the signer is a remote signer. */ public boolean isRemoteSigner() { String mode = options.getString(Options.MODE, "localSign"); @@ -400,7 +401,7 @@ public class LocalizationAdapter { } /** - * Reset pwd to keep security + * Reset the password to ensure security. */ public void releasePwd() { resetChars(options.getChars(Options.KEY_STORE_RIGHTS)); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/api/ServiceApi.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/api/ServiceApi.java index b0a3fa7ff6bdd02ac459ef6b2f81203b52c6ffa1..a62f1f5175922c74151641ea04dcfaed29dda2ca 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/api/ServiceApi.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/api/ServiceApi.java @@ -24,10 +24,10 @@ import com.ohos.hapsigntool.api.model.Options; */ public interface ServiceApi { /** - * Generate keyStore. + * Generate keystore. * * @param options options - * @return Generate or not + * @return Result indicating whether the keystore is generated. */ boolean generateKeyStore(Options options); @@ -35,7 +35,7 @@ public interface ServiceApi { * Generate csr. * * @param options options - * @return Generate or not + * @return Result indicating whether the csr is generated. */ boolean generateCsr(Options options); @@ -43,7 +43,7 @@ public interface ServiceApi { * Generate cert. * * @param options options - * @return Generate or not + * @return Result indicating whether the cert is generated. */ boolean generateCert(Options options); @@ -51,7 +51,7 @@ public interface ServiceApi { * Generate CA. * * @param options options - * @return Generate or not + * @return Result indicating whether the CA is generated. */ boolean generateCA(Options options); @@ -59,7 +59,7 @@ public interface ServiceApi { * Generate app cert. * * @param options options - * @return Generate or not + * @return Result indicating whether the app cert is generated. */ boolean generateAppCert(Options options); @@ -67,7 +67,7 @@ public interface ServiceApi { * Generate profile cert. * * @param options options - * @return Generate or not + * @return Result indicating whether the profile cert is generated. */ boolean generateProfileCert(Options options); @@ -75,7 +75,7 @@ public interface ServiceApi { * Sign for profile. * * @param options options - * @return Sign or not + * @return Result indicating whether the profile is signed. */ boolean signProfile(Options options); @@ -83,7 +83,7 @@ public interface ServiceApi { * Verify profile. * * @param options options - * @return Verify or not + * @return Result indicating whether the profile is correct. */ boolean verifyProfile(Options options); @@ -91,7 +91,7 @@ public interface ServiceApi { * Sign for hap. * * @param options options - * @return Sign or not + * @return Result indicating whether the HAP is signed. */ boolean signHap(Options options); @@ -99,7 +99,7 @@ public interface ServiceApi { * Verify hap. * * @param options options - * @return Verify or not + * @return Result indicating whether the HAP is correct. */ boolean verifyHap(Options options); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/cert/CertBuilder.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/cert/CertBuilder.java index 23bdf7b70a1249361a29ff67d0e1d70262a66981..4d178d72c9feb36d4f746d8322a131141747c866 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/cert/CertBuilder.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/cert/CertBuilder.java @@ -88,7 +88,7 @@ public class CertBuilder { request = new PKCS10CertificationRequest(csr); } catch (IOException exception) { logger.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); + CustomException.throwException(ERROR.IO_CSR_ERROR, exception.getMessage()); } x509v3CertificateBuilder = new X509v3CertificateBuilder( issuer, CertUtils.randomSerial(), Date.from(notBefore.atZone(ZoneId.systemDefault()).toInstant()), @@ -98,9 +98,12 @@ public class CertBuilder { JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(request.getSubjectPublicKeyInfo())); - } catch (NoSuchAlgorithmException | CertIOException exception) { + } catch (NoSuchAlgorithmException exception) { logger.debug(exception.getMessage(), exception); CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); + } catch (CertIOException exception) { + logger.debug(exception.getMessage(), exception); + CustomException.throwException(ERROR.IO_CERT_ERROR, exception.getMessage()); } } @@ -118,9 +121,12 @@ public class CertBuilder { extUtils.createAuthorityKeyIdentifier(SubjectPublicKeyInfo .getInstance(keyPair.getPublic().getEncoded()))); } - } catch (NoSuchAlgorithmException | CertIOException exception) { + } catch (NoSuchAlgorithmException exception) { logger.debug(exception.getMessage(), exception); CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); + } catch (CertIOException exception) { + logger.debug(exception.getMessage(), exception); + CustomException.throwException(ERROR.IO_CERT_ERROR, exception.getMessage()); } return this; } @@ -209,8 +215,16 @@ public class CertBuilder { cert = new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(x509v3CertificateBuilder.build(contentSigner)); cert.verify(keyPair.getPublic()); - } catch (CertificateException | NoSuchAlgorithmException | SignatureException - | InvalidKeyException | NoSuchProviderException exception) { + } catch (InvalidKeyException exception) { + logger.debug(exception.getMessage(), exception); + CustomException.throwException(ERROR.KEY_ERROR, exception.getMessage()); + } catch (SignatureException exception) { + logger.debug(exception.getMessage(), exception); + CustomException.throwException(ERROR.SIGN_ERROR, exception.getMessage()); + } catch (CertificateException exception) { + logger.debug(exception.getMessage(), exception); + CustomException.throwException(ERROR.CERTIFICATE_ERROR, exception.getMessage()); + } catch (NoSuchAlgorithmException | NoSuchProviderException exception) { logger.debug(exception.getMessage(), exception); CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); } diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/cert/CertTools.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/cert/CertTools.java index 5e1061cddf64c6e51653b8a365a372a3dedc8aae..a648bb3c1218ae1a6a8bd95364210aeb9295d9a8 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/cert/CertTools.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/cert/CertTools.java @@ -49,12 +49,12 @@ import java.util.regex.Pattern; */ public final class CertTools { /** - * Ten years days. + * Ten years, in days. */ private static final int TEN_YEAR_DAY = 3650; /** - * Three years dats. + * Three years, in dats. */ private static final int THREE_YEAR_DAY = 1095; @@ -101,7 +101,7 @@ public final class CertTools { .build(adapter.getSignAlg()); } catch (IOException exception) { LOGGER.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); + CustomException.throwException(ERROR.IO_CERT_ERROR, exception.getMessage()); } return null; } @@ -125,7 +125,7 @@ public final class CertTools { .build(adapter.getSignAlg()); } catch (IOException exception) { LOGGER.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); + CustomException.throwException(ERROR.IO_CERT_ERROR, exception.getMessage()); } return null; } @@ -153,7 +153,7 @@ public final class CertTools { .build(adapter.getSignAlg()); } catch (IOException exception) { LOGGER.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); + CustomException.throwException(ERROR.IO_CERT_ERROR, exception.getMessage()); } return null; } @@ -179,7 +179,7 @@ public final class CertTools { .build(adapter.getSignAlg()); } catch (IOException exception) { LOGGER.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); + CustomException.throwException(ERROR.IO_CERT_ERROR, exception.getMessage()); } return null; } @@ -201,7 +201,7 @@ public final class CertTools { return csr.getEncoded(); } catch (IOException exception) { LOGGER.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, "Not support " + subject); + CustomException.throwException(ERROR.IO_CSR_ERROR, "Not support " + subject); return NO_CSR; } } @@ -231,10 +231,9 @@ public final class CertTools { return jcaContentSignerBuilder.build(privateKey); } catch (OperatorCreationException exception) { LOGGER.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, "Not support " + signAlgorithm); + CustomException.throwException(ERROR.OPERATOR_CREATION_ERROR, exception.getMessage()); } return null; } - } diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/error/ERROR.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/error/ERROR.java index e3819527ef6a3ed9029e2bd3aaf1b944a73aaffd..2d7fe1b9617a47353c682ca1844d8cac363f8012 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/error/ERROR.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/error/ERROR.java @@ -56,8 +56,39 @@ public enum ERROR { /** * Enum constant ACCESS_ERROR. */ - ACCESS_ERROR(109); - + ACCESS_ERROR(109), + /** + * Enum constant COMMAND_PARAM_ERROR. + */ + COMMAND_PARAM_ERROR(110), + /** + *Enum constant OPERATOR_CREATION_ERROR. + */ + OPERATOR_CREATION_ERROR(111), + /** + *Enum constant PARAM_NOT_EXIST_ERROR. + */ + PARAM_NOT_EXIST_ERROR(113), + /** + *Enum constant KEYSTORE_OPERATION_ERROR. + */ + KEYSTORE_OPERATION_ERROR(114), + /** + *Enum constant CERTIFICATE_ERROR. + */ + CERTIFICATE_ERROR(115), + /** + *Enum constant KEY_ERROR. + */ + KEY_ERROR(116), + /** + *Enum constant IO_CERT_ERROR. + */ + IO_CERT_ERROR(117), + /** + *Enum constant IO_CSR_ERROR. + */ + IO_CSR_ERROR(118); /** * Field errorCode. */ diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/HapFormatException.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/HapFormatException.java index bdf096601e3ec78a6dfcc42bd7299ebc90a2c199..284ba3090cdd8c0b15f2915897a8bc913992c6fb 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/HapFormatException.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/HapFormatException.java @@ -18,7 +18,7 @@ package com.ohos.hapsigntool.hap.exception; import com.ohos.hapsigntool.utils.ParamConstants; /** - * Exception Hap file format exception + * Exception that occurs if the Hap file format is incorrect. * * @since 2021/12/20 */ diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/InvalidParamsException.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/InvalidParamsException.java index 9c58e1796159a4d2fc4fbe86aed6e5ad91b62d07..1d3bf2c5d3f5012c9b8faaca9fd2b1cc4d03bf43 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/InvalidParamsException.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/InvalidParamsException.java @@ -16,7 +16,7 @@ package com.ohos.hapsigntool.hap.exception; /** - * Exception occurs when the input parameters are invalid + * Exception that occurs when the input parameters are invalid. * * @since 2021/12/20 */ diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/MissingParamsException.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/MissingParamsException.java index 06078b0ea1e5d5c639b90b73b946ace5ee0a4196..3656c5b826c028eac477b0de73ed8931abf70e40 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/MissingParamsException.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/MissingParamsException.java @@ -16,7 +16,7 @@ package com.ohos.hapsigntool.hap.exception; /** - * Exception occurs when the required parameters aren't entered. + * Exception that occurs when the required parameters are missing. * * @since 2021/12/20 */ diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/ProfileException.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/ProfileException.java index b68acd83264042f55f7afd3163f1e01e32f7b99c..db8cbc1b8e7d11bb21c886cd0a9b0a10a9c39f42 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/ProfileException.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/ProfileException.java @@ -16,7 +16,7 @@ package com.ohos.hapsigntool.hap.exception; /** - * Exception occurs when profile is invalid + * Exception that occurs if the profile is invalid. * * @since 2021/12/20 */ diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/SignatureException.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/SignatureException.java index 15602de09d305af8686bda8535a8a77a945d16a2..a97d76880d2a736bc1dbc8d4a58b83681cf46532 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/SignatureException.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/SignatureException.java @@ -16,7 +16,7 @@ package com.ohos.hapsigntool.hap.exception; /** - * Signature exception + * Exception that occurs if the signature is invalid. * * @since 2021/12/20 */ diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/SignatureNotFoundException.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/SignatureNotFoundException.java index efd1194e041589f11d257c38bd74e673bb0643ab..a170abe52fcef712430c8689cab03aff2fdf1d65 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/SignatureNotFoundException.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/SignatureNotFoundException.java @@ -16,7 +16,7 @@ package com.ohos.hapsigntool.hap.exception; /** - * Exception to find signature in the signed hap file + * Exception that occurs when finding signature in the signed hap file. * * @since 2021/12/20 */ diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/VerifyCertificateChainException.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/VerifyCertificateChainException.java index 3a06dee50157e4fc80950a750cbfb8f6369f5b54..996778f2deb6868d1e4510f6f470dfb7973b87aa 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/VerifyCertificateChainException.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/exception/VerifyCertificateChainException.java @@ -16,7 +16,7 @@ package com.ohos.hapsigntool.hap.exception; /** - * Exception occurs when verify certificate chains + * Exception that occurs when verifying certificate chains. * * @since 2021/12/20 */ diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/LocalJKSSignProvider.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/LocalJKSSignProvider.java index 21a81086cfc1a826c0b5b6d2272741e0865e831e..7fd9a80eb628bee3f070121f7e00e03956bd1e30 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/LocalJKSSignProvider.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/LocalJKSSignProvider.java @@ -21,7 +21,6 @@ import com.ohos.hapsigntool.hap.exception.MissingParamsException; import com.ohos.hapsigntool.utils.FileUtils; import com.ohos.hapsigntool.utils.ParamConstants; import com.ohos.hapsigntool.utils.ParamProcessUtil; -import com.ohos.hapsigntool.utils.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -32,6 +31,7 @@ import java.security.GeneralSecurityException; import java.security.cert.CRL; import java.security.cert.CertificateFactory; import java.security.cert.X509CRL; +import java.util.Optional; import java.util.Set; /** @@ -43,18 +43,18 @@ public class LocalJKSSignProvider extends SignProvider { private static final Logger LOGGER = LogManager.getLogger(LocalJKSSignProvider.class); @Override - public X509CRL getCrl() { + public Optional getCrl() { X509CRL crl = null; String crlPath = signParams.get(ParamConstants.PARAM_BASIC_CRL); if (crlPath == null || "".equals(crlPath)) { - return crl; + return Optional.ofNullable(crl); } try (FileInputStream input = new FileInputStream(new File(crlPath));) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); CRL baseCrl = cf.generateCRL(input); if (!(baseCrl instanceof X509CRL)) { LOGGER.error("crl is not X509CRL"); - return crl; + return Optional.ofNullable(crl); } crl = (X509CRL) baseCrl; } catch (IOException e) { @@ -64,7 +64,7 @@ public class LocalJKSSignProvider extends SignProvider { LOGGER.error("Generate x509 CRL failed!"); crl = null; } - return crl; + return Optional.ofNullable(crl); } /** @@ -79,7 +79,7 @@ public class LocalJKSSignProvider extends SignProvider { FileUtils.isValidFile(publicKeyFile); } catch (IOException e) { LOGGER.error("file is invalid: " + publicCertsFile + System.lineSeparator(), e); - throw new InvalidParamsException("Invalid file: " + publicCertsFile); + throw new InvalidParamsException("Invalid file: " + publicCertsFile); } } diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/RemoteSignProvider.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/RemoteSignProvider.java index 1b53f650e2857462b70f378307a9bf7799bfd22d..ef7cd7ff6db93d750e88f9be0553e9475946d4ee 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/RemoteSignProvider.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/RemoteSignProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2021-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 @@ -21,6 +21,9 @@ import com.ohos.hapsigntool.hap.exception.MissingParamsException; import java.security.cert.X509Certificate; +/** + * Remote Sign Provider + */ public class RemoteSignProvider extends SignProvider { @Override public void checkParams(Options options) throws MissingParamsException, InvalidParamsException { diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/SignProvider.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/SignProvider.java index 97f869fabb20382a13a53fedce7817be469721a3..dbc70d254f65a80bd8a89d61955e929347761c07 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/SignProvider.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/provider/SignProvider.java @@ -74,6 +74,7 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; +import java.util.Optional; import java.util.jar.JarFile; import java.util.jar.JarOutputStream; @@ -88,6 +89,25 @@ public abstract class SignProvider { private static final List PARAMETERS_NEED_ESCAPE = new ArrayList(); private static final long TIMESTAMP = 1230768000000L; private static final int COMPRESSION_MODE = 9; + + static { + VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA256_ECDSA); + VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA384_ECDSA); + VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA512_ECDSA); + VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA256_RSA_PSS); + VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA384_RSA_PSS); + VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA512_RSA_PSS); + VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA256_RSA_MGF1); + VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA384_RSA_MGF1); + VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA512_RSA_MGF1); + } + + static { + PARAMETERS_NEED_ESCAPE.add(ParamConstants.PARAM_REMOTE_CODE); + PARAMETERS_NEED_ESCAPE.add(ParamConstants.PARAM_LOCAL_JKS_KEYSTORE_CODE); + PARAMETERS_NEED_ESCAPE.add(ParamConstants.PARAM_LOCAL_JKS_KEYALIAS_CODE); + } + /** * list of hap signature optional blocks */ @@ -137,6 +157,7 @@ public abstract class SignProvider { /** * check if the input path is a file + * * @param filePath input file path * @return true, if path is a file and can be read */ @@ -175,8 +196,8 @@ public abstract class SignProvider { * * @return certificate revocation list */ - public X509CRL getCrl() { - return null; + public Optional getCrl() { + return Optional.empty(); } /** @@ -184,10 +205,11 @@ public abstract class SignProvider { * * @param certificates certificate chain * @param crl certificate revocation list + * @param options options * @return Object of SignerConfig * @throws InvalidKeyException on error when the key is invalid. */ - public SignerConfig createSignerConfigs(List certificates, X509CRL crl, Options options) + public SignerConfig createSignerConfigs(List certificates, Optional crl, Options options) throws InvalidKeyException { SignerConfig signerConfig = new SignerConfig(); signerConfig.fillParameters(this.signParams); @@ -199,8 +221,8 @@ public abstract class SignProvider { ParamProcessUtil.getSignatureAlgorithm(this.signParams.get(ParamConstants.PARAM_BASIC_SIGANTURE_ALG))); signerConfig.setSignatureAlgorithms(signatureAlgorithms); - if (crl != null) { - signerConfig.setX509CRLs(Collections.singletonList(crl)); + if (!crl.equals(Optional.empty())) { + signerConfig.setX509CRLs(Collections.singletonList(crl.get())); } return signerConfig; } @@ -216,21 +238,12 @@ public abstract class SignProvider { List publicCert = null; SignerConfig signerConfig; try { - // 1. check the parameters - checkParams(options); - - // 2. load optionalBlocks - loadOptionalBlocks(); + publicCert = getX509Certificates(options); - // 3. get x509 verify certificate - publicCert = getPublicCerts(); + // Get x509 CRL + Optional crl = getCrl(); - checkProfileValid(publicCert); - - // 4. Get x509 CRL - X509CRL crl = getCrl(); - - // 5. Create signer configs, which contains public cert and crl info. + // Create signer configs, which contains public cert and crl info. signerConfig = createSignerConfigs(publicCert, crl, options); } catch (InvalidKeyException | InvalidParamsException | MissingParamsException | ProfileException e) { LOGGER.error("create signer configs failed.", e); @@ -258,27 +271,17 @@ public abstract class SignProvider { List publicCerts = null; File output = null; File tmpOutput = null; - boolean ret = false; - boolean pathOverlap = false; + boolean isRet = false; + boolean isPathOverlap = false; try { - // 1. check the parameters - checkParams(options); - - // 2. get x509 verify certificate - publicCerts = getPublicCerts(); - - // 3. load optionalBlocks - loadOptionalBlocks(); + publicCerts = getX509Certificates(options); - checkProfileValid(publicCerts); - - X509CRL crl = getCrl(); File input = new File(signParams.get(ParamConstants.PARAM_BASIC_INPUT_FILE)); output = new File(signParams.get(ParamConstants.PARAM_BASIC_OUTPUT_FILE)); if (input.getCanonicalPath().equals(output.getCanonicalPath())) { tmpOutput = File.createTempFile("signedHap", ".hap"); tmpOutput.deleteOnExit(); - pathOverlap = true; + isPathOverlap = true; } else { tmpOutput = output; } @@ -298,6 +301,7 @@ public abstract class SignProvider { ByteBuffer eocdBuffer = zipInfo.getEocd(); ZipDataInput eocd = new ByteBufferZipDataInput(eocdBuffer); + Optional crl = getCrl(); SignerConfig signerConfig = createSignerConfigs(publicCerts, crl, options); ZipDataInput[] contents = {beforeCentralDir, centralDirectory, eocd}; byte[] signingBlock = SignHap.sign(contents, signerConfig, optionalBlocks); @@ -306,18 +310,38 @@ public abstract class SignProvider { LOGGER.info("Generate signing block success, begin write it to output file"); outputSignedFile(outputHap, centralDirectoryOffset, signingBlock, centralDirectory, eocdBuffer); - ret = true; + isRet = true; } } catch (IOException | InvalidKeyException | HapFormatException | MissingParamsException | InvalidParamsException | ProfileException | CustomException e) { printErrorLogWithoutStack(e); - ret = false; + isRet = false; } catch (SignatureException e) { printErrorLog(e); - ret = false; + isRet = false; } + return doAfterSign(isRet, isPathOverlap, tmpOutput, output); + } - return doAfterSign(ret, pathOverlap, tmpOutput, output); + /** + * + * @param options parameters used to sign hap file + * @return list of type x509certificate + * @throws MissingParamsException Exception occurs when the required parameters are not entered. + * @throws InvalidParamsException Exception occurs when the required parameters are invalid. + * @throws ProfileException Exception occurs when profile is invalid. + */ + private List getX509Certificates(Options options) throws MissingParamsException, + InvalidParamsException, ProfileException { + List publicCerts; + // 1. check the parameters + checkParams(options); + // 2. get x509 verify certificate + publicCerts = getPublicCerts(); + // 3. load optionalBlocks + loadOptionalBlocks(); + checkProfileValid(publicCerts); + return publicCerts; } private void outputSignedFile(RandomAccessFile outputHap, long centralDirectoryOffset, @@ -329,37 +353,45 @@ public abstract class SignProvider { } private boolean doAfterSign(boolean isSuccess, boolean pathOverlap, File tmpOutput, File output) { - boolean ret = isSuccess; - if (ret && pathOverlap) { + boolean isRet = isSuccess; + if (isRet && pathOverlap) { try { Files.move(tmpOutput.toPath(), output.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { printErrorLog(e); - ret = false; + isRet = false; } } - if ((!ret) && (!pathOverlap) && (output != null)) { + if ((!isRet) && (!pathOverlap) && (output != null)) { output.deleteOnExit(); } - if (ret) { + if (isRet) { LOGGER.info("Sign Hap success!"); } - return ret; + return isRet; } - private void printErrorLog(Exception e) { - if (e != null) { - LOGGER.error("hap-sign-tool: error: {}", e.getMessage(), e); + private void printErrorLog(Exception exception) { + if (exception != null) { + LOGGER.error("hap-sign-tool: error: {}", exception.getMessage(), exception); } } - private void printErrorLogWithoutStack(Exception e) { - if (e != null) { - LOGGER.error("hap-sign-tool: error: {}", e.getMessage()); + private void printErrorLogWithoutStack(Exception exception) { + if (exception != null) { + LOGGER.error("hap-sign-tool: error: {}", exception.getMessage()); } } + /** + * Copy file and alignment + * + * @param input file input + * @param tmpOutput file tmpOutput + * @param alignment alignment + * @throws IOException io error + */ private void copyFileAndAlignment(File input, File tmpOutput, int alignment) throws IOException { try (JarFile inputJar = new JarFile(input, false); FileOutputStream outputFile = new FileOutputStream(tmpOutput); @@ -372,25 +404,13 @@ public abstract class SignProvider { } } - static { - VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA256_ECDSA); - VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA384_ECDSA); - VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA512_ECDSA); - VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA256_RSA_PSS); - VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA384_RSA_PSS); - VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA512_RSA_PSS); - VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA256_RSA_MGF1); - VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA384_RSA_MGF1); - VALID_SIGN_ALG_NAME.add(ParamConstants.HAP_SIG_ALGORITHM_SHA512_RSA_MGF1); - } - /** * check signature algorithm * * @throws InvalidParamsException Exception occurs when the inputted sign algorithm is invalid. */ private void checkSignatureAlg() throws InvalidParamsException { - String signAlg = signParams.get( ParamConstants.PARAM_BASIC_SIGANTURE_ALG).trim(); + String signAlg = signParams.get(ParamConstants.PARAM_BASIC_SIGANTURE_ALG).trim(); for (String validAlg : VALID_SIGN_ALG_NAME) { if (validAlg.equalsIgnoreCase(signAlg)) { return; @@ -473,8 +493,8 @@ public abstract class SignProvider { String content; if (!isProfileWithoutSign) { CMSSignedData cmsSignedData = new CMSSignedData(profile); - boolean verifyResult = VerifyUtils.verifyCmsSignedData(cmsSignedData); - if (!verifyResult) { + boolean isVerify = VerifyUtils.verifyCmsSignedData(cmsSignedData); + if (!isVerify) { throw new ProfileException("Verify profile pkcs7 failed! Profile is invalid."); } Object contentObj = cmsSignedData.getSignedContent().getContent(); @@ -566,12 +586,6 @@ public abstract class SignProvider { checkSignAlignment(); } - static { - PARAMETERS_NEED_ESCAPE.add(ParamConstants.PARAM_REMOTE_CODE); - PARAMETERS_NEED_ESCAPE.add(ParamConstants.PARAM_LOCAL_JKS_KEYSTORE_CODE); - PARAMETERS_NEED_ESCAPE.add(ParamConstants.PARAM_LOCAL_JKS_KEYALIAS_CODE); - } - /** * Get parameters from inputted strings. This function unescape some escaped parameters and return it. * @@ -580,7 +594,7 @@ public abstract class SignProvider { * @return parameter value in the correct form. */ protected String getParamValue(String paramName, String paramValue) { - for ( String name : PARAMETERS_NEED_ESCAPE) { + for (String name : PARAMETERS_NEED_ESCAPE) { if (name.equals(paramName)) { return EscapeCharacter.unescape(paramValue); } diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignBin.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignBin.java index c861c4f6c324655c41ec319d900509cbbb1e149a..bc94668de46bccd15069f025448f3fe36159d1da 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignBin.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignBin.java @@ -37,22 +37,25 @@ import java.io.IOException; import java.util.Map; /** - * Lite OS bin file Signature signer. + * LiteOS bin file Signature signer. * * @since 2021/12/21 */ public class SignBin { + /** + * Constructor of Method + */ private SignBin() { } private static final Logger LOGGER = LogManager.getLogger(SignBin.class); /** - * The function of sign bin file. + * Sign the bin file. * - * @param signerConfig The config of sign bin file. - * @param signParams The input parameters of sign bin - * @return true, if sign successfully. + * @param signerConfig Config of the bin file to be signed. + * @param signParams The input parameters of sign bin. + * @return true if sign successfully; false otherwise. */ public static boolean sign(SignerConfig signerConfig, Map signParams) { boolean result = false; @@ -68,7 +71,7 @@ public class SignBin { } LOGGER.info("The block head data made success."); - /* 2. Make sign data, add write to output file */ + /* 2. Make sign data, and write to output file */ String signAlg = signParams.get(ParamConstants.PARAM_BASIC_SIGANTURE_ALG); if (!writeSignDataToOutputFile(signerConfig, outputFile, signAlg)) { LOGGER.error("The sign data made failed."); @@ -77,7 +80,7 @@ public class SignBin { } LOGGER.info("The data signed success."); - /* 3. Make sign data, add write to output file */ + /* 3. Make sign data, and write to output file */ if (!writeSignHeadDataToOutputFile(inputFile, outputFile)) { LOGGER.error("The sign head data made failed."); ParamProcessUtil.delDir(new File(outputFile)); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyAndParseProvision.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyAndParseProvision.java index 5279ba660aabd86eb483686b79ce205140733d97..0ffed2bf6192f4920c52a1b35523b22572ff8e2b 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyAndParseProvision.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyAndParseProvision.java @@ -35,18 +35,17 @@ public class VerifyAndParseProvision { private static final Logger LOGGER = LogManager.getLogger(VerifyAndParseProvision.class); /** - * this function verify signatures of provision and output unsigned provision + * verify signatures of provision and output unsigned provision * - * @param signedProvisionPath the path of the inputted signedProvision file - * @param unsignedProvisionPath the path which the caller wants to output unsignedProvision file - * @return true indicates verify and parse provision file successfully, - * false indicates something wrong is happened. + * @param signedProvisionPath the path of the input signedProvision file. + * @param unsignedProvisionPath the path to which the unsignedProvision file is output. + * @return true if the provision file is verified and parsed successfully, false otherwise. */ public boolean verifyAndParseProvision(String signedProvisionPath, String unsignedProvisionPath) { File signedProvisionFile = new File(signedProvisionPath); try { if (!checkProvisionFile(signedProvisionFile)) { - String errorMsg = "Check input provision file false!"; + String errorMsg = "Check input provision file failed!"; LOGGER.error(errorMsg); throw new IOException(); } diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyResult.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyResult.java index 1b5947bd3e520b2b7d18d8e3804b87d91b8ccb6b..8ba54b0ba1847c5abc271d6b174bca3af7a1ccab 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyResult.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyResult.java @@ -31,7 +31,7 @@ import java.util.List; */ public class VerifyResult { /** - * Return code of verify success. + * Return code of verification success. */ public static final int RET_SUCCESS = 10000; diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/keystore/KeyStoreHelper.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/keystore/KeyStoreHelper.java index ddaa5dc58d52bc4dbaaf2a6623bec9c8afd36f8d..65ce94357084dd2d947b5ce4f3614608fa3421c1 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/keystore/KeyStoreHelper.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/keystore/KeyStoreHelper.java @@ -238,7 +238,7 @@ public class KeyStoreHelper { * @return certificates of alias */ public List loadCertificates(String alias) { - ValidateUtils.throwIfNotMatches(this.hasAlias(alias), ERROR.NOT_SUPPORT_ERROR, + ValidateUtils.throwIfNotMatches(this.hasAlias(alias), ERROR.FILE_NOT_FOUND, String.format("Not found '%s' in %s", alias, this.keyStorePath)); List certificates = new ArrayList<>(); @@ -256,7 +256,7 @@ public class KeyStoreHelper { } } catch (KeyStoreException exception) { logger.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); + CustomException.throwException(ERROR.KEYSTORE_OPERATION_ERROR, exception.getMessage()); } ValidateUtils.throwIfNotMatches(certificates.size() > 0, ERROR.ACCESS_ERROR, @@ -317,7 +317,7 @@ public class KeyStoreHelper { .getCertificate(certificateBuilder.build(contentSigner)); } catch (CertificateException exception) { logger.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); + CustomException.throwException(ERROR.IO_CERT_ERROR, exception.getMessage()); return null; } } @@ -341,7 +341,7 @@ public class KeyStoreHelper { } } catch (KeyStoreException exception) { logger.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); + CustomException.throwException(ERROR.KEYSTORE_OPERATION_ERROR, exception.getMessage()); } return typeKeyStore; } diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/profile/model/BundleInfo.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/profile/model/BundleInfo.java index 11b1036d7f23aa10d1a1596d9230249e9f881f38..a274eff8530d66b149fbf872db48acdd4e690793 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/profile/model/BundleInfo.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/profile/model/BundleInfo.java @@ -122,8 +122,6 @@ public class BundleInfo { * @param buildType build type */ public void enforceValid(String buildType) { - ValidateUtils.throwIfMatches(this.developerId == null, ERROR.SIGN_ERROR, - "Require developerId in bundleInfo!"); if (Provision.isBuildTypeRelease(buildType)) { ValidateUtils.throwIfMatches(this.distributionCertificate == null, ERROR.SIGN_ERROR, "Require cert in bundleInfo!"); @@ -131,10 +129,5 @@ public class BundleInfo { ValidateUtils.throwIfMatches(this.developmentCertificate == null, ERROR.SIGN_ERROR, "Require cert in bundleInfo!"); } - ValidateUtils.throwIfMatches(this.bundleName == null, ERROR.SIGN_ERROR, - "Require bundleName in bundleInfo!"); - ValidateUtils.throwIfMatches(this.appFeature == null || Provision.isAppDistTypeValid(this.appFeature), - ERROR.SIGN_ERROR, "Require appFeature be hos_system_app or hos_normal_app,curr is :" - + this.appFeature + " in bundleInfo!"); } } diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/profile/model/Provision.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/profile/model/Provision.java index 0e2f3c29c40eeae7b662241029ffc6eacd61548c..6feda36b98f40a7b1eb6271020e2355862ab4d9b 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/profile/model/Provision.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/profile/model/Provision.java @@ -193,33 +193,12 @@ public class Provision { * @param provision provision */ public static void enforceValid(Provision provision) { - ValidateUtils.throwIfMatches(provision == null, ERROR.SIGN_ERROR, - "Require provision not empty!"); - ValidateUtils.throwIfMatches(provision.versionName == null, ERROR.SIGN_ERROR, - "Require provision version name!"); - ValidateUtils.throwIfMatches(provision.versionCode == 0, ERROR.SIGN_ERROR, - "Require provision version code!"); - ValidateUtils.throwIfMatches(provision.uuid == null, ERROR.SIGN_ERROR, - "Require provision uuid!"); ValidateUtils.throwIfMatches(provision.type == null || !isBuildTypeValid(provision.type), ERROR.SIGN_ERROR, "Require build type must be debug or release, current is :" + provision.type); - ValidateUtils.throwIfMatches(isBuildTypeRelease(provision.type) - && (provision.appDistributionType == null - || !isAppDistTypeValid(provision.appDistributionType)), ERROR.SIGN_ERROR, - "Require app distribution type must be one of app_gallery, " - + "enterprise or os_integration, current is " + provision.appDistributionType); ValidateUtils.throwIfMatches(provision.bundleInfo == null, ERROR.SIGN_ERROR, "Require bundleInfo in provision!"); provision.bundleInfo.enforceValid(provision.type); - ValidateUtils.throwIfMatches(provision.validity == null, ERROR.SIGN_ERROR, - "Require validity in provision!"); - provision.validity.enforceValid(); - if (provision.debuginfo != null) { - provision.debuginfo.enforceValid(); - } - ValidateUtils.throwIfMatches(provision.issuer == null, ERROR.SIGN_ERROR, - "Require issuer in provision!"); } public Integer getVersionCode() { diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertUtils.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertUtils.java index bfbd93287680cb37fcfb2c8d186196fb576b8056..58533882e05a37380caa9ac9b8479510bbc8c5b1 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertUtils.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertUtils.java @@ -179,23 +179,6 @@ public final class CertUtils { } } - /** - * Generate crl. - * - * @param crl crl - * @return X509CRL - */ - public static X509CRL generateCrl(byte[] crl) { - try { - CertificateFactory factory = CertificateFactory.getInstance("X.509"); - return (X509CRL) factory.generateCRL(new ByteArrayInputStream(crl)); - } catch (CertificateException | CRLException exception) { - LOGGER.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); - } - return null; - } - /** * Convert byte to CSR String. * @@ -233,27 +216,6 @@ public final class CertUtils { return new BigInteger(RANDOM_SERIAL_LENGTH, new SecureRandom()); } - /** - * save2Pem. - * - * @param certificates certificates to save - * @param filePath filePath to save - */ - public static void save2Pem(List certificates, String filePath) { - try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(new FileOutputStream(filePath)))) { - for (X509Certificate certificate : certificates) { - PemObject object = new PemObject("certificate", certificate.getEncoded()); - pemWriter.writeObject(object); - } - } catch (CertificateEncodingException exception) { - LOGGER.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.NOT_SUPPORT_ERROR, exception.getMessage()); - } catch (IOException exception) { - LOGGER.debug(exception.getMessage(), exception); - CustomException.throwException(ERROR.WRITE_FILE_ERROR, exception.getMessage()); - } - } - /** * Convert byte to cert. * diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/ParamProcessUtil.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/ParamProcessUtil.java index aa93c3cd893162e16009b036eb5c8926fc1c1f18..ebd1ad89d31a42264b05f4a791d176cf0ee09816 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/ParamProcessUtil.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/ParamProcessUtil.java @@ -27,7 +27,7 @@ import java.util.HashSet; import java.util.Set; /** - * Utils functions for process parameters. + * Utils functions for processing parameters. * * @since 2021/12/21 */ diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/StringUtils.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/StringUtils.java index bd0e3d1405fecec528158319cc2cad2b3e0745f6..c3823f6b5ebaa1878f64f7c9e7e751d3130be753 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/StringUtils.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/StringUtils.java @@ -25,7 +25,7 @@ public final class StringUtils { } /** - * Check string is empty. + * Check whether the input string is empty. * * @param cs input string * @return true, if cs is empty diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/zip/ZipDataInput.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/zip/ZipDataInput.java index f9ffe64715a18972a5302e4ea83b137ba8dd06d9..483aa56936697dad1a8dda97fa2f75ed371bcb9b 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/zip/ZipDataInput.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/zip/ZipDataInput.java @@ -25,7 +25,7 @@ import java.nio.ByteBuffer; */ public interface ZipDataInput { /** - * return how many bytes contained in this data input + * Get how many bytes are contained in this data input. * * @return this data input size */ diff --git a/tools/auto_test.py b/tools/auto_test.py index fbfa53759e5bc24805118f7bcb3292465dc1b577..f569d86445b0b17263089166527c6f76192dd1b3 100644 --- a/tools/auto_test.py +++ b/tools/auto_test.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python +# coding=utf-8 ############################################## # Copyright (c) 2021-2022 Huawei Device Co., Ltd. # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tools/commands.config b/tools/commands.config index ef6b2f6720418d2c0a3d7e74fc00fa6ce1864cad..4f5da296f12dfdae87aeda1682551c8333ff34a5 100644 --- a/tools/commands.config +++ b/tools/commands.config @@ -38,7 +38,6 @@ 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd 123456 -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "CN= Application Signature Service CA" -validity 365 -signAlg SHA256withECDSA -basicConstraintsPathLen 1 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd 123456 -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -signAlg SHA256withECDSA -basicConstraintsPathLen 1 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd 123456 -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity -signAlg SHA256withECDSA -basicConstraintsPathLen 1 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', - 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd 123456 -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity**() -signAlg SHA256withECDSA -basicConstraintsPathLen 1 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd 123456 -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity 365 -signAlg SHA256withECDSA -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd 123456 -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity 365 -signAlg SHA256withECDSA -basicConstraintsPathLen -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd 123456 -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity 365 -signAlg SHA256withECDSA -basicConstraintsPathLen OK0 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', @@ -182,6 +181,7 @@ 'generate-ca -keyAlias -keyPwd 123456 -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity 365 -signAlg SHA256withECDSA -basicConstraintsPathLen 1 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity 365 -signAlg SHA256withECDSA -basicConstraintsPathLen 1 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity 365 -signAlg SHA256withECDSA -basicConstraintsPathLen 1 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', + 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd 123456 -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity**() -signAlg SHA256withECDSA -basicConstraintsPathLen 1 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd "@#$%&" -keyAlg ECC -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity 365 -signAlg SHA256withECDSA -basicConstraintsPathLen 1 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd 123456 -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity 365 -signAlg SHA256withECDSA -basicConstraintsPathLen 1 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"', 'generate-ca -keyAlias "oh-profile-sign-srv-ca-key-v1" -keyPwd 123456 -keyAlg -keySize NIST-P-256 -issuer "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN=Root CA" -issuerKeyAlias "oh-root-ca-key-v1" -issuerKeyPwd 123456 -subject "C=CN,O=OpenHarmony,OU=OpenHarmony Community,CN= Application Signature Service CA" -validity 365 -signAlg SHA256withECDSA -basicConstraintsPathLen 1 -keystoreFile "ohtest.jks" -keystorePwd 123456 -extCfgFile "111.txt" -outFile "profile-sign-srv-ca.cer"',