Explorar o código

提交新网关

echo587 hai 4 días
pai
achega
5bc897309f

BIN=BIN
test-api/libs/java-sdk-core-3.2.7.jar


+ 59 - 0
test-api/pom.xml

@@ -100,6 +100,65 @@
         </dependency>
 
 
+        <!--  -->
+        <dependency>
+            <groupId>commons-codec</groupId>
+            <artifactId>commons-codec</artifactId>
+            <version>1.16.0</version>
+        </dependency>
+        <dependency>
+            <groupId>commons-logging</groupId>
+            <artifactId>commons-logging</artifactId>
+            <version>1.3.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+            <version>4.5.14</version>
+        </dependency>
+        <dependency>
+            <groupId>com.squareup.okhttp3</groupId>
+            <artifactId>okhttp</artifactId>
+            <version>4.11.0</version>
+        </dependency>
+        <dependency>
+            <groupId>com.squareup.okio</groupId>
+            <artifactId>okio</artifactId>
+            <version>3.5.0</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpcore</artifactId>
+            <version>4.4.16</version>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+            <version>2.0.16</version>
+            <scope>compile</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-simple</artifactId>
+            <version>2.0.16</version>
+        </dependency>
+        <dependency>
+            <systemPath>${project.basedir}/libs/java-sdk-core-3.2.7.jar</systemPath>
+            <groupId>com.huawei.apigateway</groupId>
+            <artifactId>java-sdk-core</artifactId>
+            <version>3.2.7</version>
+            <scope>system</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.openeuler</groupId>
+            <artifactId>bgmprovider</artifactId>
+            <version>1.1.3</version>
+        </dependency>
+        <dependency>
+            <groupId>org.bouncycastle</groupId>
+            <artifactId>bcprov-jdk18on</artifactId>
+            <version>1.78</version>
+        </dependency>
 
 
     </dependencies>

+ 23 - 0
test-api/src/main/java/com/sooka/utils/Constant.java

@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
+ */
+
+package com.sooka.utils;
+
+public final class Constant {
+    // verify ssl certificate (true) or do not verify (false)
+    public static final boolean DO_VERIFY = false;
+
+    public static final String HTTPS = "HTTPS";
+    public static final String TRUST_MANAGER_FACTORY = "SunX509";
+    public static final String GM_PROTOCOL = "GMTLS";
+    public static final String INTERNATIONAL_PROTOCOL = "TLSv1.2";
+    public static final String SIGNATURE_ALGORITHM_SDK_HMAC_SHA256 = "SDK-HMAC-SHA256";
+    public static final String[] SUPPORTED_CIPHER_SUITES = {"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
+            "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
+            "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"};
+    public static final String SECURE_RANDOM_ALGORITHM_NATIVE_PRNG_NON_BLOCKING = "NativePRNGNonBlocking";
+
+    private Constant() {
+    }
+}

+ 17 - 0
test-api/src/main/java/com/sooka/utils/HostName.java

@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) Huawei Technologies Co., Ltd. 2023-2025. All rights reserved.
+ */
+
+package com.sooka.utils;
+
+public class HostName {
+    private static String urlHostName;
+
+    public static void setUrlHostName(String hostName) {
+        urlHostName = hostName;
+    }
+
+    public static boolean checkHostName(String sslHostName) {
+        return urlHostName.equals(sslHostName);
+    }
+}

+ 110 - 0
test-api/src/main/java/com/sooka/utils/HttpUtil3.java

