生成自签名证书:
1、生成带有 RSA 的私钥:
openssl genrsa -out private.key 2048
2.创建openssl.conf,设置IP.1和/或DNS.1指向受信任的 IP/DNS 地址,内容如下
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = CN
ST = FuJian
L = FuZhou
O = 随便填
OU = 随便填
CN = 填域名地址
[v3_req]
subjectAltName = @alt_names
[alt_names]
DNS.1 = 填域名地址
IP.1 = 填域名ip
2、生成公钥证书,名称为public.crt
openssl req -new -x509 -nodes -days 730 -key private.key -out public.crt -config openssl.conf
chrome浏览器信任证书
设置-隐私设置和安全性-安全-管理证书-受信任的根证书办法机构-导入public.crt
如果应用是用java运行的,可以无需修改代码,直接在java证书库信任该证书
keystore导入证书
cd $JAVA_HOME/jre/lib/security
sudo keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias 证书别名 -file ${CERT:-default /app/file/cert/getcacert.cer}
删除证书
sudo keytool -delete -alias 证书别名 -trustcacerts -keystore cacerts -storepass changeit
或者修改代码,信任所有主机及证书
public class SslClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
if (connection instanceof HttpsURLConnection) {
prepareHttpsConnection((HttpsURLConnection) connection);
}
super.prepareConnection(connection, httpMethod);
}
private void prepareHttpsConnection(HttpsURLConnection connection) {
connection.setHostnameVerifier(new SkipHostnameVerifier());
try {
connection.setSSLSocketFactory(createSslSocketFactory());
}
catch (Exception ex) {
// Ignore
}
}
private SSLSocketFactory createSslSocketFactory() throws Exception {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{new SkipX509TrustManager()}, new SecureRandom());
return context.getSocketFactory();
}
private class SkipHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
}
private static class SkipX509TrustManager implements X509TrustManager {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
}
}