您当前的位置:首页 > 计算机 > 服务器 > 网络服务

搭建 https 服务端 测试 https 客户端

时间:12-14来源:作者:点击数:

搭建自签名服务端程序

Generate private key (.key)

# Key considerations for algorithm "RSA" ≥ 2048-bit
openssl genrsa -out server.key 2048

# Key considerations for algorithm "ECDSA" ≥ secp384r1
# List ECDSA the supported curves (openssl ecparam -list_curves)
openssl ecparam -genkey -name secp384r1 -out server.key

Generation of self-signed(x509) public key (PEM-encodings .pem|.crt) based on the private (.key)

openssl req -new -x509 -sha256 -key server.key -out server.crt -days 3650

Simple Golang HTTPS/TLS Server

package main

import (
    "net/http"
    "log"
)

func HelloServer(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-Type", "text/plain")
    w.Write([]byte("This is an example server.\n"))
}

func main() {
    http.HandleFunc("/hello", HelloServer)
    err := http.ListenAndServeTLS(":443", "server.crt", "server.key", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

Hint: visit, please do not forget to use https begins,otherwise chrome will download a file as follows:

$ curl -sL https://localhost/hello

更多

设置 HttpsURLConnection,让它信任所有证书,跳过验证步骤
private static void trustHttps(String url, HttpsURLConnection conn) {
  boolean useHttps = url.toLowerCase().startsWith("https");
  if (!useHttps) {
    return;
  }

  try {
    val sc = SSLContext.getInstance("TLS");
    sc.init(
        null,
        new TrustManager[] {
          new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
              return new X509Certificate[] {};
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
              // trust all
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
              // trust all
            }
          }
        },
        new java.security.SecureRandom());
    val newFactory = sc.getSocketFactory();
    conn.setSSLSocketFactory(newFactory);
  } catch (Exception ignore) {
    // ignore
  }
  conn.setHostnameVerifier((hostname, session) -> true);
}

@SneakyThrows
private static void readOutErrorStream(HttpURLConnection conn) {
  // by https://docs.oracle.com/javase/7/docs/technotes/guides/net/http-keepalive.html,
  // the connection should be cleaned up by reading the response body so that it could be reused.
  @Cleanup InputStream errorStream = conn.getErrorStream();

  if (errorStream == null) {
    return;
  }

  try {
    Is.toString(errorStream);
  } catch (Exception ioe) {
    // ignore
  }
}
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