@@ -0,0 +1,110 @@
+package com.sooka.utils;
+
+import com.cloud.apigateway.sdk.utils.Client;
+import com.cloud.apigateway.sdk.utils.Request;
+import org.apache.http.Header;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import javax.net.ssl.*;
+import java.io.InputStreamReader;
+import java.io.OutputStreamWriter;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * 2025-12-08 共享新网关调用
+ */
+public class HttpUtil3 {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil3.class);
+
+
+    public static String doPost (String url, String param, Map headerparam) throws Exception {
+
+        Request httpClientRequest = new Request();
+        String result = null;
+        try {
+            if(headerparam != null){
+                Set<String> keys =headerparam.keySet();
+                Iterator<String> iterator = keys.iterator();
+                while(iterator.hasNext()){
+                    String key =iterator.next().toString();
+                    System.out.println("=======key======="+key);
+                    httpClientRequest.setKey(key);//HUAWEICLOUD_SDK_AK
+                    Object value = headerparam.get(key);
+                    System.out.println("=======value======="+value);
+                    String v = value.toString();
+                    httpClientRequest.setSecret(v);//HUAWEICLOUD_SDK_SK
+                }
+            }
+            httpClientRequest.setMethod("POST");
+            httpClientRequest.setUrl(url);
+            httpClientRequest.addHeader("Content-Type", "plain/text");
+            httpClientRequest.setBody(param);
+
+            // Sign the request.
+            // The default hashAlgorithm is SDK-HMAC-SHA256.
+            HttpRequestBase signedRequest = Client.sign(httpClientRequest);
+            HttpResponse response = executeRequest(signedRequest, httpClientRequest.getHost());
+            if (response != null) {
+                HttpEntity resEntity = response.getEntity();
+                if (resEntity != null) {
+                    result = EntityUtils.toString(resEntity);
+                }
+            }
+        } catch (Exception e) {
+            LOGGER.error(e.getMessage());
+        }
+        return result;
+    }
+
+    public static HttpResponse executeRequest(HttpRequestBase signedRequest, String host) throws Exception {
+        CloseableHttpClient client = null;
+        HttpResponse response = null;
+        try {
+            // Print request header parameters: Authorization
+            LOGGER.info("Print the authorization: {}", Arrays.toString(signedRequest.getHeaders("Authorization")));
+            if (Constant.DO_VERIFY) {
+                // creat httpClient and verify ssl certificate
+                HostName.setUrlHostName(host);
+                client = (CloseableHttpClient) SSLCipherSuiteUtil.createHttpClientWithVerify(
+                        Constant.INTERNATIONAL_PROTOCOL);
+            } else {
+                // creat httpClient and do not verify ssl certificate
+                client = (CloseableHttpClient) SSLCipherSuiteUtil.createHttpClient(Constant.INTERNATIONAL_PROTOCOL);
+            }
+            response = client.execute(signedRequest);
+            // Print the status line of the response.
+            LOGGER.info("Print the status line of the response: {}", response.getStatusLine().toString());
+            // Print the header fields of the response.
+            Header[] resHeaders = response.getAllHeaders();
+            for (Header h : resHeaders) {
+                LOGGER.info("Processing Header with name: {} and value: {}", h.getName(), h.getValue());
+            }
+            // Print the body of the response.
+            HttpEntity resEntity = response.getEntity();
+            if (resEntity != null) {
+                LOGGER.info("Processing Body with name: {} and value: {}", System.getProperty("line.separator"),
+                        EntityUtils.toString(resEntity, "UTF-8"));
+            }
+        } catch (Exception e) {
+            LOGGER.error(e.getMessage());
+        } finally {
+            if (client != null) {
+                client.close();
+            }
+        }
+        return response;
+    }
+
+
+}

+ 209 - 0
test-api/src/main/java/com/sooka/utils/SSLCipherSuiteUtil.java

