From 06d2b32c7777df22caca661bf83ae6e8f7b3fa55 Mon Sep 17 00:00:00 2001 From: fuqingji <51312040@qq.com> Date: Mon, 21 Mar 2022 16:15:51 +0800 Subject: [PATCH] 20220315-bugs --- .../service/impl/BizSmsEmailServiceImpl.java | 34 ++-- .../crypconfigure/crypto/helper/Config.java | 26 +-- .../crypto/helper/DiagnosticFileDumper.java | 4 +- .../crypconfigure/crypto/helper/Utils.java | 7 +- .../crypto/security/CryptoPrimitives.java | 68 +++---- .../security/HLSDKJCryptoSuiteFactory.java | 15 +- .../crypto/service/CrypServiceImpl.java | 7 +- .../impl/CrypConfigureServiceImpl.java | 191 +++++++++--------- .../feign/config/FeignConfiguration.java | 9 +- .../ebtp/extend/feign/utils/UrlConstants.java | 20 +- .../timeService/TimeServiceConstant.java | 116 ++++++----- .../controller/TimeServiceController.java | 7 +- 12 files changed, 262 insertions(+), 242 deletions(-) diff --git a/src/main/java/com/chinaunicom/mall/ebtp/extend/bizshortmessageemail/service/impl/BizSmsEmailServiceImpl.java b/src/main/java/com/chinaunicom/mall/ebtp/extend/bizshortmessageemail/service/impl/BizSmsEmailServiceImpl.java index dfde45a..d254640 100644 --- a/src/main/java/com/chinaunicom/mall/ebtp/extend/bizshortmessageemail/service/impl/BizSmsEmailServiceImpl.java +++ b/src/main/java/com/chinaunicom/mall/ebtp/extend/bizshortmessageemail/service/impl/BizSmsEmailServiceImpl.java @@ -1,12 +1,6 @@ package com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.service.impl; -import java.io.*; -import java.nio.file.Files; -import java.time.LocalDateTime; - -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.disk.DiskFileItem; -import org.springframework.web.multipart.MultipartFile; +import cn.hutool.core.exceptions.ExceptionUtil; import com.chinaunicom.mall.ebtp.common.base.entity.BaseResponse; import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.client.NotificationFeignClient; import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.entity.BizSendEmailVO; @@ -15,18 +9,25 @@ import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.entity.EshopMailPen import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.entity.EshopSmsPendingPO; import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.enums.ExceptionEnum; import com.chinaunicom.mall.ebtp.extend.bizshortmessageemail.service.BizSmsEmailService; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItem; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.annotation.Resource; +import java.io.*; +import java.nio.file.Files; /** * @author Neo */ @Service +@Slf4j public class BizSmsEmailServiceImpl implements BizSmsEmailService { private static final Logger logger = LoggerFactory.getLogger(BizSmsEmailServiceImpl.class); @@ -42,7 +43,7 @@ public class BizSmsEmailServiceImpl implements BizSmsEmailService { po.setSendUid(msgVO.getSendUid()); po.setSendUName(msgVO.getSendUName()); if (msgVO.getMutiMobileNumber() != null && !msgVO.getMutiMobileNumber().isEmpty()) { - po.setStrMobileNumber(StringUtils.join(msgVO.getMutiMobileNumber().toArray(),",")); + po.setStrMobileNumber(StringUtils.join(msgVO.getMutiMobileNumber().toArray(), ",")); } else { po.setStrMobileNumber(msgVO.getStrMobileNumberr()); } @@ -75,7 +76,7 @@ public class BizSmsEmailServiceImpl implements BizSmsEmailService { po.setFileType(emailVO.getFileType()); if ("1".equals(emailVO.getFileType())) { po.setFileUrl(emailVO.getFileUrl()); - } else if ("2".equals(emailVO.getFileType())){ + } else if ("2".equals(emailVO.getFileType())) { po.setFile(this.getFile()); } @@ -88,28 +89,27 @@ public class BizSmsEmailServiceImpl implements BizSmsEmailService { } /** - * - * @Description 返回MultipartFile文件 * @return org.springframework.web.multipart.MultipartFile + * @Description 返回MultipartFile文件 * @date 2019/1/5 11:08 * @auther dell */ private MultipartFile getFile() throws IOException { String filePath = "D:\\文档\\3.0能力间调用接口-通知中心.docx"; File file = new File(filePath); - FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()),false,file.getName(),(int)file.length(),file.getParentFile()); + FileItem fileItem = new DiskFileItem("copyfile.txt", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile()); byte[] buffer = new byte[4096]; int n; - try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){ - while ( (n = inputStream.read(buffer,0,4096)) != -1){ - os.write(buffer,0,n); + try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) { + while ((n = inputStream.read(buffer, 0, 4096)) != -1) { + os.write(buffer, 0, n); } //也可以用IOUtils.copy(inputStream,os); MultipartFile multipartFile = new CommonsMultipartFile(fileItem); System.out.println(multipartFile.getName()); return multipartFile; - }catch (IOException e){ - e.printStackTrace(); + } catch (IOException e) { + log.info(ExceptionUtil.stacktraceToString(e)); } return null; } diff --git a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/Config.java b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/Config.java index 35833f9..f91d633 100644 --- a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/Config.java +++ b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/Config.java @@ -108,12 +108,12 @@ public class Config { public static final String LIFECYCLE_INITREQUIREDDEFAULT = "org.hyperledger.fabric.com.chinaunicom.ebtp.mall.cloud.attachment.sdk.lifecycle.initRequiredDefault"; //ORG_HYPERLEDGER_FABRIC_SDK_LIFECYCLE_INITREQUIREDDEFAULT private static Config config; - private static final Properties sdkProperties = new Properties(); - private static final AtomicLong count = new AtomicLong(0); + private static final Properties SDK_PROPERTIES = new Properties(); + private static final AtomicLong COUNT = new AtomicLong(0); //Provides a unique id for logging to identify a specific instance. public String getNextID() { - return "" + count.incrementAndGet(); + return "" + COUNT.incrementAndGet(); } private Config() { @@ -126,7 +126,7 @@ public class Config { logger.debug(format("Loading configuration from %s and it is present: %b", loadFile.toString(), loadFile.exists())); configProps = new FileInputStream(loadFile); - sdkProperties.load(configProps); + SDK_PROPERTIES.load(configProps); } catch (IOException e) { logger.warn(format("Failed to load any configuration from: %s. Using toolkit defaults", @@ -200,7 +200,7 @@ public class Config { defaultProperty(LIFECYCLE_CHAINCODE_VALIDATION_PLUGIN, DEFAULT_NULL); defaultProperty(LIFECYCLE_INITREQUIREDDEFAULT, DEFAULT_NULL); - final String inLogLevel = sdkProperties.getProperty(LOGGERLEVEL); + final String inLogLevel = SDK_PROPERTIES.getProperty(LOGGERLEVEL); if (null != inLogLevel) { @@ -232,10 +232,10 @@ public class Config { */ private String getProperty(String property) { - if (!sdkProperties.containsKey(property)) { + if (!SDK_PROPERTIES.containsKey(property)) { logger.warn(format("No configuration value found for '%s'", property)); } - String ret = sdkProperties.getProperty(property); + String ret = SDK_PROPERTIES.getProperty(property); if (DEFAULT_NULL.equals(ret)) { ret = null; } @@ -246,15 +246,15 @@ public class Config { String ret = System.getProperty(key); if (ret != null) { - sdkProperties.put(key, ret); + SDK_PROPERTIES.put(key, ret); } else { String envKey = key.toUpperCase().replaceAll("\\.", "_"); ret = System.getenv(envKey); if (null != ret) { - sdkProperties.put(key, ret); + SDK_PROPERTIES.put(key, ret); } else { - if (null == sdkProperties.getProperty(key) && value != null) { - sdkProperties.put(key, value); + if (null == SDK_PROPERTIES.getProperty(key) && value != null) { + SDK_PROPERTIES.put(key, value); } } @@ -500,7 +500,7 @@ public class Config { return diagnosticFileDumper; } - String dd = sdkProperties.getProperty(DIAGNOTISTIC_FILE_DIRECTORY); + String dd = SDK_PROPERTIES.getProperty(DIAGNOTISTIC_FILE_DIRECTORY); if (dd != null) { @@ -601,6 +601,6 @@ public class Config { } - return null; + return false; } } \ No newline at end of file diff --git a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/DiagnosticFileDumper.java b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/DiagnosticFileDumper.java index a5b64ba..c9e5481 100644 --- a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/DiagnosticFileDumper.java +++ b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/DiagnosticFileDumper.java @@ -46,7 +46,7 @@ public class DiagnosticFileDumper implements Runnable { private final BlockingQueue queEntries = new LinkedBlockingQueue<>(); private static DiagnosticFileDumper singleInstance = null; - private static final AtomicInteger counter = new AtomicInteger(0); + private static final AtomicInteger COUNTER = new AtomicInteger(0); private DiagnosticFileDumper(File directory) { @@ -115,7 +115,7 @@ public class DiagnosticFileDumper implements Runnable { SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss_SSS"); dateFormatGmt.setTimeZone(TimeZone.getTimeZone("UTC")); fileName = prefix + dateFormatGmt.format(new Date()) + "P" + pid + "_" + Thread.currentThread().getId() - + "_" + counter.addAndGet(1) + "." + ext; + + "_" + COUNTER.addAndGet(1) + "." + ext; fileName = fileName.replaceAll("\\:", "-"); // colon is bad for windows. new QueEntry(fileName, bytes); //Add to Que let process by async thread. diff --git a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/Utils.java b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/Utils.java index f4ac2e1..3db4dd4 100644 --- a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/Utils.java +++ b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/helper/Utils.java @@ -50,8 +50,8 @@ public final class Utils { private static final Log logger = LogFactory.getLog(Utils.class); private static final boolean TRACE_ENABED = logger.isTraceEnabled(); - private static final Config config = Config.getConfig(); - private static final int MAX_LOG_STRING_LENGTH = config.maxLogStringLength(); + private static final Config CONFIG = Config.getConfig(); + private static final int MAX_LOG_STRING_LENGTH = CONFIG.maxLogStringLength(); /** * Generate parameter hash for the given chaincode path,func and args @@ -300,7 +300,8 @@ public final class Utils { } Properties props = new Properties(); - final Pattern p = Pattern.compile("([^:]+)[:]//([^:]+)[:]([0-9]+)", Pattern.CASE_INSENSITIVE); + final String regex = "([^:]+)[:]//([^:]+)[:]([0-9]+)"; + final Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(url); if (m.matches()) { props.setProperty("protocol", m.group(1)); diff --git a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/security/CryptoPrimitives.java b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/security/CryptoPrimitives.java index 445d150..a47b88a 100644 --- a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/security/CryptoPrimitives.java +++ b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/security/CryptoPrimitives.java @@ -59,22 +59,22 @@ import static com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.helper.Utils import static java.lang.String.format; public class CryptoPrimitives implements CryptoSuite { - private static final Log logger = LogFactory.getLog(CryptoPrimitives.class); - private static final Config config = Config.getConfig(); - private static final boolean IS_TRACE_LEVEL = logger.isTraceEnabled(); + private static final Log LOGGER = LogFactory.getLog(CryptoPrimitives.class); + private static final Config CONFIG = Config.getConfig(); + private static final boolean IS_TRACE_LEVEL = LOGGER.isTraceEnabled(); - private static final DiagnosticFileDumper diagnosticFileDumper = IS_TRACE_LEVEL - ? config.getDiagnosticFileDumper() : null; + private static final DiagnosticFileDumper DIAGNOSTIC_FILE_DUMPER = IS_TRACE_LEVEL + ? CONFIG.getDiagnosticFileDumper() : null; private String curveName; private CertificateFactory cf; private Provider SECURITY_PROVIDER; - private String hashAlgorithm = config.getHashAlgorithm(); - private int securityLevel = config.getSecurityLevel(); - private String CERTIFICATE_FORMAT = config.getCertificateFormat(); - private String DEFAULT_SIGNATURE_ALGORITHM = config.getSignatureAlgorithm(); + private String hashAlgorithm = CONFIG.getHashAlgorithm(); + private int securityLevel = CONFIG.getSecurityLevel(); + private String CERTIFICATE_FORMAT = CONFIG.getCertificateFormat(); + private String DEFAULT_SIGNATURE_ALGORITHM = CONFIG.getSignatureAlgorithm(); - private Map securityCurveMapping = config.getSecurityCurveMapping(); + private Map securityCurveMapping = CONFIG.getSecurityCurveMapping(); // Following configuration settings are hardcoded as they don't deal with any interactions with Fabric MSP and BCCSP components // If you wish to make these customizable, follow the logic from setProperties(); @@ -87,7 +87,7 @@ public class CryptoPrimitives implements CryptoSuite { // private int MAC_KEY_BYTE_COUNT = 32; public CryptoPrimitives() throws ClassNotFoundException, IllegalAccessException, InstantiationException { - String securityProviderClassName = config.getSecurityProviderClassName(); + String securityProviderClassName = CONFIG.getSecurityProviderClassName(); SECURITY_PROVIDER = setUpExplicitProvider(securityProviderClassName); @@ -183,7 +183,7 @@ public class CryptoPrimitives implements CryptoSuite { try { providerList.add(BouncyCastleProvider.class.newInstance()); // bouncy castle is there always. } catch (Exception e) { - logger.warn(e); + LOGGER.warn(e); } for (Provider provider : providerList) { @@ -220,7 +220,7 @@ public class CryptoPrimitives implements CryptoSuite { if (ret == null) { - logger.error("Could not convert pem bytes"); + LOGGER.error("Could not convert pem bytes"); } @@ -242,10 +242,10 @@ public class CryptoPrimitives implements CryptoSuite { PemObject po = pr.readPemObject(); PEMParser pem = new PEMParser(new StringReader(new String(pemKey))); - if (po.getType().equals("PRIVATE KEY")) { + if ("PRIVATE KEY".equals(po.getType())) { pk = new JcaPEMKeyConverter().getPrivateKey((PrivateKeyInfo) pem.readObject()); } else { - logger.trace("Found private key with type " + po.getType()); + LOGGER.trace("Found private key with type " + po.getType()); PEMKeyPair kp = (PEMKeyPair) pem.readObject(); pk = new JcaPEMKeyConverter().getPrivateKey(kp.getPrivateKeyInfo()); } @@ -263,13 +263,13 @@ public class CryptoPrimitives implements CryptoSuite { return false; } - if (config.extraLogLevel(10)) { - if (null != diagnosticFileDumper) { + if (CONFIG.extraLogLevel(10)) { + if (null != DIAGNOSTIC_FILE_DUMPER) { String message = "plaintext in hex: " + DatatypeConverter.printHexBinary(plainText) + '\n' + "signature in hex: " + DatatypeConverter.printHexBinary(signature) + '\n' + "PEM cert in hex: " + DatatypeConverter.printHexBinary(pemCertificate); - logger.trace("verify : " + - diagnosticFileDumper.createDiagnosticFile(message)); + LOGGER.trace("verify : " + + DIAGNOSTIC_FILE_DUMPER.createDiagnosticFile(message)); } } @@ -293,11 +293,11 @@ public class CryptoPrimitives implements CryptoSuite { CryptoException ex = new CryptoException("Cannot verify signature. Error is: " + e.getMessage() + "\r\nCertificate: " + DatatypeConverter.printHexBinary(pemCertificate), e); - logger.error(ex.getMessage(), ex); + LOGGER.error(ex.getMessage(), ex); throw ex; } catch (NoSuchAlgorithmException | SignatureException e) { CryptoException ex = new CryptoException("Cannot verify. Signature algorithm is invalid. Error is: " + e.getMessage(), e); - logger.error(ex.getMessage(), ex); + LOGGER.error(ex.getMessage(), ex); throw ex; } @@ -433,9 +433,9 @@ public class CryptoPrimitives implements CryptoSuite { } try { - if (config.extraLogLevel(10)) { - if (null != diagnosticFileDumper) { - logger.trace(format("Adding cert to trust store. alias: %s. certificate:", alias) + diagnosticFileDumper.createDiagnosticFile(alias + "cert: " + caCert.toString())); + if (CONFIG.extraLogLevel(10)) { + if (null != DIAGNOSTIC_FILE_DUMPER) { + LOGGER.trace(format("Adding cert to trust store. alias: %s. certificate:", alias) + DIAGNOSTIC_FILE_DUMPER.createDiagnosticFile(alias + "cert: " + caCert.toString())); } } synchronized (certificateSet) { @@ -449,7 +449,7 @@ public class CryptoPrimitives implements CryptoSuite { } } catch (KeyStoreException e) { String emsg = "Unable to add CA certificate to trust store. Error: " + e.getMessage(); - logger.error(emsg, e); + LOGGER.error(emsg, e); throw new CryptoException(emsg, e); } } @@ -543,7 +543,7 @@ public class CryptoPrimitives implements CryptoSuite { return validateCertificate(certificate); } catch (Exception e) { - logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate (PEM, hex): " + LOGGER.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate (PEM, hex): " + DatatypeConverter.printHexBinary(certPEM)); return false; } @@ -573,7 +573,7 @@ public class CryptoPrimitives implements CryptoSuite { isValidated = true; } catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | CertificateException | CertPathValidatorException | CryptoException e) { - logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate" + LOGGER.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate" + cert.toString()); isValidated = false; } @@ -588,7 +588,7 @@ public class CryptoPrimitives implements CryptoSuite { * @throws InvalidArgumentException */ void setSecurityLevel(final int securityLevel) throws InvalidArgumentException { - logger.trace(format("setSecurityLevel to %d", securityLevel)); + LOGGER.trace(format("setSecurityLevel to %d", securityLevel)); if (securityCurveMapping.isEmpty()) { throw new InvalidArgumentException("Security curve mapping has no entries."); @@ -608,7 +608,7 @@ public class CryptoPrimitives implements CryptoSuite { String lcurveName = securityCurveMapping.get(securityLevel); - logger.debug(format("Mapped curve strength %d to %s", securityLevel, lcurveName)); + LOGGER.debug(format("Mapped curve strength %d to %s", securityLevel, lcurveName)); X9ECParameters params = ECNamedCurveTable.getByName(lcurveName); //Check if can match curve name to requested strength. @@ -617,7 +617,7 @@ public class CryptoPrimitives implements CryptoSuite { InvalidArgumentException invalidArgumentException = new InvalidArgumentException( format("Curve %s defined for security strength %d was not found.", curveName, securityLevel)); - logger.error(invalidArgumentException); + LOGGER.error(invalidArgumentException); throw invalidArgumentException; } @@ -787,7 +787,7 @@ public class CryptoPrimitives implements CryptoSuite { return certificationRequestToPEM(p10Builder.build(signer)); } catch (Exception e) { - logger.error(e); + LOGGER.error(e); throw new InvalidArgumentException(e); } @@ -905,7 +905,7 @@ public class CryptoPrimitives implements CryptoSuite { cf = CertificateFactory.getInstance(CERTIFICATE_FORMAT); } catch (CertificateException e) { CryptoException ex = new CryptoException("Cannot initialize " + CERTIFICATE_FORMAT + " certificate factory. Error = " + e.getMessage(), e); - logger.error(ex.getMessage(), ex); + LOGGER.error(ex.getMessage(), ex); throw ex; } } @@ -925,12 +925,12 @@ public class CryptoPrimitives implements CryptoSuite { if (properties.containsKey(Config.SECURITY_CURVE_MAPPING)) { securityCurveMapping = Config.parseSecurityCurveMappings(properties.getProperty(Config.SECURITY_CURVE_MAPPING)); } else { - securityCurveMapping = config.getSecurityCurveMapping(); + securityCurveMapping = CONFIG.getSecurityCurveMapping(); } final String providerName = properties.containsKey(Config.SECURITY_PROVIDER_CLASS_NAME) ? properties.getProperty(Config.SECURITY_PROVIDER_CLASS_NAME) : - config.getSecurityProviderClassName(); + CONFIG.getSecurityProviderClassName(); try { SECURITY_PROVIDER = setUpExplicitProvider(providerName); diff --git a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/security/HLSDKJCryptoSuiteFactory.java b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/security/HLSDKJCryptoSuiteFactory.java index b006c8f..f6f192c 100644 --- a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/security/HLSDKJCryptoSuiteFactory.java +++ b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/security/HLSDKJCryptoSuiteFactory.java @@ -15,7 +15,6 @@ package com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.security; - import com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.exception.CryptoException; import com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.exception.InvalidArgumentException; import com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.helper.Config; @@ -30,20 +29,20 @@ import java.util.concurrent.ConcurrentHashMap; * SDK's Default implementation of CryptoSuiteFactory. */ public class HLSDKJCryptoSuiteFactory implements CryptoSuiteFactory { - private static final Config config = Config.getConfig(); - private static final int SECURITY_LEVEL = config.getSecurityLevel(); - private static final String HASH_ALGORITHM = config.getHashAlgorithm(); + private static final Config CONFIG = Config.getConfig(); + private static final int SECURITY_LEVEL = CONFIG.getSecurityLevel(); + private static final String HASH_ALGORITHM = CONFIG.getHashAlgorithm(); private HLSDKJCryptoSuiteFactory() { } - private static final Map cache = new ConcurrentHashMap<>(); + private static final Map CACHE = new ConcurrentHashMap<>(); @Override public CryptoSuite getCryptoSuite(Properties properties) throws CryptoException, InvalidArgumentException { - CryptoSuite ret = cache.get(properties); + CryptoSuite ret = CACHE.get(properties); if (ret == null) { try { CryptoPrimitives cp = new CryptoPrimitives(); @@ -54,7 +53,7 @@ public class HLSDKJCryptoSuiteFactory implements CryptoSuiteFactory { throw new CryptoException(e.getMessage(), e); } - cache.put(properties, ret); + CACHE.put(properties, ret); } @@ -85,7 +84,7 @@ public class HLSDKJCryptoSuiteFactory implements CryptoSuiteFactory { if (null == theFACTORY) { - String cf = config.getDefaultCryptoSuiteFactory(); + String cf = CONFIG.getDefaultCryptoSuiteFactory(); if (null == cf || cf.isEmpty() || cf.equals(HLSDKJCryptoSuiteFactory.class.getName())) { // Use this class as the factory. theFACTORY = HLSDKJCryptoSuiteFactory.instance(); diff --git a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/service/CrypServiceImpl.java b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/service/CrypServiceImpl.java index e4f6181..3eeade9 100644 --- a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/service/CrypServiceImpl.java +++ b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/crypto/service/CrypServiceImpl.java @@ -1,5 +1,6 @@ package com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.service; +import cn.hutool.core.exceptions.ExceptionUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.SerializerFeature; import com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.exception.InvalidArgumentException; @@ -121,11 +122,11 @@ public class CrypServiceImpl { byte[] crtBytes = crtKey.getBytes(); result = cp.verify(crtBytes, SIGNING_ALGORITHM, signature, plainData); } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) { - e.printStackTrace(); + log.info(ExceptionUtil.stacktraceToString(e)); } catch (InvalidArgumentException e) { - e.printStackTrace(); + log.info(ExceptionUtil.stacktraceToString(e)); } catch (com.chinaunicom.mall.ebtp.extend.crypconfigure.crypto.exception.CryptoException e) { - e.printStackTrace(); + log.info(ExceptionUtil.stacktraceToString(e)); } return result; } diff --git a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/service/impl/CrypConfigureServiceImpl.java b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/service/impl/CrypConfigureServiceImpl.java index 99ce30b..560e490 100644 --- a/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/service/impl/CrypConfigureServiceImpl.java +++ b/src/main/java/com/chinaunicom/mall/ebtp/extend/crypconfigure/service/impl/CrypConfigureServiceImpl.java @@ -40,12 +40,12 @@ import java.util.*; /** * 对数据表 biz_bid_cryp_configure 操作的 serviceImpl - * @author yss * + * @author yss */ @Slf4j @Service -public class CrypConfigureServiceImpl extends BaseServiceImpl implements ICrypConfigureService { +public class CrypConfigureServiceImpl extends BaseServiceImpl implements ICrypConfigureService { @Autowired private IBlockChainLogService iBlockChainLogService; @@ -56,9 +56,9 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl=0){ + if (str != null && !"".equals(str) && str.indexOf("_RSP\":{\"Code\":200,") >= 0) { blockChainLog.setStatus(0);//成功 this.iBlockChainLogService.save(blockChainLog); return true; - }else{ + } else { blockChainLog.setStatus(1);//失败 } } else { @@ -128,7 +129,7 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl query = Wrappers.lambdaQuery(blog); //状态 - if(vo.getStatus()!=null&&!"".equals(vo.getStatus())){ - query.eq(BlockChainLog::getStatus,vo.getStatus()); + if (vo.getStatus() != null && !"".equals(vo.getStatus())) { + query.eq(BlockChainLog::getStatus, vo.getStatus()); } //时间 - if(vo.getStartTime()!=null&&!"".equals(vo.getStartTime())){ - query.ge(BlockChainLog::getCreateDate,vo.getStartTime()); + if (vo.getStartTime() != null && !"".equals(vo.getStartTime())) { + query.ge(BlockChainLog::getCreateDate, vo.getStartTime()); } - if(vo.getEndTime()!=null&&!"".equals(vo.getEndTime())){ - query.le(BlockChainLog::getCreateDate,vo.getEndTime()); + if (vo.getEndTime() != null && !"".equals(vo.getEndTime())) { + query.le(BlockChainLog::getCreateDate, vo.getEndTime()); } List logList = this.iBlockChainLogService.list(query); - logList.forEach(blockChainLog->{ - log.info("请求路径:"+blockChainLog.getInterfaceUrl()); + logList.forEach(blockChainLog -> { + log.info("请求路径:" + blockChainLog.getInterfaceUrl()); try { - String json = blockChainLog.getParam(); + String json = blockChainLog.getParam(); //blockChainLog.setParam(json);//请求参数 String str = UniBssServiceImpl.uniBssHttpPost(blockChainLog.getInterfaceUrl(), json); blockChainLog.setResult(str);//返回参数 UniBss uniBssRsp = JSONArray.parseObject(str, UniBss.class); if (uniBssRsp != null && UniBssConstant.RESP_CODE_00000.equals(uniBssRsp.getUniBssHead().getRespCode())) { - System.out.println("返回接口:"+uniBssRsp); + System.out.println("返回接口:" + uniBssRsp); - if(str!=null&&!"".equals(str)&&str.indexOf("_RSP\":{\"Code\":200,")>=0){ + if (str != null && !"".equals(str) && str.indexOf("_RSP\":{\"Code\":200,") >= 0) { blockChainLog.setStatus(0);//成功 this.iBlockChainLogService.saveOrUpdate(blockChainLog); - }else{ + } else { blockChainLog.setStatus(1);//失败 } } else { @@ -203,7 +205,7 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl jsonMap = JSONArray.parseObject(json); + Map jsonMap = JSONArray.parseObject(json); Object signObject = new Object(); - if(jsonMap.get("BODY_LIST")!=null){ - List jsonList = (List)jsonMap.get("BODY_LIST"); - log.info("加密参数2:"+jsonList); + if (jsonMap.get("BODY_LIST") != null) { + List jsonList = (List) jsonMap.get("BODY_LIST"); + log.info("加密参数2:" + jsonList); InputStream is = CrypConfigureServiceImpl.class.getClassLoader().getResourceAsStream(PEM_PATH); - signValue = CrypServiceImpl.signObject2(jsonList,IOUtils.toString(is)); - }else{ - log.info("加密参数2:"+jsonMap); + signValue = CrypServiceImpl.signObject2(jsonList, IOUtils.toString(is)); + } else { + log.info("加密参数2:" + jsonMap); InputStream is = CrypConfigureServiceImpl.class.getClassLoader().getResourceAsStream(PEM_PATH); - signValue = CrypServiceImpl.signObject2(jsonMap,IOUtils.toString(is)); + signValue = CrypServiceImpl.signObject2(jsonMap, IOUtils.toString(is)); } - log.info("加密结果:"+signValue); - }catch (Exception e){ - log.info("---------加密异常-"+e.getMessage()); + log.info("加密结果:" + signValue); + } catch (Exception e) { + log.info("---------加密异常-" + e.getMessage()); } return signValue; } /** * 获取加密签名 + * * @param map * @return */ - private String getUniBss(String reqName, Map map){ + private String getUniBss(String reqName, Map map) { UniBss uniBss = new UniBss(); uniBss.setUniBssAttached(new UniBssAttached().setMediaInf("")); //天擎部分head - UniBssUtil util = new UniBssUtil(app_id,app_secret); + UniBssUtil util = new UniBssUtil(app_id, app_secret); uniBss.setUniBssHead(util.getUniBssHead()); UniReqHead reqhead = new UniReqHead(); //测试写死 String accessToken = "MQjkzVoYoSHe6r/3uZm0MV/TLx+n8PS9ivfPhgY4bWmh+8DVxj7vTC15xbBkuV8oujD3XBZPP7PhcWag9UU5IzsUBT7PSwPhqi/fUqa+iAWhCWpvyihG/23BAY3rJyaoa3OdMNSnIh8woPDCJQTzCTpNtg0toKwdWnuc2mig7vI0Lm9lePvrx3XxFLSaFr+jB5C3qnAX4uUBioZzithSjtra1QUK6S1cb9DCmpj6NRI="; //SystemId测试环境 990001 生产环境 74 - if(app_secret.equals("1mb6n6635cJkDb3pEQPUFXc2nRJ8RPaS")){ + if ("1mb6n6635cJkDb3pEQPUFXc2nRJ8RPaS".equals(app_secret)) { //测试环境 reqhead.setSystemId("990001"); - }else{ + } else { //生产环境 reqhead.setSystemId("74"); accessToken = AccessToken.tokenCreate("bidding"); - accessToken = accessToken.replaceAll("\n",""); - log.info("获取token:"+accessToken); + accessToken = accessToken.replaceAll("\n", ""); + log.info("获取token:" + accessToken); } reqhead.setSystemName("bidding"); - reqhead.setUserId(service.getCacheUser().getUserId()!=null?service.getCacheUser().getUserId():"dzztb"); - reqhead.setUserName(service.getCacheUser().getUserId()!=null?service.getCacheUser().getUserId():"dzztb"); + reqhead.setUserId(service.getCacheUser().getUserId() != null ? service.getCacheUser().getUserId() : "dzztb"); + reqhead.setUserName(service.getCacheUser().getUserId() != null ? service.getCacheUser().getUserId() : "dzztb"); reqhead.setAccessToken(accessToken); - log.info("业务参数封装前:"+map); + log.info("业务参数封装前:" + map); UniCrpyReq req = new UniCrpyReq(); req.setBody(map); req.setHead(reqhead); - log.info("业务参数封装中:"+req);; + log.info("业务参数封装中:" + req); + ; Map reqMap = new HashMap(); - reqMap.put(reqName,req); + reqMap.put(reqName, req); uniBss.setUniBssBodyMap(reqMap); - log.info("业务参数封装后:"+reqMap); - log.info("业务参数封装后uniBss:"+uniBss); + log.info("业务参数封装后:" + reqMap); + log.info("业务参数封装后uniBss:" + uniBss); return JSON.toJSONString(uniBss); } + /** * 解密 + * * @param bean * @return */ @Override - public Boolean verifyObject(CrypBean bean){ + public Boolean verifyObject(CrypBean bean) { - try{ + try { log.info("解密参数1:" + bean); String json = JSONArray.toJSONString(bean.getObject()); Map jsonMap = JSONArray.parseObject(json, Map.class); - if(jsonMap.get("BODY_LIST")!=null){ - List jsonList = (List)jsonMap.get("BODY_LIST"); - log.info("解密参数2:"+jsonList); + if (jsonMap.get("BODY_LIST") != null) { + List jsonList = (List) jsonMap.get("BODY_LIST"); + log.info("解密参数2:" + jsonList); InputStream is = CrypConfigureServiceImpl.class.getClassLoader().getResourceAsStream(CRT_PATH); Boolean b = CrypServiceImpl.verifyValue(bean.getSign(), jsonList, IOUtils.toString(is)); return b; - }else { + } else { log.info("解密参数2:" + bean); InputStream is = CrypConfigureServiceImpl.class.getClassLoader().getResourceAsStream(CRT_PATH); Boolean b = CrypServiceImpl.verifyValue(bean.getSign(), jsonMap, IOUtils.toString(is)); return b; } - }catch (Exception e){ - log.info("-----------解密失败"+e.getMessage()); + } catch (Exception e) { + log.info("-----------解密失败" + e.getMessage()); } return false; } - public static Map parseJSON2Map(String jsonStr){ - Map map = new HashMap(); - Map strmap = JSONArray.parseObject(jsonStr,Map.class); - for(Object k : strmap.keySet()){ + public static Map parseJSON2Map(String jsonStr) { + Map map = new HashMap(); + Map strmap = JSONArray.parseObject(jsonStr, Map.class); + for (Object k : strmap.keySet()) { Object v = strmap.get(k); - if(v instanceof JSONArray){ - List> list = new ArrayList>(); - Iterator it = ((JSONArray)v).iterator(); - while (it.hasNext()){ + if (v instanceof JSONArray) { + List> list = new ArrayList>(); + Iterator it = ((JSONArray) v).iterator(); + while (it.hasNext()) { Object json2 = it.next(); list.add(parseJSON2Map(json2.toString())); } - map.put(k.toString(),list); - }else{ - map.put(k.toString(),v); + map.put(k.toString(), list); + } else { + map.put(k.toString(), v); } } return map; @@ -413,6 +421,5 @@ public class CrypConfigureServiceImpl extends BaseServiceImpl"+tsaData); + log.info("tsaData -->" + tsaData); String timestamp = Base64.encodeBase64String(tsaData); - log.info("timestamp -->"+timestamp); + log.info("timestamp -->" + timestamp); return timestamp; - }catch (Exception e){ + } catch (Exception e) { log.error("申请时间戳异常", e); } return ""; } + /** * 解析时间戳 + * * @param timestamp 时间戳加密原文 * @return 时间戳对象 */ - public TtsAgent.TtsParseResult verifyTimeStamp2(String timestamp){ + public TtsAgent.TtsParseResult verifyTimeStamp2(String timestamp) { String systemtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); - TtsAgent.TtsParseResult ttsParseResult = new TtsAgent.TtsParseResult(systemtime,"",""); - if(redis.equals("eshop-redis-sim")){ + TtsAgent.TtsParseResult ttsParseResult = new TtsAgent.TtsParseResult(systemtime, "", ""); + if ("eshop-redis-sim".equals(redis)) { return ttsParseResult; } - try{ + try { - log.info("timestamp -->"+timestamp); + log.info("timestamp -->" + timestamp); TSAVerifyResult verifyResult = this.verifyTimeStamp(timestamp); String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(verifyResult.getSignedTime()); ttsParseResult = new TtsAgent.TtsParseResult(time, HelperUtil.bytesToHexString(verifyResult.getData()), verifyResult.getSignerSubject()); - }catch (Exception e){ + } catch (Exception e) { log.error("解析时间戳", e); } return ttsParseResult; } - private TSAVerifyResult verifyTimeStamp(String timestamp){ + private TSAVerifyResult verifyTimeStamp(String timestamp) { - try{ + try { - log.info("timestamp -->"+timestamp); + log.info("timestamp -->" + timestamp); TSAVerifyResult verifyResult = client.verifyTimeStamp(Base64.decodeBase64(timestamp)); return verifyResult; - }catch (Exception e){ + } catch (Exception e) { log.error("解析时间戳", e); } return null; @@ -107,20 +112,21 @@ public class TimeServiceConstant { /** * 获取时间戳 + * * @param data 待申请时间戳的原文 * @return 时间戳对象 */ - public TtsAgent.TtsParseResult getServiceTimeObj(String data){ + public TtsAgent.TtsParseResult getServiceTimeObj(String data) { String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); - TtsAgent.TtsParseResult ttsParseResult = new TtsAgent.TtsParseResult(time,"",""); - if(redis.equals("eshop-redis-sim")){ + TtsAgent.TtsParseResult ttsParseResult = new TtsAgent.TtsParseResult(time, "", ""); + if ("eshop-redis-sim".equals(redis)) { return ttsParseResult; } - try{ + try { String timestamp = this.signTimeStamp(data); ttsParseResult = this.verifyTimeStamp2(timestamp); - }catch (Exception e){ + } catch (Exception e) { log.error("获取时间戳异常", e); } return ttsParseResult; @@ -128,21 +134,22 @@ public class TimeServiceConstant { /** * 直接获取获取时间戳 时间1 + * * @param data 待申请时间戳的原文 * @return 时间 */ - public String getServiceTime(String data){ - log.info("------------------redis-"+redis); + public String getServiceTime(String data) { + log.info("------------------redis-" + redis); String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); - if(redis.equals("eshop-redis-sim")){ + if ("eshop-redis-sim".equals(redis)) { return time; } - try{ + try { String timestamp = this.signTimeStamp(data); TSAVerifyResult verifyResult = this.verifyTimeStamp(timestamp); time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(verifyResult.getSignedTime()); - }catch (Exception e){ + } catch (Exception e) { log.error("获取时间戳异常", e); } return time; @@ -151,53 +158,56 @@ public class TimeServiceConstant { /** * 直接获取获取时间戳 时间1 + * * @param data 待申请时间戳的原文 * @return date时间 */ - public Date getServiceDate(String data){ - if(redis.equals("eshop-redis-sim")){ + public Date getServiceDate(String data) { + if ("eshop-redis-sim".equals(redis)) { return new Date(); } - try{ + try { String timestamp = this.signTimeStamp(data); TSAVerifyResult verifyResult = this.verifyTimeStamp(timestamp); Date date = verifyResult.getSignedTime(); return date; - }catch (Exception e){ + } catch (Exception e) { log.error("获取时间戳异常", e); } return new Date(); } + /** * 获取年月日时分秒分割存储对象 + * * @param data 待申请时间戳的原文 * @return SystemTime */ - public SystemTime getServiceSystemTime(String data){ + public SystemTime getServiceSystemTime(String data) { Date date = new Date(); - if(redis.equals("eshop-redis-sim")){ + if ("eshop-redis-sim".equals(redis)) { return new SystemTime() - .setYear(date.getYear()+1900) - .setMonth(date.getMonth()+1) + .setYear(date.getYear() + 1900) + .setMonth(date.getMonth() + 1) .setDate(date.getDate()) .setHour(date.getHours()) .setMinute(date.getMinutes()) .setSecond(date.getSeconds()) .setTimestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date)); } - try{ + try { String timestamp = this.signTimeStamp(data); TSAVerifyResult verifyResult = this.verifyTimeStamp(timestamp); date = verifyResult.getSignedTime(); - }catch (Exception e){ + } catch (Exception e) { log.error("获取时间戳异常", e); } SystemTime systemTime = new SystemTime() - .setYear(date.getYear()+1900) - .setMonth(date.getMonth()+1) + .setYear(date.getYear() + 1900) + .setMonth(date.getMonth() + 1) .setDate(date.getDate()) .setHour(date.getHours()) .setMinute(date.getMinutes()) @@ -206,19 +216,19 @@ public class TimeServiceConstant { return systemTime; } - public static void main(String arge[]){ - try{ + public static void main(String arge[]) { + try { Date date = new Date(); - System.out.println("-----------"+(date.getYear()+1900)); - System.out.println("-----------"+(date.getMonth()+1)); - System.out.println("-----------"+date.getDate()); - System.out.println("-----------"+date.getHours()); - System.out.println("-----------"+date.getMinutes()); - System.out.println("-----------"+date.getSeconds()); + System.out.println("-----------" + (date.getYear() + 1900)); + System.out.println("-----------" + (date.getMonth() + 1)); + System.out.println("-----------" + date.getDate()); + System.out.println("-----------" + date.getHours()); + System.out.println("-----------" + date.getMinutes()); + System.out.println("-----------" + date.getSeconds()); - }catch (Exception e){ - e.printStackTrace(); + } catch (Exception e) { + log.info(ExceptionUtil.stacktraceToString(e)); } } } diff --git a/src/main/java/com/chinaunicom/mall/ebtp/extend/timeService/controller/TimeServiceController.java b/src/main/java/com/chinaunicom/mall/ebtp/extend/timeService/controller/TimeServiceController.java index 22ce64e..1265a45 100644 --- a/src/main/java/com/chinaunicom/mall/ebtp/extend/timeService/controller/TimeServiceController.java +++ b/src/main/java/com/chinaunicom/mall/ebtp/extend/timeService/controller/TimeServiceController.java @@ -1,13 +1,14 @@ package com.chinaunicom.mall.ebtp.extend.timeService.controller; +import cn.hutool.core.exceptions.ExceptionUtil; import com.chinaunicom.mall.ebtp.common.base.entity.BaseResponse; -import com.chinaunicom.mall.ebtp.extend.export.service.ExportServiceFactory; import com.chinaunicom.mall.ebtp.extend.timeService.TimeServiceConstant; import com.chinaunicom.mall.ebtp.extend.timeService.tsa.SystemTime; import com.chinaunicom.mall.ebtp.extend.timeService.tsa.TtsAgent; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; @@ -20,10 +21,12 @@ import java.util.Date; @RestController @Api(tags = "") @RequestMapping("/v1/timeService") +@Slf4j public class TimeServiceController { @Autowired private TimeServiceConstant timeServiceConstant; + /** * 申请时间戳 * @@ -118,7 +121,7 @@ public class TimeServiceController { .setSecond((int) s); return BaseResponse.success(systemTime); } catch (ParseException e) { - e.printStackTrace(); + log.info(ExceptionUtil.stacktraceToString(e)); } return BaseResponse.success(new SystemTime()); }