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
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
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
}
}