@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) Huawei Technologies Co., Ltd. 2018-2025. All rights reserved.
+ */
+
+package com.sooka.utils;
+
+import okhttp3.OkHttpClient;
+import org.apache.http.client.HttpClient;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.bouncycastle.crypto.BlockCipher;
+import org.bouncycastle.crypto.engines.AESEngine;
+import org.bouncycastle.crypto.prng.SP800SecureRandomBuilder;
+import org.openeuler.BGMProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.*;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.security.*;
+import java.security.cert.X509Certificate;
+import java.util.Locale;
+import java.util.concurrent.TimeUnit;
+
+public class SSLCipherSuiteUtil {
+    private static final Logger LOGGER = LoggerFactory.getLogger(SSLCipherSuiteUtil.class);
+    private static CloseableHttpClient httpClient;
+    private static OkHttpClient okHttpClient;
+
+    private static final int CIPHER_LEN = 256;
+
+    private static final int ENTROPY_BITS_REQUIRED = 384;
+
+    public static HttpClient createHttpClient(String protocol) throws Exception {
+        SSLContext sslContext = getSslContext(protocol);
+        // create factory
+        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
+                new String[]{protocol}, Constant.SUPPORTED_CIPHER_SUITES, new TrustAllHostnameVerifier());
+
+        httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
+        return httpClient;
+    }
+
+    public static HttpClient createHttpClientWithVerify(String protocol) throws Exception {
+        SSLContext sslContext = getSslContextWithVerify(protocol);
+        // create factory
+        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
+                new String[]{protocol}, Constant.SUPPORTED_CIPHER_SUITES, new TheRealHostnameVerifier());
+
+        httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
+        return httpClient;
+    }
+
+    public static OkHttpClient createOkHttpClient(String protocol) throws Exception {
+        SSLContext sslContext = getSslContext(protocol);
+        // Create an ssl socket factory with our all-trusting manager
+        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
+        OkHttpClient.Builder builder = new OkHttpClient.Builder()
+                .sslSocketFactory(sslSocketFactory, new TrustAllManager())
+                .hostnameVerifier(new TrustAllHostnameVerifier());
+        okHttpClient = builder.connectTimeout(10, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).build();
+        return okHttpClient;
+    }
+
+    public static OkHttpClient createOkHttpClientWithVerify(String protocol) throws Exception {
+        SSLContext sslContext = getSslContextWithVerify(protocol);
+        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
+
+        TrustManagerFactory tmf = TrustManagerFactory.getInstance(Constant.TRUST_MANAGER_FACTORY);
+        tmf.init((KeyStore) null);
+        TrustManager[] verify = tmf.getTrustManagers();
+        OkHttpClient.Builder builder = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory,
+                (X509TrustManager) verify[0]).hostnameVerifier(new TheRealHostnameVerifier());
+
+        okHttpClient = builder.connectTimeout(10, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).build();
+        return okHttpClient;
+    }
+
+    public static HttpURLConnection createHttpsOrHttpURLConnection(URL uUrl, String protocol) throws Exception {
+        // initial connection
+        if (uUrl.getProtocol().toUpperCase(Locale.getDefault()).equals(Constant.HTTPS)) {
+            SSLContext sslContext = getSslContext(protocol);
+            HttpsURLConnection.setDefaultHostnameVerifier(new TrustAllHostnameVerifier());
+            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
+            return (HttpsURLConnection) uUrl.openConnection();
+        }
+        return (HttpURLConnection) uUrl.openConnection();
+    }
+
+    public static HttpURLConnection createHttpsOrHttpURLConnectionWithVerify(URL uUrl, String protocol) throws Exception {
+        // initial connection
+        if (uUrl.getProtocol().toUpperCase(Locale.getDefault()).equals(Constant.HTTPS)) {
+            SSLContext sslContext = getSslContextWithVerify(protocol);
+            HttpsURLConnection.setDefaultHostnameVerifier(new TheRealHostnameVerifier());
+            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
+            return (HttpsURLConnection) uUrl.openConnection();
+        }
+        return (HttpURLConnection) uUrl.openConnection();
+    }
+
+    private static SSLContext getSslContext(String protocol) throws UnsupportProtocolException,
+            NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
+        if (!Constant.GM_PROTOCOL.equals(protocol) && !Constant.INTERNATIONAL_PROTOCOL.equals(protocol)) {
+            LOGGER.info("Unsupport protocol: {}, Only support GMTLS TLSv1.2", protocol);
+            throw new UnsupportProtocolException("Unsupport protocol, Only support GMTLS TLSv1.2");
+        }
+        // Create a trust manager that does not validate certificate chains
+        TrustAllManager[] trust = {new TrustAllManager()};
+        KeyManager[] kms = null;
+        SSLContext sslContext;
+
+        sslContext = SSLContext.getInstance(Constant.INTERNATIONAL_PROTOCOL, "SunJSSE");
+
+        if (Constant.GM_PROTOCOL.equals(protocol)) {
+            Security.insertProviderAt(new BGMProvider(), 1);
+            sslContext = SSLContext.getInstance(Constant.GM_PROTOCOL, "BGMProvider");
+        }
+        SecureRandom secureRandom = getSecureRandom();
+        sslContext.init(kms, trust, secureRandom);
+        sslContext.getServerSessionContext().setSessionCacheSize(8192);
+        sslContext.getServerSessionContext().setSessionTimeout(3600);
+        return sslContext;
+    }
+
+    private static SSLContext getSslContextWithVerify(String protocol)
+            throws UnsupportProtocolException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException,
+            KeyStoreException {
+        if (!Constant.GM_PROTOCOL.equals(protocol) && !Constant.INTERNATIONAL_PROTOCOL.equals(protocol)) {
+            LOGGER.info("Unsupport protocol: {}, Only support GMTLS TLSv1.2", protocol);
+            throw new UnsupportProtocolException("Unsupport protocol, Only support GMTLS TLSv1.2");
+        }
+        KeyManager[] kms = null;
+        SSLContext sslContext = SSLContext.getInstance(Constant.INTERNATIONAL_PROTOCOL, "SunJSSE");
+        SecureRandom secureRandom = getSecureRandom();
+
+        if (Constant.GM_PROTOCOL.equals(protocol)) {
+            Security.insertProviderAt(new BGMProvider(), 1);
+            sslContext = SSLContext.getInstance(Constant.GM_PROTOCOL, "BGMProvider");
+        }
+
+        TrustManagerFactory tmf = TrustManagerFactory.getInstance(Constant.TRUST_MANAGER_FACTORY);
+        tmf.init((KeyStore) null);
+        TrustManager[] verify = tmf.getTrustManagers();
+        sslContext.init(kms, verify, secureRandom);
+
+        sslContext.getServerSessionContext().setSessionCacheSize(8192);
+        sslContext.getServerSessionContext().setSessionTimeout(3600);
+        return sslContext;
+    }
+
+    // 不校验域名
+    private static class TrustAllHostnameVerifier implements HostnameVerifier {
+        public boolean verify(String hostname, SSLSession session) {
+            return true;
+        }
+    }
+
+    // 校验域名
+    private static class TheRealHostnameVerifier implements HostnameVerifier {
+        public boolean verify(String hostname, SSLSession session) {
+            if (HostName.checkHostName(hostname)) {
+                return true;
+            } else {
+                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
+                return hv.verify(hostname, session);
+            }
+        }
+    }
+
+    // 不校验服务端证书
+    private static class TrustAllManager implements X509TrustManager {
+        private X509Certificate[] issuers;
+
+        public TrustAllManager() {
+            this.issuers = new X509Certificate[0];
+        }
+
+        public X509Certificate[] getAcceptedIssuers() {
+            return issuers;
+        }
+
+        public void checkClientTrusted(X509Certificate[] chain, String authType) {
+        }
+
+        public void checkServerTrusted(X509Certificate[] chain, String authType) {
+        }
+    }
+
+    private static SecureRandom getSecureRandom() {
+        SecureRandom source;
+        try {
+            source = SecureRandom.getInstance(Constant.SECURE_RANDOM_ALGORITHM_NATIVE_PRNG_NON_BLOCKING);
+        } catch (NoSuchAlgorithmException e) {
+            try {
+                source = SecureRandom.getInstanceStrong();
+            } catch (NoSuchAlgorithmException ex) {
+                LOGGER.error("get SecureRandom failed", e);
+                throw new RuntimeException("get SecureRandom failed");
+            }
+        }
+        boolean predictionResistant = true;
+        BlockCipher cipher = new AESEngine();
+        boolean reSeed = false;
+        return new SP800SecureRandomBuilder(source, predictionResistant).setEntropyBitsRequired(
+                ENTROPY_BITS_REQUIRED).buildCTR(cipher, CIPHER_LEN, null, reSeed);
+    }
+}

+ 15 - 0
test-api/src/main/java/com/sooka/utils/UnsupportProtocolException.java

@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
+ */
+
+package com.sooka.utils;
+
+public class UnsupportProtocolException extends Exception {
+    private static final long serialVersionUID = 4312820110480855928L;
+    private String msgDes; // 异常对应的描述信息
+
+    public UnsupportProtocolException(String message) {
+        super(message);
+        msgDes = message;
+    }
+}