From bd5b1b945cdea24917f7d19c750a5c0f0d6993a7 Mon Sep 17 00:00:00 2001 From: wangzeyu Date: Mon, 12 Aug 2024 09:49:40 +0800 Subject: [PATCH 1/3] clean code check ai Signed-off-by: wangzeyu --- .../ohos/hapsigntoolcmd/ConcurrencyTest.java | 13 +++++++-- .../ohos/hapsigntoolcmd/HapSignToolTest.java | 20 ++++++------- .../hapsigntool/error/CustomException.java | 1 + .../hapsigntool/hap/config/SignerConfig.java | 4 +-- .../{HwBlockHead.java => BlockHead.java} | 4 +-- .../hap/entity/SignContentInfo.java | 10 +++---- .../entity/{HwSignHead.java => SignHead.java} | 2 +- .../hap/entity/SignatureBlockTypes.java | 4 +-- .../hap/provider/LocalJKSSignProvider.java | 5 ++-- .../hap/provider/RemoteSignProvider.java | 2 +- .../hap/provider/SignProvider.java | 2 +- .../hap/sign/BcPkcs7Generator.java | 14 +++++----- .../ohos/hapsigntool/hap/sign/SignBin.java | 18 ++++++------ .../ohos/hapsigntool/hap/sign/SignElf.java | 12 ++++---- .../hapsigntool/hap/verify/HapVerify.java | 21 +++++++------- .../hapsigntool/hap/verify/VerifyElf.java | 28 +++++++++---------- .../hapsigntool/utils/ByteArrayUtils.java | 9 ++++++ .../hapsigntool/utils/CertChainUtils.java | 2 -- .../hapsigntool/utils/CertificateUtils.java | 4 +-- .../hapsigntool/utils/EscapeCharacter.java | 2 +- .../com/ohos/hapsigntool/utils/FileUtils.java | 6 ++++ .../com/ohos/hapsigntool/utils/HashUtils.java | 24 ++++++++-------- 22 files changed, 114 insertions(+), 93 deletions(-) rename hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/{HwBlockHead.java => BlockHead.java} (95%) rename hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/{HwSignHead.java => SignHead.java} (99%) diff --git a/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/ConcurrencyTest.java b/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/ConcurrencyTest.java index 58d5951e..5a5ce54f 100644 --- a/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/ConcurrencyTest.java +++ b/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/ConcurrencyTest.java @@ -27,6 +27,8 @@ import com.ohos.hapsigntool.HapSignTool; import com.ohos.hapsigntool.error.ERROR; import com.ohos.hapsigntool.utils.FileUtils; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; @@ -75,6 +77,7 @@ public class ConcurrencyTest { private static final File TMP_DIR = new File("concurrentTest"); private static final List tmpSource = new ArrayList<>(); + private static final Logger log = LogManager.getLogger(ConcurrencyTest.class); /** * before test @@ -140,13 +143,19 @@ public class ConcurrencyTest { CountDownLatch countDownLatch = new CountDownLatch(CONCURRENT_TASK_COUNT); ThreadPoolExecutor executor = new ThreadPoolExecutor(CONCURRENT_TASK_COUNT, CONCURRENT_TASK_COUNT, KEEP_ALIVE_TIMES, TimeUnit.SECONDS, new ArrayBlockingQueue<>(CONCURRENT_TASK_COUNT), - new ThreadPoolExecutor.AbortPolicy()); + new ThreadPoolExecutor.DiscardPolicy()); List> futures = new ArrayList<>(CONCURRENT_TASK_COUNT); for (int i = 0; i < CONCURRENT_TASK_COUNT; i++) { futures.add(executor.submit(generateSignHapTask(countDownLatch))); } executor.shutdown(); - boolean isFinished = countDownLatch.await(KEEP_ALIVE_TIMES, TimeUnit.SECONDS); + boolean isFinished; + try { + isFinished = countDownLatch.await(KEEP_ALIVE_TIMES, TimeUnit.SECONDS); + } catch (InterruptedException e) { + isFinished = false; + log.error("concurrency test interrupted"); + } if (!isFinished) { executor.shutdownNow(); } diff --git a/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/HapSignToolTest.java b/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/HapSignToolTest.java index 460efabb..057175a4 100644 --- a/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/HapSignToolTest.java +++ b/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/HapSignToolTest.java @@ -80,13 +80,13 @@ public class HapSignToolTest { signAppParameters.setKeyStoreFile("../../tools/ohtest_pass.jks"); signAppParameters.setKeystorePwd("123456".toCharArray()); signAppParameters.setOutFile(outputFile.getCanonicalPath()); - Assertions.assertSame(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); + Assertions.assertEquals(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); VerifyAppParameters verifyAppParameters = new VerifyAppParameters(); verifyAppParameters.setInFile(outputFile.getCanonicalPath()); verifyAppParameters.setOutCertChain("out.cer"); verifyAppParameters.setOutProfile("out.p7b"); - Assertions.assertSame(HapSignTool.verifyApp(verifyAppParameters).getErrCode(), ERROR.SUCCESS_CODE); + Assertions.assertEquals(HapSignTool.verifyApp(verifyAppParameters).getErrCode(), ERROR.SUCCESS_CODE); } /** @@ -111,14 +111,14 @@ public class HapSignToolTest { signAppParameters.setKeystorePwd("123456".toCharArray()); signAppParameters.setOutFile(outputFile.getCanonicalPath()); signAppParameters.setInForm(InForm.ELF); - Assertions.assertSame(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); + Assertions.assertEquals(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); VerifyAppParameters verifyAppParameters = new VerifyAppParameters(); verifyAppParameters.setInFile(outputFile.getCanonicalPath()); verifyAppParameters.setOutCertChain("out.cer"); verifyAppParameters.setOutProfile("out.p7b"); verifyAppParameters.setInForm(InForm.ELF); - Assertions.assertSame(HapSignTool.verifyApp(verifyAppParameters).getErrCode(), ERROR.SUCCESS_CODE); + Assertions.assertEquals(HapSignTool.verifyApp(verifyAppParameters).getErrCode(), ERROR.SUCCESS_CODE); } /** @@ -144,7 +144,7 @@ public class HapSignToolTest { signAppParameters.setOutFile(outputFile.getCanonicalPath()); signAppParameters.setProfileSigned(ProFileSigned.UNSIGNED); signAppParameters.setInForm(InForm.ELF); - Assertions.assertNotSame(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); + Assertions.assertNotEquals(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); } /** @@ -167,7 +167,7 @@ public class HapSignToolTest { signAppParameters.setKeyStoreFile("../../tools/ohtest_pass.jks"); signAppParameters.setKeystorePwd("123456".toCharArray()); signAppParameters.setOutFile(outputFile.getCanonicalPath()); - Assertions.assertNotSame(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); + Assertions.assertNotEquals(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); } /** @@ -190,7 +190,7 @@ public class HapSignToolTest { signAppParameters.setKeyStoreFile("../../tools/ohtest_pass.jks"); signAppParameters.setKeystorePwd("123456".toCharArray()); signAppParameters.setOutFile(outputFile.getCanonicalPath()); - Assertions.assertNotSame(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); + Assertions.assertNotEquals(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); } @@ -214,7 +214,7 @@ public class HapSignToolTest { signAppParameters.setKeyStoreFile("../../tools/ohtest_pass.jks"); signAppParameters.setKeystorePwd("123456".toCharArray()); signAppParameters.setOutFile(outputFile.getCanonicalPath()); - Assertions.assertNotSame(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); + Assertions.assertNotEquals(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); } /** @@ -237,7 +237,7 @@ public class HapSignToolTest { signAppParameters.setKeyStoreFile("../../tools/ohtest_pass.jks"); signAppParameters.setKeystorePwd("123456".toCharArray()); signAppParameters.setOutFile(outputFile.getCanonicalPath()); - Assertions.assertNotSame(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); + Assertions.assertNotEquals(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); } /** @@ -260,7 +260,7 @@ public class HapSignToolTest { signAppParameters.setAppCertFile("../../tools/app1.pem"); signAppParameters.setKeystorePwd("123456".toCharArray()); signAppParameters.setOutFile(outputFile.getCanonicalPath()); - Assertions.assertNotSame(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); + Assertions.assertNotEquals(HapSignTool.signApp(signAppParameters).getErrCode(), ERROR.SUCCESS_CODE); } private static class Cleanable { diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/error/CustomException.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/error/CustomException.java index 7b65d7d9..af3b09ec 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/error/CustomException.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/error/CustomException.java @@ -32,6 +32,7 @@ public class CustomException extends RuntimeException { * @param message Error msg to throw */ CustomException(ERROR error, String message) { + super(message); this.error = error; this.message = message; } diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/config/SignerConfig.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/config/SignerConfig.java index aab64f28..46a70491 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/config/SignerConfig.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/config/SignerConfig.java @@ -160,7 +160,7 @@ public class SignerConfig { * * @param params params map */ - public void fillParameters(Map params) { + public void setParameters(Map params) { this.signParamMap = params; } @@ -209,7 +209,7 @@ public class SignerConfig { */ public SignerConfig copy() { SignerConfig signerConfig = new SignerConfig(); - signerConfig.fillParameters(signParamMap); + signerConfig.setParameters(signParamMap); signerConfig.setCertificates(certificates); signerConfig.setOptions(options); signerConfig.setSignatureAlgorithms(signatureAlgorithms); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/HwBlockHead.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/BlockHead.java similarity index 95% rename from hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/HwBlockHead.java rename to hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/BlockHead.java index c790e885..63e1f5f0 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/HwBlockHead.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/BlockHead.java @@ -23,7 +23,7 @@ import java.nio.ByteOrder; * * @since 2023/11/07 */ -public class HwBlockHead { +public class BlockHead { /** * bin file sign block length is 8 byte */ @@ -90,7 +90,7 @@ public class HwBlockHead { * @return Byte array after serialization of HwBlockHead */ public static byte[] getBlockHeadLittleEndian(char type, char tag, int length, int offset) { - ByteBuffer bf = ByteBuffer.allocate(HwBlockHead.ELF_BLOCK_LEN).order(ByteOrder.LITTLE_ENDIAN); + ByteBuffer bf = ByteBuffer.allocate(BlockHead.ELF_BLOCK_LEN).order(ByteOrder.LITTLE_ENDIAN); bf.putChar(type); bf.putChar(tag); bf.putInt(length); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignContentInfo.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignContentInfo.java index 44f34b4a..1c379858 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignContentInfo.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignContentInfo.java @@ -59,7 +59,7 @@ class SignContentHash { /** * the length of content */ - protected int contentHashLen; + protected int contentHashLen; SignContentHash(char type, char tag, short algId, int length, byte[] hash) { this.type = type; @@ -98,11 +98,9 @@ public class SignContentInfo { } private void addHashData(SignContentHash signInfo) { - if (hashData != null) { - hashData.add(signInfo); - numOfBlocks++; - size += signInfo.contentHashLen; - } + hashData.add(signInfo); + numOfBlocks++; + size += signInfo.contentHashLen; } /** diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/HwSignHead.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignHead.java similarity index 99% rename from hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/HwSignHead.java rename to hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignHead.java index 97bd30a7..75b99f59 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/HwSignHead.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignHead.java @@ -26,7 +26,7 @@ import java.nio.ByteOrder; * * @since 2021-12-13 */ -public class HwSignHead { +public class SignHead { /** * length of sign head */ diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignatureBlockTypes.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignatureBlockTypes.java index a59e9c01..e553fb8a 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignatureBlockTypes.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignatureBlockTypes.java @@ -54,10 +54,10 @@ public class SignatureBlockTypes { * @return profile block type value */ public static char getProfileBlockTypes(String isSigned) { - if (isSigned != null && "0".equals(isSigned)) { + if ("0".equals(isSigned)) { return PROFILE_NOSIGNED_BLOCK; } - if (isSigned != null && "1".equals(isSigned)) { + if ("1".equals(isSigned)) { return PROFILE_SIGNED_BLOCK; } return PROFILE_NOSIGNED_BLOCK; 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 7bfd632a..b2a36d96 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 @@ -22,6 +22,7 @@ import com.ohos.hapsigntool.utils.FileUtils; import com.ohos.hapsigntool.entity.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; @@ -47,10 +48,10 @@ public class LocalJKSSignProvider extends SignProvider { public Optional getCrl() { X509CRL crl = null; String crlPath = signParams.get(ParamConstants.PARAM_BASIC_CRL); - if (crlPath == null || "".equals(crlPath)) { + if (StringUtils.isEmpty(crlPath)) { return Optional.ofNullable(crl); } - try (FileInputStream input = new FileInputStream(new File(crlPath));) { + try (FileInputStream input = new FileInputStream(crlPath)) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); CRL baseCrl = cf.generateCRL(input); if (!(baseCrl instanceof X509CRL)) { 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 10770de1..061d046b 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 @@ -35,6 +35,6 @@ public class RemoteSignProvider extends SignProvider { @Override protected boolean checkInputCertMatchWithProfile(X509Certificate inputCert, X509Certificate certInProfile) { - return inputCert == null ? false : inputCert.equals(certInProfile); + return inputCert != null && inputCert.equals(certInProfile); } } \ No newline at end of file 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 c493350a..8b00c53c 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 @@ -224,7 +224,7 @@ public abstract class SignProvider { public SignerConfig createSignerConfigs(List certificates, Optional crl, Options options) throws InvalidKeyException { SignerConfig signerConfig = new SignerConfig(); - signerConfig.fillParameters(this.signParams); + signerConfig.setParameters(this.signParams); signerConfig.setCertificates(certificates); signerConfig.setOptions(options); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/BcPkcs7Generator.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/BcPkcs7Generator.java index 1e92a855..ad4cda15 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/BcPkcs7Generator.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/BcPkcs7Generator.java @@ -115,10 +115,10 @@ public class BcPkcs7Generator implements Pkcs7Generator { ASN1Set crls = null; byte[] signBlock; try { - if (checkListNotNullOrEmty(signerConfig.getCertificates())) { + if (checkListNotNullOrEmpty(signerConfig.getCertificates())) { certs = createBerSetFromCerts(signerConfig.getCertificates()); } - if (checkListNotNullOrEmty(signerConfig.getX509CRLs())) { + if (checkListNotNullOrEmpty(signerConfig.getX509CRLs())) { crls = createBerSetFromCrls(signerConfig.getX509CRLs()); } SignedData signedData = new SignedData( @@ -157,7 +157,7 @@ public class BcPkcs7Generator implements Pkcs7Generator { if (signatureBytes == null) { throw new SignatureException("Generate signature bytes error"); } - if (!checkListNotNullOrEmty(signerConfig.getCertificates())) { + if (!checkListNotNullOrEmpty(signerConfig.getCertificates())) { throw new SignatureException("No certificates configured for signer"); } @@ -206,7 +206,7 @@ public class BcPkcs7Generator implements Pkcs7Generator { } private ASN1Set createBerSetFromCrls(List crls) throws CRLException { - if (crls == null || crls.size() == 0) { + if (crls == null || crls.isEmpty()) { return null; } ASN1EncodableVector vector = new ASN1EncodableVector(); @@ -217,7 +217,7 @@ public class BcPkcs7Generator implements Pkcs7Generator { } private ASN1Set createBerSetFromCerts(List certs) throws CertificateEncodingException { - if (certs == null || certs.size() == 0) { + if (certs == null || certs.isEmpty()) { return null; } ASN1EncodableVector vector = new ASN1EncodableVector(); @@ -228,8 +228,8 @@ public class BcPkcs7Generator implements Pkcs7Generator { return new BERSet(vector); } - private boolean checkListNotNullOrEmty(List lists) { - return (lists != null) && (lists.size() > 0); + private boolean checkListNotNullOrEmpty(List lists) { + return (lists != null) && (!lists.isEmpty()); } private boolean verifySignatureFromServer( 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 3d7c7a90..07256af2 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 @@ -16,8 +16,8 @@ package com.ohos.hapsigntool.hap.sign; import com.ohos.hapsigntool.hap.config.SignerConfig; -import com.ohos.hapsigntool.hap.entity.HwBlockHead; -import com.ohos.hapsigntool.hap.entity.HwSignHead; +import com.ohos.hapsigntool.hap.entity.BlockHead; +import com.ohos.hapsigntool.hap.entity.SignHead; import com.ohos.hapsigntool.hap.entity.SignContentInfo; import com.ohos.hapsigntool.hap.entity.SignatureBlockTags; import com.ohos.hapsigntool.hap.entity.SignatureBlockTypes; @@ -102,21 +102,21 @@ public class SignBin { throw new IOException(); } - long offset = binFileLen + HwBlockHead.getBlockLen() + HwBlockHead.getBlockLen(); + long offset = binFileLen + BlockHead.getBlockLen() + BlockHead.getBlockLen(); if (isLongOverflowInteger(offset)) { - LOGGER.error("The profile block head offset is overflow interger range, offset: " + offset); + LOGGER.error("The profile block head offset is overflow integer range, offset: " + offset); throw new IOException(); } char isSigned = SignatureBlockTypes.getProfileBlockTypes(profileSigned); byte[] proBlockByte = - HwBlockHead.getBlockHead(isSigned, SignatureBlockTags.DEFAULT, (short) profileDataLen, (int) offset); + BlockHead.getBlockHead(isSigned, SignatureBlockTags.DEFAULT, (short) profileDataLen, (int) offset); offset += profileDataLen; if (isLongOverflowInteger(offset)) { LOGGER.error("The sign block head offset is overflow integer range, offset: " + offset); throw new IOException(); } - byte[] signBlockByte = HwBlockHead.getBlockHead( + byte[] signBlockByte = BlockHead.getBlockHead( SignatureBlockTypes.SIGNATURE_BLOCK, SignatureBlockTags.DEFAULT, (short) 0, (int) offset); return writeSignedBin(inputFile, proBlockByte, signBlockByte, profileFile, outputFile); @@ -132,7 +132,7 @@ public class SignBin { DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);) { // 1. write the input file to the output file. if (!FileUtils.writeFileToDos(inputFile, dataOutputStream)) { - LOGGER.error("Failed to write infomation of input file: " + inputFile + + LOGGER.error("Failed to write information of input file: " + inputFile + " to outputFile: " + outputFile); throw new IOException(); } @@ -166,12 +166,12 @@ public class SignBin { } private static boolean writeSignHeadDataToOutputFile(String inputFile, String outputFile) { - long size = FileUtils.getFileLen(outputFile) - FileUtils.getFileLen(inputFile) + HwSignHead.SIGN_HEAD_LEN; + long size = FileUtils.getFileLen(outputFile) - FileUtils.getFileLen(inputFile) + SignHead.SIGN_HEAD_LEN; if (isLongOverflowInteger(size)) { LOGGER.error("File size is Overflow integer range."); return false; } - HwSignHead signHeadData = new HwSignHead(); + SignHead signHeadData = new SignHead(); byte[] signHeadByte = signHeadData.getSignHead((int) size); if (signHeadByte == null || signHeadByte.length == 0) { LOGGER.error("Failed to get sign head data."); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignElf.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignElf.java index 5a2180ad..576e0a42 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignElf.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignElf.java @@ -19,8 +19,8 @@ import com.ohos.hapsigntool.codesigning.exception.CodeSignException; import com.ohos.hapsigntool.codesigning.exception.FsVerityDigestException; import com.ohos.hapsigntool.codesigning.sign.CodeSigning; import com.ohos.hapsigntool.hap.config.SignerConfig; -import com.ohos.hapsigntool.hap.entity.HwBlockHead; -import com.ohos.hapsigntool.hap.entity.HwSignHead; +import com.ohos.hapsigntool.hap.entity.BlockHead; +import com.ohos.hapsigntool.hap.entity.SignHead; import com.ohos.hapsigntool.hap.entity.SignBlockData; import com.ohos.hapsigntool.hap.entity.SignatureBlockTags; import com.ohos.hapsigntool.hap.entity.SignatureBlockTypes; @@ -214,12 +214,12 @@ public class SignElf { private static void generateSignBlockHead(List signDataList) throws IOException { - long offset = (long) HwBlockHead.getElfBlockLen() * signDataList.size(); + long offset = (long) BlockHead.getElfBlockLen() * signDataList.size(); for (int i = 0; i < signDataList.size(); i++) { SignBlockData signBlockData = signDataList.get(i); - signBlockData.setBlockHead(HwBlockHead.getBlockHeadLittleEndian(signBlockData.getType(), + signBlockData.setBlockHead(BlockHead.getBlockHeadLittleEndian(signBlockData.getType(), SignatureBlockTags.DEFAULT, (int) signBlockData.getLen(), (int) offset)); offset += signBlockData.getLen(); if (isLongOverflowInteger(offset)) { @@ -248,7 +248,7 @@ public class SignElf { return null; } CodeSigning codeSigning = new CodeSigning(signerConfig); - long offset = binFileLen + (long) HwBlockHead.getElfBlockLen() * blockNum; + long offset = binFileLen + (long) BlockHead.getElfBlockLen() * blockNum; String profileContent = signParams.get(ParamConstants.PARAM_PROFILE_JSON_CONTENT); byte[] codesignData = codeSigning.getElfCodeSignBlock(new File(inputFile), offset, signParams.get(ParamConstants.PARAM_IN_FORM), profileContent); @@ -261,7 +261,7 @@ public class SignElf { LOGGER.error("File size is Overflow integer range."); return false; } - HwSignHead signHeadData = new HwSignHead(); + SignHead signHeadData = new SignHead(); byte[] signHeadByte = signHeadData.getSignHeadLittleEndian((int) size, blockNum); if (signHeadByte == null) { LOGGER.error("Failed to get sign head data."); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/HapVerify.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/HapVerify.java index 39a091e0..6707caa4 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/HapVerify.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/HapVerify.java @@ -75,6 +75,8 @@ import java.util.Set; public class HapVerify { private static final Logger LOGGER = LogManager.getLogger(HapVerify.class); + private static final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + private ZipDataInput beforeApkSigningBlock; private ByteBuffer signatureSchemeBlock; @@ -282,7 +284,7 @@ public class HapVerify { Store certificates = cmsSignedData.getCertificates(); try { List certificateList = certStoreToCertList(certificates); - if (certificateList == null || certificateList.size() == 0) { + if (certificateList.isEmpty()) { throw new VerifyHapException("Certificate chain is empty!"); } if (isPrintCert) { @@ -357,18 +359,18 @@ public class HapVerify { LOGGER.info("version is: {}, number of block is: {}", signBlockVersion, signBlockCount); int digestBlockLen = digestDatas.getInt(); int signatureAlgId = digestDatas.getInt(); - int digestDatalen = digestDatas.getInt(); - if (digestBlockLen != digestDatalen + 8) { - throw new SignatureException("digestBlockLen: " + digestBlockLen + ", digestDatalen: " + digestDatalen); + int digestDataLen = digestDatas.getInt(); + if (digestBlockLen != digestDataLen + 8) { + throw new SignatureException("digestBlockLen: " + digestBlockLen + ", digestDataLen: " + digestDataLen); } - ByteBuffer degestBuffer = HapUtils.sliceBuffer(digestDatas, digestDatalen); - byte[] degisetData = new byte[degestBuffer.remaining()]; - degestBuffer.get(degisetData); + ByteBuffer digestBuffer = HapUtils.sliceBuffer(digestDatas, digestDataLen); + byte[] digestData = new byte[digestBuffer.remaining()]; + digestBuffer.get(digestData); SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.findById(signatureAlgId); if (signatureAlgorithm == null) { throw new SignatureException("Unsupported SignatureAlgorithm ID : " + signatureAlgId); } - digestMap.put(signatureAlgorithm.getContentDigestAlgorithm(), degisetData); + digestMap.put(signatureAlgorithm.getContentDigestAlgorithm(), digestData); } Set keySet = digestMap.keySet(); @@ -382,7 +384,7 @@ public class HapVerify { if (!Arrays.equals(actualDigest, exceptDigest)) { isResult = false; LOGGER.error( - "degist data do not match! DigestAlgorithm: {}, actualDigest: <{}> VS exceptDigest : <{}>", + "digest data do not match! DigestAlgorithm: {}, actualDigest: <{}> VS exceptDigest : <{}>", digestAlg.getDigestAlgorithm(), HapUtils.toHex(actualDigest, ""), HapUtils.toHex(exceptDigest, "")); @@ -425,7 +427,6 @@ public class HapVerify { private String formatDateTime(Date date) { if (date != null) { - DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return format.format(date); } return ""; diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyElf.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyElf.java index 6157601a..9d8c6177 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyElf.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/verify/VerifyElf.java @@ -20,8 +20,8 @@ import com.ohos.hapsigntool.codesigning.exception.FsVerityDigestException; import com.ohos.hapsigntool.codesigning.exception.VerifyCodeSignException; import com.ohos.hapsigntool.codesigning.sign.VerifyCodeSignature; import com.ohos.hapsigntool.hap.entity.ElfBlockData; -import com.ohos.hapsigntool.hap.entity.HwBlockHead; -import com.ohos.hapsigntool.hap.entity.HwSignHead; +import com.ohos.hapsigntool.hap.entity.BlockHead; +import com.ohos.hapsigntool.hap.entity.SignHead; import com.ohos.hapsigntool.hap.entity.SignatureBlockTypes; import com.ohos.hapsigntool.hap.entity.SigningBlock; import com.ohos.hapsigntool.error.ProfileException; @@ -247,18 +247,18 @@ public class VerifyElf { } private ElfBlockData getElfSignBlockData(byte[] bytes) throws IOException { - int offset = bytes.length - HwSignHead.SIGN_HEAD_LEN; - byte[] magicByte = readByteArrayOffset(bytes, offset, HwSignHead.ELF_MAGIC.length); - offset += HwSignHead.ELF_MAGIC.length; - byte[] versionByte = readByteArrayOffset(bytes, offset, HwSignHead.VERSION.length); - offset += HwSignHead.VERSION.length; - for (int i = 0; i < HwSignHead.ELF_MAGIC.length; i++) { - if (HwSignHead.ELF_MAGIC[i] != magicByte[i]) { + int offset = bytes.length - SignHead.SIGN_HEAD_LEN; + byte[] magicByte = readByteArrayOffset(bytes, offset, SignHead.ELF_MAGIC.length); + offset += SignHead.ELF_MAGIC.length; + byte[] versionByte = readByteArrayOffset(bytes, offset, SignHead.VERSION.length); + offset += SignHead.VERSION.length; + for (int i = 0; i < SignHead.ELF_MAGIC.length; i++) { + if (SignHead.ELF_MAGIC[i] != magicByte[i]) { throw new IOException("elf magic verify failed"); } } - for (int i = 0; i < HwSignHead.VERSION.length; i++) { - if (HwSignHead.VERSION[i] != versionByte[i]) { + for (int i = 0; i < SignHead.VERSION.length; i++) { + if (SignHead.VERSION[i] != versionByte[i]) { throw new IOException("elf sign version verify failed"); } } @@ -272,7 +272,7 @@ public class VerifyElf { ByteBuffer blockSizeBf = ByteBuffer.wrap(blockSizeByte).order(ByteOrder.LITTLE_ENDIAN); int blockSize = blockSizeBf.getInt(); - int blockStart = bytes.length - HwSignHead.SIGN_HEAD_LEN - blockSize; + int blockStart = bytes.length - SignHead.SIGN_HEAD_LEN - blockSize; return new ElfBlockData(blockNum, blockStart); } @@ -281,7 +281,7 @@ public class VerifyElf { Map blockMap = new HashMap<>(); for (int i = 0; i < elfBlockData.getBlockNum(); i++) { - byte[] blockByte = readByteArrayOffset(bytes, offset, HwBlockHead.ELF_BLOCK_LEN); + byte[] blockByte = readByteArrayOffset(bytes, offset, BlockHead.ELF_BLOCK_LEN); ByteBuffer blockBuffer = ByteBuffer.wrap(blockByte).order(ByteOrder.LITTLE_ENDIAN); char type = blockBuffer.getChar(); char tag = blockBuffer.getChar(); @@ -289,7 +289,7 @@ public class VerifyElf { int blockOffset = blockBuffer.getInt(); byte[] value = readByteArrayOffset(bytes, elfBlockData.getBlockStart() + blockOffset, length); blockMap.put(type, new SigningBlock(type, value, elfBlockData.getBlockStart() + blockOffset)); - offset += HwBlockHead.ELF_BLOCK_LEN; + offset += BlockHead.ELF_BLOCK_LEN; } return blockMap; } diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/ByteArrayUtils.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/ByteArrayUtils.java index 214fcdb1..75c22e35 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/ByteArrayUtils.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/ByteArrayUtils.java @@ -41,6 +41,9 @@ public class ByteArrayUtils { * @return end of position of inserting, if successfully */ public static int insertIntToByteArray(byte[] desByte, int index, int num) { + if (desByte == null) { + return -1; + } if (index + Integer.BYTES > desByte.length) { return -1; } @@ -66,6 +69,9 @@ public class ByteArrayUtils { * @return end of position of inserting, if successfully */ public static int insertShortToByteArray(byte[] desByte, int desByteLen, int index, short num) { + if (desByte == null) { + return -1; + } if (index + HALF_INTEGER_BYTES > desByteLen) { return -1; } @@ -103,6 +109,9 @@ public class ByteArrayUtils { * @return end of position of inserting, if successfully */ public static int insertCharToByteArray(byte[] des, int start, char[] src) { + if (des == null) { + return -1; + } if (start > des.length - src.length) { return -1; } diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertChainUtils.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertChainUtils.java index 3ab6ca97..f6c658da 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertChainUtils.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertChainUtils.java @@ -50,8 +50,6 @@ import java.util.List; * @since 2021/12/28 */ public class CertChainUtils { - private static final Logger LOGGER = LogManager.getLogger(CertUtils.class); - private CertChainUtils() { } diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertificateUtils.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertificateUtils.java index c88fa73b..713e93f4 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertificateUtils.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertificateUtils.java @@ -54,7 +54,7 @@ public class CertificateUtils { */ public static void verifyCertChain(List certs) throws VerifyCertificateChainException { if (certs.size() <= 1) { - return; + throw new VerifyCertificateChainException("certificate chain is empty") ; } for (int i = 1; i < certs.size(); i++) { try { @@ -91,7 +91,7 @@ public class CertificateUtils { CertificateFactory cf = CertificateFactory.getInstance("X.509"); Collection certificates = (Collection) cf.generateCertificates(fileInputStream); - if (certificates != null && certificates.size() > 0) { + if (certificates != null && !certificates.isEmpty()) { List certs = new ArrayList(certificates); CertUtils.sortCertificateChain(certs); verifyCertChain(certs); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/EscapeCharacter.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/EscapeCharacter.java index a0b03bd7..b4c1c4aa 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/EscapeCharacter.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/EscapeCharacter.java @@ -59,7 +59,7 @@ public class EscapeCharacter { * @return string after unescape. */ public static String unescape(String src) { - StringBuffer tmp = new StringBuffer(); + StringBuilder tmp = new StringBuilder(); tmp.ensureCapacity(src.length()); int lastPos = 0; int pos = 0; diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java index fe65899a..95c4b787 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java @@ -17,6 +17,7 @@ package com.ohos.hapsigntool.utils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import com.ohos.hapsigntool.error.CustomException; import com.ohos.hapsigntool.error.ERROR; import org.apache.logging.log4j.LogManager; @@ -214,6 +215,11 @@ public final class FileUtils { * @throws IOException Write failed */ public static void write(byte[] content, File output) throws IOException { + boolean canWrite = output.canWrite(); + if (!canWrite) { + CustomException.throwException(ERROR.WRITE_FILE_ERROR, "no permission write file " + + output.getCanonicalPath()); + } try (FileOutputStream out = new FileOutputStream(output)) { for (byte con : content) { out.write(con); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/HashUtils.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/HashUtils.java index a23ac6d1..6b1837a2 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/HashUtils.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/HashUtils.java @@ -49,20 +49,18 @@ public class HashUtils { * @return algorithm ID */ public static int getHashAlgsId(String algMethod) { - int result = HashAlgs.USE_NONE; - if ("SHA-224".equals(algMethod)) { - result = HashAlgs.USE_SHA224; + switch (algMethod) { + case "SHA-224": + return HashAlgs.USE_SHA224; + case "SHA-256": + return HashAlgs.USE_SHA256; + case "SHA-384": + return HashAlgs.USE_SHA384; + case "SHA-512": + return HashAlgs.USE_SHA512; + default: + return HashAlgs.USE_NONE; } - if ("SHA-256".equals(algMethod)) { - result = HashAlgs.USE_SHA256; - } - if ("SHA-384".equals(algMethod)) { - result = HashAlgs.USE_SHA384; - } - if ("SHA-512".equals(algMethod)) { - result = HashAlgs.USE_SHA512; - } - return result; } private static MessageDigest getMessageDigest(String algMethod) { -- Gitee From 3cfd64290bfa10c6b81a6905c1bc5df045798f35 Mon Sep 17 00:00:00 2001 From: wangzeyu Date: Wed, 14 Aug 2024 16:07:23 +0800 Subject: [PATCH 2/3] clean code check ai Signed-off-by: wangzeyu --- .../src/test/java/com/ohos/hapsigntoolcmd/ConcurrencyTest.java | 2 +- .../java/com/ohos/hapsigntool/hap/entity/SignContentInfo.java | 2 +- .../main/java/com/ohos/hapsigntool/utils/CertificateUtils.java | 2 +- .../src/main/java/com/ohos/hapsigntool/utils/FileUtils.java | 3 +-- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/ConcurrencyTest.java b/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/ConcurrencyTest.java index 5a5ce54f..b991ebec 100644 --- a/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/ConcurrencyTest.java +++ b/hapsigntool/hap_sign_tool/src/test/java/com/ohos/hapsigntoolcmd/ConcurrencyTest.java @@ -154,7 +154,7 @@ public class ConcurrencyTest { isFinished = countDownLatch.await(KEEP_ALIVE_TIMES, TimeUnit.SECONDS); } catch (InterruptedException e) { isFinished = false; - log.error("concurrency test interrupted"); + log.error("concurrency test interrupted", e); } if (!isFinished) { executor.shutdownNow(); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignContentInfo.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignContentInfo.java index 1c379858..cac75a36 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignContentInfo.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/entity/SignContentInfo.java @@ -59,7 +59,7 @@ class SignContentHash { /** * the length of content */ - protected int contentHashLen; + protected int contentHashLen; SignContentHash(char type, char tag, short algId, int length, byte[] hash) { this.type = type; diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertificateUtils.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertificateUtils.java index 713e93f4..042e83d2 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertificateUtils.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/CertificateUtils.java @@ -54,7 +54,7 @@ public class CertificateUtils { */ public static void verifyCertChain(List certs) throws VerifyCertificateChainException { if (certs.size() <= 1) { - throw new VerifyCertificateChainException("certificate chain is empty") ; + return; } for (int i = 1; i < certs.size(); i++) { try { diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java index 95c4b787..15018beb 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java @@ -215,8 +215,7 @@ public final class FileUtils { * @throws IOException Write failed */ public static void write(byte[] content, File output) throws IOException { - boolean canWrite = output.canWrite(); - if (!canWrite) { + if (output.exists() && !output.canWrite()) { CustomException.throwException(ERROR.WRITE_FILE_ERROR, "no permission write file " + output.getCanonicalPath()); } -- Gitee From 418b9a968d66c050554880d9ff0690f72a61f2f3 Mon Sep 17 00:00:00 2001 From: wangzeyu Date: Sat, 31 Aug 2024 15:40:42 +0800 Subject: [PATCH 3/3] clean code check ai Signed-off-by: wangzeyu --- .../ohos/hapsigntool/hap/sign/SignBin.java | 2 +- .../ohos/hapsigntool/hap/sign/SignElf.java | 2 +- .../com/ohos/hapsigntool/utils/FileUtils.java | 2 +- .../com/ohos/hapsigntool/utils/HashUtils.java | 23 ++++++++++--------- 4 files changed, 15 insertions(+), 14 deletions(-) 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 07256af2..8c776060 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 @@ -168,7 +168,7 @@ public class SignBin { private static boolean writeSignHeadDataToOutputFile(String inputFile, String outputFile) { long size = FileUtils.getFileLen(outputFile) - FileUtils.getFileLen(inputFile) + SignHead.SIGN_HEAD_LEN; if (isLongOverflowInteger(size)) { - LOGGER.error("File size is Overflow integer range."); + LOGGER.error("File size is overflow integer range."); return false; } SignHead signHeadData = new SignHead(); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignElf.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignElf.java index 576e0a42..bc0b646c 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignElf.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/hap/sign/SignElf.java @@ -258,7 +258,7 @@ public class SignElf { private static boolean writeSignHeadDataToOutputFile(String inputFile, String outputFile, int blockNum) { long size = FileUtils.getFileLen(outputFile) - FileUtils.getFileLen(inputFile); if (isLongOverflowInteger(size)) { - LOGGER.error("File size is Overflow integer range."); + LOGGER.error("File size is overflow integer range."); return false; } SignHead signHeadData = new SignHead(); diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java index 15018beb..bb7d713a 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/FileUtils.java @@ -216,7 +216,7 @@ public final class FileUtils { */ public static void write(byte[] content, File output) throws IOException { if (output.exists() && !output.canWrite()) { - CustomException.throwException(ERROR.WRITE_FILE_ERROR, "no permission write file " + + CustomException.throwException(ERROR.WRITE_FILE_ERROR, "No permission to write file " + output.getCanonicalPath()); } try (FileOutputStream out = new FileOutputStream(output)) { diff --git a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/HashUtils.java b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/HashUtils.java index 6b1837a2..2874bf1b 100644 --- a/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/HashUtils.java +++ b/hapsigntool/hap_sign_tool_lib/src/main/java/com/ohos/hapsigntool/utils/HashUtils.java @@ -26,6 +26,7 @@ import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; +import java.util.Map; /** * The utils function used to get hash value. @@ -35,6 +36,14 @@ import java.util.HashMap; public class HashUtils { private static final Logger LOGGER = LogManager.getLogger(HashUtils.class); private static final int HASH_LEN = 4096; + private static final Map ALG_METHOD = new HashMap<>(); + + static { + ALG_METHOD.put("SHA-224", HashAlgs.USE_SHA224); + ALG_METHOD.put("SHA-256", HashAlgs.USE_SHA256); + ALG_METHOD.put("SHA-384", HashAlgs.USE_SHA384); + ALG_METHOD.put("SHA-512", HashAlgs.USE_SHA512); + } /** * Constructor of Method @@ -49,18 +58,10 @@ public class HashUtils { * @return algorithm ID */ public static int getHashAlgsId(String algMethod) { - switch (algMethod) { - case "SHA-224": - return HashAlgs.USE_SHA224; - case "SHA-256": - return HashAlgs.USE_SHA256; - case "SHA-384": - return HashAlgs.USE_SHA384; - case "SHA-512": - return HashAlgs.USE_SHA512; - default: - return HashAlgs.USE_NONE; + if (ALG_METHOD.containsKey(algMethod)) { + return ALG_METHOD.get(algMethod); } + return HashAlgs.USE_NONE; } private static MessageDigest getMessageDigest(String algMethod) { -- Gitee