问题总结

1.国密与非国密

什么是国密?

国密即国家密码局认定的国产密码算法。主要有SM1,SM2,SM3,SM4。具体可以参考https://zhuanlan.zhihu.com/p/132352160

什么是非国密?

就是除了国密以外的算法,包括除国密算法以外的加密算法。

2.国密与非国密和http与https有什么关系?

使用国密算法需要依靠https进行通信。

使用非国密,如果使用了加密算法仍然要依靠https进行通信,没有加密算法可以使用http通信。

3.基于nginx搭建非国密https环境

3.1.下载并解压nginx

本文使用的版本是1.16.1,下载地址是http://nginx.org/download/nginx-1.16.1.tar.gz,下载后上传到服务器进行解压。

tar -zxvf nginx-1.16.1.tar.gz

3.2 携带ssl模块安装nginx

 在解压目录下运行以下命令

./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
make
make install

3.3 查看ssl是否安装成功

/usr/local/nginx/sbin/nginx -V

如果出现以下结果,则表明安装成功。 

3.4启动nginx

cd /usr/local/nginx/sbin
./nginx

3.5配置ssl证书

本文把证书放在/root/notgm目录下

3.6修改nginx配置

修改/usr/local/nginx/conf/nginx.conf

在最后一个}之前填写以下信息,则表明将开启一个1445端口。

  server {
    listen      1445 ssl;
    #listen      8888;
    server_name  localhost;
    #limit_req zone=reqperip burst=20 nodelay;
    #limit_req zone=reqperserver burst=200 nodelay;
    #limit_conn connperip 20;
    #limit_conn connperserver 500;
    #ssl on;
    ssl_certificate             /root/notgm/server.crt;
    ssl_certificate_key          /root/notgm/server.key;

    ssl_client_certificate       /root/notgm/ca.crt;

    ssl_verify_client       on;
    

    ssl_protocols  SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA+RC4 EECDH EDH+aRSA !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS !RC4";
   location / {
#	default_type application/json;
 #       return 200 '{"code":200}';
        proxy_pass http://192.168.110.27:8089/;
      }

    
    location ~ .*\.(json)$
    {
        default_type application/json;
        return 200 '{"code":200}';
    }
}

 3.7 加载nginx.conf

./nginx -s reload

4.验证https通信

4.1 Python

import requests
session = requests.Session()
r=session.post("https://192.168.110.235:1445/V1/jcc/reg_rs",
               verify='./192.168.110.235/ca.crt',
               cert=('./192.168.110.235/server.crt', './192.168.110.235/server.key'))
print r.text

运行结果如下,表明可以通信成功。

 

4.2Java 

4.2.1 使用HttpURLConnection方式

可以参考https://blog.csdn.net/qq_36313856/article/details/111407772

