zoukankan      html  css  js  c++  java
  • Spring boot 配置https 实现java通过https接口访问

          近来公司需要搭建一个https的服务器来调试接口(服务器用的spring boot框架),刚开始接触就是一顿百度,最后发现互联网认可的https安全链接的证书需要去CA认证机构申请,由于是调试阶段就采用了java的keytool工具来生成密钥文件,下面是生成密钥文件的指令和步骤(前提是需要配置好java 的环境变量)。

      1、首先打开cmd命令,操作如下:

    keytool -genkey -alias tomcat  -storetype PKCS12 -keyalg RSA -keysize 2048  -keystore keystore.p12 -validity 3650
    1.-storetype 指定密钥仓库类型 
    2.-keyalg 生证书的算法名称,RSA是一种非对称加密算法 
    3.-keysize 证书大小 
    4.-keystore 生成的证书文件的存储路径 
    5.-validity 证书的有效期
    根据提示完成操作,保存在操作时数据内容,最后keystore.p12为生成的密钥文件

       2、打开spring boot 项目工程,将keykeystore.p12文件放到项目的resources根目录中,同时在application.properties中添加如下代码:

    #你生成的证书名字
    server.ssl.key-store=classpath:keystore.p12
    # 密钥库密码
    server.ssl.key-store-password=第一步生成密钥文件时输入的密钥
    server.ssl.keyStoreType=PKCS12
    server.ssl.keyAlias=tomcat

    此时工程的https访问路径已经配置好了启动项目,打开浏览器就可以访问页面,不过会提示不安全链接,主要还是因为证书是不认的。

      3、通过java访问https接口代码如下:

    import java.io.*;
    import java.net.URL;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.KeyManager;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.SSLSocketFactory;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    
    /**
     * 通过https访问服务器忽略证书没被认可也继续访问
     */
    public class HttpsConnect extends BaseConnect {
        private static String TAG = "HttpConnect";
    
        private static final class DefaultTrustManager implements X509TrustManager {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
    
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
    
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }
       protected static byte[] getBytesFromStream(InputStream is) throws IOException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] kb = new byte[1024];
            int len;
            while ((len = is.read(kb)) != -1) {
                baos.write(kb, 0, len);
            }
            byte[] bytes = baos.toByteArray();
            baos.close();
            is.close();
            return bytes;
        }
    
        protected static void setBytesToStream(OutputStream os, byte[] bytes) throws IOException {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            byte[] kb = new byte[1024];
            int len;
            while ((len = bais.read(kb)) != -1) {
                os.write(kb, 0, len);
            }
            os.flush();
            os.close();
            bais.close();
        }
    
    
        private static HttpsURLConnection getHttpsURLConnection(String uri, String method) throws IOException {
            SSLContext ctx = null;
            try {
                ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            SSLSocketFactory ssf = ctx.getSocketFactory();
    
            URL url = new URL(uri);
            HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
            httpsConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            httpsConn.setSSLSocketFactory(ssf);
            httpsConn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
            httpsConn.setRequestMethod(method);
            if("post".equals(method.toLowerCase())) {
                httpConn.setDoOutput(true);
                httpConn.setDoInput(true);
            }
            return httpsConn;
        }
    
        public static byte[] doGet(String uri) throws IOException {
            HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "GET");
            return getBytesFromStream(httpsConn.getInputStream());
        }
    
        public static byte[] doPost(String uri, String data) throws IOException {
            HttpsURLConnection httpsConn = getHttpsURLConnection(uri, "POST");
            setBytesToStream(httpsConn.getOutputStream(), data.getBytes("UTF-8"));
            return getBytesFromStream(httpsConn.getInputStream());
        }
    
    }
    import com.mpos.init.Gloabl.DES3Utils;
    import com.mpos.init.Gloabl.Global;
    
    import java.io.*;
    
    public class BaseConnect {
    
        protected static byte[] getBytesFromStream(InputStream is) throws IOException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] kb = new byte[1024];
            int len;
            while ((len = is.read(kb)) != -1) {
                baos.write(kb, 0, len);
            }
            byte[] bytes = baos.toByteArray();
            baos.close();
            is.close();
            return bytes;
        }
    
        protected static void setBytesToStream(OutputStream os, byte[] bytes) throws IOException {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            byte[] kb = new byte[1024];
            int len;
            while ((len = bais.read(kb)) != -1) {
                os.write(kb, 0, len);
            }
            os.flush();
            os.close();
            bais.close();
        }
    
        /**
         * 从输入流中获取字节数组
         *
         * @param inputStream
         * @return
         * @throws IOException
         */
        protected static byte[] readInputStream(InputStream inputStream) throws IOException {
            byte[] buffer = new byte[8 * 600];
            int len;
            byte[] desKey = Global.getDesKey();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                byte[] temp = new byte[len];
                System.arraycopy(buffer, 0, temp, 0, len);
                bos.write(temp);
            }
            byte[] data = DES3Utils.decryptMode(desKey, bos.toByteArray());
            bos.flush();
            bos.close();
            byte[] result = Global.getSourceData(data);
            return result;
        }
    }
    
  • 相关阅读:
    Java tomcat max-http-header-size配置导致的oom
    Idea修改jvm参数
    Java List的SubList使用问题
    Java Arrays.asList的三个坑
    Java 重写equals的时候为什么一定要重写hashcode-一个例子
    远心镜头
    镜头常识总结
    halcon中保存图像jpeg的压缩比
    红外光 相机拍照
    电磁波的穿透能力总结
  • 原文地址:https://www.cnblogs.com/blogzhangwei/p/9882263.html
Copyright © 2011-2022 走看看