Browse Source

处理安全性问题

ouyang 1 year ago
parent
commit
b3b70f012d

+ 4 - 4
soc-common/soc-common-security/src/main/java/com/xunmei/common/security/utils/AsymmetricEncryptionUtil.java

@@ -28,14 +28,14 @@ public class AsymmetricEncryptionUtil {
     private static final String RSA = "RSA";
     private static final ConcurrentHashMap<String,Key> cache = new ConcurrentHashMap<>();
 
-    public static void main(String[] args) {
+/*    public static void main(String[] args) {
         //test("123456");
         String content = "GhZ/K5X9m/c2ArlDvH1H2IU0TOfAV0mR7vZJxXtanaS0GyNRPu/AzQld9Oe6LmaJRRSEleJQ6041u6IqeGKXnqsjrK1IQjwtJDgTAz3GvbxyOsedl0pol2FqdvQFw/y3rsFEFQsCYPPF7IYS/6YScSS+F7Qm/k+6fYryJG1xHoU=";
         String decrypt = decrypt(content);
         System.out.println("解密后明文为:"+decrypt);
-    }
+    }*/
 
-    public static void test(String content) {
+/*    public static void test(String content) {
         try {
             KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA);
             keyPairGenerator.initialize(1024);
@@ -54,7 +54,7 @@ public class AsymmetricEncryptionUtil {
         } catch (NoSuchAlgorithmException e) {
             log.error("加解密失败", e);
         }
-    }
+    }*/
 
 
     /**

+ 4 - 4
soc-common/soc-common-security/src/main/java/com/xunmei/common/security/utils/SaltHelper.java

@@ -21,7 +21,7 @@ public class SaltHelper {
     public static String decryptAES(final String content) {
         try {
             final SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
-            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // "算法/模式/补码方式"
+            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding","CCM"); // "算法/模式/补码方式"
             cipher.init(Cipher.DECRYPT_MODE, skeySpec);
             return new String(cipher.doFinal(Base64.decode(content)));
         } catch (final Exception e) {
@@ -33,7 +33,7 @@ public class SaltHelper {
     public static String encryptAES(final String content) {
         try {
             final SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
-            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // "算法/模式/补码方式"
+            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding","CCM"); // "算法/模式/补码方式"
             cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
             return Base64.encode(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
         } catch (final Exception e) {
@@ -76,7 +76,7 @@ public class SaltHelper {
     public static void main(String[] args) {
        // System.out.println(encryptAES("Admin123456"));
       //  System.out.println(decryptAES("lQTeYH546VVRPTQXS/pcJg=="));
-        System.out.println(DigestUtils.md5Hex("6c88ab6be7661b3173455c28e9af1c19"));
-        System.out.println(DigestUtils.md5Hex("Admin@123456" + DigestUtils.md5Hex("6c88ab6be7661b3173455c28e9af1c19")));
+        //System.out.println(DigestUtils.md5Hex("6c88ab6be7661b3173455c28e9af1c19"));
+        //System.out.println(DigestUtils.md5Hex("Admin@123456" + DigestUtils.md5Hex("6c88ab6be7661b3173455c28e9af1c19")));
     }
 }

+ 2 - 2
soc-common/soc-common-security/src/main/java/com/xunmei/common/security/utils/SecurityUtils.java

@@ -120,7 +120,7 @@ public class SecurityUtils {
         try {
             final SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
             // "算法/模式/补码方式"
-            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
+            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding","CCM");
             cipher.init(Cipher.DECRYPT_MODE, skeySpec);
             return new String(cipher.doFinal(Base64.decode(content)));
         } catch (final Exception e) {
@@ -132,7 +132,7 @@ public class SecurityUtils {
         try {
             final SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes("UTF-8"), "AES");
             // "算法/模式/补码方式"
-            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
+            final Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding","CCM");
             cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
             return Base64.encode(cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)));
         } catch (final Exception e) {

+ 3 - 2
soc-modules/soc-modules-core/src/main/java/com/xunmei/core/weather/service/impl/WeatherWarningServiceImpl.java

@@ -168,8 +168,9 @@ public class WeatherWarningServiceImpl extends ServiceImpl<WeatherWarningMapper,
         querys.put("needMoreDay", "0");
         String str=null;
         try {
-             HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
-             str = EntityUtils.toString(response.getEntity());
+            // HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
+             //str = EntityUtils.toString(response.getEntity());
+            str =HttpUtils.doGetNew(host, path, method, headers, querys);
              //稳定过后取消,前期留着,一遍分析数据
              log.info("时间:【{}】区域【{}】的天气数据【{}】", DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"),areaId,str);
         }catch (Exception e) {

+ 279 - 197
soc-modules/soc-modules-core/src/main/java/com/xunmei/core/weather/utils/HttpUtils.java

@@ -18,67 +18,164 @@ import org.apache.http.entity.StringEntity;
 import org.apache.http.impl.client.DefaultHttpClient;
 import org.apache.http.message.BasicNameValuePair;
 
+import javax.net.ssl.HttpsURLConnection;
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.TrustManager;
 import javax.net.ssl.X509TrustManager;
-import java.io.UnsupportedEncodingException;
+import java.io.*;
+import java.net.ConnectException;
+import java.net.URL;
 import java.net.URLEncoder;
 import java.security.KeyManagementException;
 import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.cert.CertificateException;
 import java.security.cert.X509Certificate;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 
 public class HttpUtils {
-	
-	/**
-	 * get
-	 * 
-	 * @param host
-	 * @param path
-	 * @param method
-	 * @param headers
-	 * @param querys
-	 * @return
-	 * @throws Exception
-	 */
-	public static HttpResponse doGet(String host, String path, String method, 
-			Map<String, String> headers, 
-			Map<String, String> querys)
-            throws Exception {    	
-    	HttpClient httpClient = wrapClient(host);
-
-    	HttpGet request = new HttpGet(buildUrl(host, path, querys));
+
+    /**
+     * get
+     *
+     * @param host
+     * @param path
+     * @param method
+     * @param headers
+     * @param querys
+     * @return
+     * @throws Exception
+     */
+    public static HttpResponse doGet(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception {
+        HttpClient httpClient = wrapClient(host);
+
+        HttpGet request = new HttpGet(buildUrl(host, path, querys));
         for (Map.Entry<String, String> e : headers.entrySet()) {
-        	request.addHeader(e.getKey(), e.getValue());
+            request.addHeader(e.getKey(), e.getValue());
         }
-        
+
         return httpClient.execute(request);
     }
-	
-	/**
-	 * post form
-	 * 
-	 * @param host
-	 * @param path
-	 * @param method
-	 * @param headers
-	 * @param querys
-	 * @param bodys
-	 * @return
-	 * @throws Exception
-	 */
-	public static HttpResponse doPost(String host, String path, String method, 
-			Map<String, String> headers, 
-			Map<String, String> querys, 
-			Map<String, String> bodys)
-            throws Exception {    	
-    	HttpClient httpClient = wrapClient(host);
-
-    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
+
+    /**
+     * @param host
+     * @param path
+     * @param method
+     * @param headers
+     * @param querys
+     * @return
+     */
+    public static String doGetNew(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) {
+        HttpsURLConnection conn = null;
+        InputStream inputStream = null;
+        InputStreamReader inputStreamReader = null;
+        BufferedReader bufferedReader = null;
+        String resultStr = null;
+
+        try {
+            //检查证书
+            TrustManager[] tm = checkTrustManager();
+            SSLContext ctx = SSLContext.getInstance("TLS");
+            ctx.init(null, tm, new SecureRandom());
+            javax.net.ssl.SSLSocketFactory ssf = ctx.getSocketFactory();
+            URL url = new URL(buildUrl(host, path, querys));
+            conn = (HttpsURLConnection) url.openConnection();
+            conn.setSSLSocketFactory(ssf);
+            //设置从HttpsURLConnection读入
+            conn.setDoInput(true);
+            //设置向HttpsURLConnection输出
+            conn.setDoOutput(false);
+            //不使用缓存
+            conn.setUseCaches(false);
+            //请求方式
+            conn.setRequestMethod(method);
+            //超时3000毫秒
+            conn.setConnectTimeout(3000);
+            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
+            for (Map.Entry<String, String> e : headers.entrySet()) {
+                conn.setRequestProperty(e.getKey(), e.getValue());
+            }
+            if (conn.getResponseCode() == 200) {
+                //从输入流读取返回的内容
+                inputStream = conn.getInputStream();
+                inputStreamReader = new InputStreamReader(inputStream, "utf-8");
+                bufferedReader = new BufferedReader(inputStreamReader);
+                StringBuffer buffer = new StringBuffer();
+                String str = null;
+                while ((str = bufferedReader.readLine()) != null) {
+                    buffer.append(str);
+                }
+                resultStr = buffer.toString();
+            }
+        } catch (ConnectException e) {
+            throw new RuntimeException(e);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        } finally {
+            //释放链接,关闭流
+            if (conn != null) {
+                conn.disconnect();
+            }
+            try {
+                if (bufferedReader != null) {
+                    bufferedReader.close();
+                }
+                if (inputStreamReader != null) {
+                    inputStreamReader.close();
+                }
+                if (inputStream != null) {
+                    inputStream.close();
+                }
+            } catch (IOException e) {
+                throw new RuntimeException(e);
+            }
+        }
+        return resultStr;
+    }
+
+    private static TrustManager[] checkTrustManager() {
+        TrustManager[] trustManagers = {new X509TrustManager() {
+            //检查客户端证书
+            @Override
+            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
+
+            }
+
+            //检查服务器端证书
+            @Override
+            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
+
+            }
+
+            //返回受信任的x509证书数组
+            @Override
+            public X509Certificate[] getAcceptedIssuers() {
+                return null;
+            }
+        }};
+        return trustManagers;
+    }
+
+    /**
+     * post form
+     *
+     * @param host
+     * @param path
+     * @param method
+     * @param headers
+     * @param querys
+     * @param bodys
+     * @return
+     * @throws Exception
+     */
+    public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys) throws Exception {
+        HttpClient httpClient = wrapClient(host);
+
+        HttpPost request = new HttpPost(buildUrl(host, path, querys));
         for (Map.Entry<String, String> e : headers.entrySet()) {
-        	request.addHeader(e.getKey(), e.getValue());
+            request.addHeader(e.getKey(), e.getValue());
         }
 
         if (bodys != null) {
@@ -93,210 +190,195 @@ public class HttpUtils {
         }
 
         return httpClient.execute(request);
-    }	
-	
-	/**
-	 * Post String
-	 * 
-	 * @param host
-	 * @param path
-	 * @param method
-	 * @param headers
-	 * @param querys
-	 * @param body
-	 * @return
-	 * @throws Exception
-	 */
-	public static HttpResponse doPost(String host, String path, String method, 
-			Map<String, String> headers, 
-			Map<String, String> querys, 
-			String body)
-            throws Exception {    	
-    	HttpClient httpClient = wrapClient(host);
-
-    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
+    }
+
+    /**
+     * Post String
+     *
+     * @param host
+     * @param path
+     * @param method
+     * @param headers
+     * @param querys
+     * @param body
+     * @return
+     * @throws Exception
+     */
+    public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception {
+        HttpClient httpClient = wrapClient(host);
+
+        HttpPost request = new HttpPost(buildUrl(host, path, querys));
         for (Map.Entry<String, String> e : headers.entrySet()) {
-        	request.addHeader(e.getKey(), e.getValue());
+            request.addHeader(e.getKey(), e.getValue());
         }
 
         if (StringUtils.isNotBlank(body)) {
-        	request.setEntity(new StringEntity(body, "utf-8"));
+            request.setEntity(new StringEntity(body, "utf-8"));
         }
 
         return httpClient.execute(request);
     }
-	
-	/**
-	 * Post stream
-	 * 
-	 * @param host
-	 * @param path
-	 * @param method
-	 * @param headers
-	 * @param querys
-	 * @param body
-	 * @return
-	 * @throws Exception
-	 */
-	public static HttpResponse doPost(String host, String path, String method, 
-			Map<String, String> headers, 
-			Map<String, String> querys, 
-			byte[] body)
-            throws Exception {    	
-    	HttpClient httpClient = wrapClient(host);
-
-    	HttpPost request = new HttpPost(buildUrl(host, path, querys));
+
+    /**
+     * Post stream
+     *
+     * @param host
+     * @param path
+     * @param method
+     * @param headers
+     * @param querys
+     * @param body
+     * @return
+     * @throws Exception
+     */
+    public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception {
+        HttpClient httpClient = wrapClient(host);
+
+        HttpPost request = new HttpPost(buildUrl(host, path, querys));
         for (Map.Entry<String, String> e : headers.entrySet()) {
-        	request.addHeader(e.getKey(), e.getValue());
+            request.addHeader(e.getKey(), e.getValue());
         }
 
         if (body != null) {
-        	request.setEntity(new ByteArrayEntity(body));
+            request.setEntity(new ByteArrayEntity(body));
         }
 
         return httpClient.execute(request);
     }
-	
-	/**
-	 * Put String
-	 * @param host
-	 * @param path
-	 * @param method
-	 * @param headers
-	 * @param querys
-	 * @param body
-	 * @return
-	 * @throws Exception
-	 */
-	public static HttpResponse doPut(String host, String path, String method, 
-			Map<String, String> headers, 
-			Map<String, String> querys, 
-			String body)
-            throws Exception {    	
-    	HttpClient httpClient = wrapClient(host);
-
-    	HttpPut request = new HttpPut(buildUrl(host, path, querys));
+
+    /**
+     * Put String
+     *
+     * @param host
+     * @param path
+     * @param method
+     * @param headers
+     * @param querys
+     * @param body
+     * @return
+     * @throws Exception
+     */
+    public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception {
+        HttpClient httpClient = wrapClient(host);
+
+        HttpPut request = new HttpPut(buildUrl(host, path, querys));
         for (Map.Entry<String, String> e : headers.entrySet()) {
-        	request.addHeader(e.getKey(), e.getValue());
+            request.addHeader(e.getKey(), e.getValue());
         }
 
         if (StringUtils.isNotBlank(body)) {
-        	request.setEntity(new StringEntity(body, "utf-8"));
+            request.setEntity(new StringEntity(body, "utf-8"));
         }
 
         return httpClient.execute(request);
     }
-	
-	/**
-	 * Put stream
-	 * @param host
-	 * @param path
-	 * @param method
-	 * @param headers
-	 * @param querys
-	 * @param body
-	 * @return
-	 * @throws Exception
-	 */
-	public static HttpResponse doPut(String host, String path, String method, 
-			Map<String, String> headers, 
-			Map<String, String> querys, 
-			byte[] body)
-            throws Exception {    	
-    	HttpClient httpClient = wrapClient(host);
-
-    	HttpPut request = new HttpPut(buildUrl(host, path, querys));
+
+    /**
+     * Put stream
+     *
+     * @param host
+     * @param path
+     * @param method
+     * @param headers
+     * @param querys
+     * @param body
+     * @return
+     * @throws Exception
+     */
+    public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception {
+        HttpClient httpClient = wrapClient(host);
+
+        HttpPut request = new HttpPut(buildUrl(host, path, querys));
         for (Map.Entry<String, String> e : headers.entrySet()) {
-        	request.addHeader(e.getKey(), e.getValue());
+            request.addHeader(e.getKey(), e.getValue());
         }
 
         if (body != null) {
-        	request.setEntity(new ByteArrayEntity(body));
+            request.setEntity(new ByteArrayEntity(body));
         }
 
         return httpClient.execute(request);
     }
-	
-	/**
-	 * Delete
-	 *  
-	 * @param host
-	 * @param path
-	 * @param method
-	 * @param headers
-	 * @param querys
-	 * @return
-	 * @throws Exception
-	 */
-	public static HttpResponse doDelete(String host, String path, String method, 
-			Map<String, String> headers, 
-			Map<String, String> querys)
-            throws Exception {    	
-    	HttpClient httpClient = wrapClient(host);
-
-    	HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
+
+    /**
+     * Delete
+     *
+     * @param host
+     * @param path
+     * @param method
+     * @param headers
+     * @param querys
+     * @return
+     * @throws Exception
+     */
+    public static HttpResponse doDelete(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception {
+        HttpClient httpClient = wrapClient(host);
+
+        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
         for (Map.Entry<String, String> e : headers.entrySet()) {
-        	request.addHeader(e.getKey(), e.getValue());
+            request.addHeader(e.getKey(), e.getValue());
         }
-        
+
         return httpClient.execute(request);
     }
-	
-	private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
-    	StringBuilder sbUrl = new StringBuilder();
-    	sbUrl.append(host);
-    	if (!StringUtils.isBlank(path)) {
-    		sbUrl.append(path);
+
+    private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
+        StringBuilder sbUrl = new StringBuilder();
+        sbUrl.append(host);
+        if (!StringUtils.isBlank(path)) {
+            sbUrl.append(path);
         }
-    	if (null != querys) {
-    		StringBuilder sbQuery = new StringBuilder();
-        	for (Map.Entry<String, String> query : querys.entrySet()) {
-        		if (0 < sbQuery.length()) {
-        			sbQuery.append("&");
-        		}
-        		if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
-        			sbQuery.append(query.getValue());
+        if (null != querys) {
+            StringBuilder sbQuery = new StringBuilder();
+            for (Map.Entry<String, String> query : querys.entrySet()) {
+                if (0 < sbQuery.length()) {
+                    sbQuery.append("&");
+                }
+                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
+                    sbQuery.append(query.getValue());
                 }
-        		if (!StringUtils.isBlank(query.getKey())) {
-        			sbQuery.append(query.getKey());
-        			if (!StringUtils.isBlank(query.getValue())) {
-        				sbQuery.append("=");
-        				sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
-        			}        			
+                if (!StringUtils.isBlank(query.getKey())) {
+                    sbQuery.append(query.getKey());
+                    if (!StringUtils.isBlank(query.getValue())) {
+                        sbQuery.append("=");
+                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
+                    }
                 }
-        	}
-        	if (0 < sbQuery.length()) {
-        		sbUrl.append("?").append(sbQuery);
-        	}
+            }
+            if (0 < sbQuery.length()) {
+                sbUrl.append("?").append(sbQuery);
+            }
         }
-    	
-    	return sbUrl.toString();
+
+        return sbUrl.toString();
+    }
+
+    private static HttpClient wrapClient(String host) {
+        HttpClient httpClient = new DefaultHttpClient();
+        if (host.startsWith("https://")) {
+            sslClient(httpClient);
+        }
+
+        return httpClient;
     }
-	
-	private static HttpClient wrapClient(String host) {
-		HttpClient httpClient = new DefaultHttpClient();
-		if (host.startsWith("https://")) {
-			sslClient(httpClient);
-		}
-		
-		return httpClient;
-	}
-	
-	private static void sslClient(HttpClient httpClient) {
+
+    private static void sslClient(HttpClient httpClient) {
         try {
             SSLContext ctx = SSLContext.getInstance("TLS");
             X509TrustManager tm = new X509TrustManager() {
                 public X509Certificate[] getAcceptedIssuers() {
                     return null;
                 }
+
                 public void checkClientTrusted(X509Certificate[] xcs, String str) {
-                	
+
                 }
+
                 public void checkServerTrusted(X509Certificate[] xcs, String str) {
-                	
+
                 }
             };
-            ctx.init(null, new TrustManager[] { tm }, null);
+            ctx.init(null, new TrustManager[]{tm}, null);
             SSLSocketFactory ssf = new SSLSocketFactory(ctx);
             ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
             ClientConnectionManager ccm = httpClient.getConnectionManager();
@@ -305,7 +387,7 @@ public class HttpUtils {
         } catch (KeyManagementException ex) {
             throw new RuntimeException(ex);
         } catch (NoSuchAlgorithmException ex) {
-        	throw new RuntimeException(ex);
+            throw new RuntimeException(ex);
         }
     }
 }