1、对客户端证书和私钥进行打包处理(需要输入密码,之后在代码中需要用到该密码)
openssl pkcs12 -export -in server.crt -inkey server.key -out client.p12
2、.p12文件转化成JKS格式
keytool -importkeystore -srckeystore client.p12 -srcstoretype pkcs12 -destkeystore client.jks -deststoretype JKS
3、CA根证书转成JKS格式(需要输入密码,之后在代码中需要用到该密码)
keytool -import -noprompt -file ca.crt -keystore ca.jks -storepass 123456
ca.jksclient.jks放到/usr/local/qwzy/jcqcomponent/
package learn.https;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class HttpsUtil {
    //CA根证书文件路径
    private String caPath="C:\\Users\\anny\\Desktop\\ca.jks";
    //CA根证书生成密码
    private String caPassword="123456";
    //客户端证书文件名
    private String clientCertPath="C:\\Users\\anny\\Desktop\\client.jks";
    //客户端证书生成密码
    private String clientCertPassword="123456";

    private SSLSocketFactory sslFactory;

    public static void main(String[] args) throws Exception {
        HttpsUtil util=new HttpsUtil();
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("code", 0);
        jsonParam.put("detail", "detail");
        jsonParam.put("audit_time", "2020-11-10");
        util.httpsPost("https://192.168.124.244:20443/V1/jcc/reg_rs",jsonParam.toJSONString());
    }

    //https POST请求返回结果和结果码
    public  Map<String,Object> httpsPost(String requestUrl, String xml) throws Exception {
        Map<String,Object> map=new HashMap<>();
        OutputStreamWriter wr=null;
        HttpURLConnection conn=null;
        try {
            URL url = new URL(requestUrl);
            //start 这一段代码必须加在open之前,即支持ip访问的关键代码
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            //end
            byte[] xmlBytes = xml.getBytes();
            conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestMethod("POST");
            //根据自己项目需求设置Content-Type
            conn.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");
            conn.setRequestProperty("Content-Length", String.valueOf(xmlBytes.length));
            conn.setRequestProperty("Content-Type", "application/xml;charset=UTF-8");
            conn.setRequestProperty("Content-Length", String.valueOf(xmlBytes.length));
            conn.setRequestProperty("Src-Node", "204300010001");
            conn.setRequestProperty("Dst-Node", "180206020029");
            conn.setRequestProperty("Source-Type", "DIRECTOR_AUDIT");
            conn.setRequestProperty("BusinessData-Type", "DIRECTOR_AUDIT_RESULT");
            conn.setRequestProperty("Content-Type", "application/json");
            ((HttpsURLConnection) conn).setSSLSocketFactory(getSslFactory());
            wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(xml);
            wr.close();
            conn.connect();
            String responseBody = getResponseBodyAsString(conn);
            int responseCode=getResponseCode(conn);
            map.put("responseBody",responseBody);
            map.put("responseCode",responseCode);
            if (getResponseCode(conn) == 200) {
                System.out.println("请求成功");
                System.out.println(map.get("responseCode").getClass().getName());
            } else {
                System.out.println("请求失败");
            }
            System.out.println(responseBody);
            conn.disconnect();
        } catch (Exception e) {
            log.error("HTTPS请求出现异常,请求参数为:"+xml);
            e.printStackTrace();
            throw e;
        }finally {
            try{
                if(wr!=null){
                    wr.close();
                }
                if(conn!=null){
                    conn.disconnect();
                }
            }catch (Exception e){

            }
        }
        return map;
    }

    public SSLSocketFactory getSslFactory() throws Exception {
        if (sslFactory == null) {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            TrustManager[] tm = {new MyX509TrustManager()};
            KeyStore trustStore = KeyStore.getInstance("JKS");
            //加载客户端证书
            FileInputStream clientInputStream=new FileInputStream(clientCertPath);
            trustStore.load(clientInputStream, clientCertPassword.toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(trustStore, clientCertPassword.toCharArray());
            sslContext.init(kmf.getKeyManagers(), tm, new SecureRandom());
            sslFactory = sslContext.getSocketFactory();
        }
        return sslFactory;
    }

    public int getResponseCode(HttpURLConnection connection) throws Exception {
        return connection.getResponseCode();
    }

    public String getResponseBodyAsString(HttpURLConnection connection) throws Exception {
        BufferedReader reader = null;
        if (connection.getResponseCode() == 200) {
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
            reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }
        StringBuffer buffer = new StringBuffer();
        String line = null;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        return buffer.toString();
    }

    class MyX509TrustManager implements X509TrustManager {
        private X509TrustManager sunJSSEX509TrustManager;

        MyX509TrustManager() throws Exception {
            KeyStore ks = KeyStore.getInstance("JKS");
            //获取CA证书
            FileInputStream caInputStream=new FileInputStream(caPath);
            ks.load(caInputStream, caPassword.toCharArray());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
            tmf.init(ks);
            TrustManager tms[] = tmf.getTrustManagers();
            for (int i = 0; i < tms.length; i++) {
                if (tms[i] instanceof X509TrustManager) {
                    sunJSSEX509TrustManager = (X509TrustManager) tms[i];
                    return;
                }
            }
            throw new Exception("Couldn't not initialize");
        }

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            try {
                sunJSSEX509TrustManager.checkClientTrusted(x509Certificates, s);
            } catch (Exception e) {

            }
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            try {
                sunJSSEX509TrustManager.checkServerTrusted(x509Certificates, s);
            } catch (Exception e) {

            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return sunJSSEX509TrustManager.getAcceptedIssuers();
        }

    }
}

4.2.2使用HttpClient方式

生成jks的方式和4.2.1一样


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.KeyManagerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class TEst {
    public static void main(String[] args) throws Exception {
        String url = "https://192.168.110.235:1445/xxx";
        TEst t = new TEst();
        t.connect(url, "");
    }

    public String connect(String queryUrl, String xml) throws Exception {
        BufferedReader in = null;
        String keyStore = "C:\\Users\\anny\\Desktop\\client.jks"; //证书的路径,pfx格式
        String trustStore = "C:\\Users\\anny\\Desktop\\ca.jks";//密钥库文件,jks格式
        String keyPass = "123456"; //pfx文件的密码
        String trustPass = "123456"; //jks文件的密码

        SSLContext sslContext = null;
        try {

            KeyStore ks = KeyStore.getInstance("jks");
            // 加载pfx文件
            ks.load(new FileInputStream(keyStore), keyPass.toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509");
            kmf.init(ks, keyPass.toCharArray());

            KeyStore ts = KeyStore.getInstance("jks");
            //加载jks文件
            ts.load(new FileInputStream(trustStore), trustPass.toCharArray());
            TrustManager[] tm;
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509");
            tmf.init(ts);
            tm = tmf.getTrustManagers();

            sslContext = SSLContext.getInstance("SSL");
//初始化
            sslContext.init(kmf.getKeyManagers(), tm, null);

        } catch (Exception e) {
            e.printStackTrace();
        }

        String result = null;
        try {

            HttpClient httpclient = new DefaultHttpClient();
            //下面是重点
            SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext);
            Scheme sch = new Scheme("https", 800, socketFactory);
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);
            HttpPost httpPost = null;

            httpPost = new HttpPost(queryUrl);

            // 创建名/值组列表
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("Name", "zhangsan"));
            parameters.add(new BasicNameValuePair("passWord", "123456"));

            // 创建UrlEncodedFormEntity对象
            UrlEncodedFormEntity formEntiry = new UrlEncodedFormEntity(parameters);
            System.out.println("formEntity={}" + formEntiry);
            httpPost.setEntity(formEntiry);
            HttpResponse httpResponse = httpclient.execute(httpPost);
            in = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();

            result = URLDecoder.decode(result.toString(), "GBK");
            System.out.println("result={}" + result);
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值