一、简介

nginx到客户端的连接通过HTTPS加密,实现了安全隔离。本文在windows中使用keytool生成证书和私钥实现ssl认证。

二、nginx开启server块的ssl

使用listen指令的ssl参数激活了SSL模块。

完整的配置:

worker_processes  1;

events {
worker_connections 1024;
}

http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;

server {
listen 8088 default ssl;
server_name localhost;
proxy_read_timeout 300s;
proxy_connect_timeout 300s;
proxy_send_timeout 300s;
#ssl配置
ssl_prefer_server_ciphers on;
ssl_protocols TLSv1 SSLv3;ssl_ciphers RC4:HIGH:!aNULL:!MD5:@STRENGTH;
ssl_session_cache shared:WEB:10m;
ssl_certificate C:\Users\yangjianzhang\Desktop\server.crt;
ssl_certificate_key C:\Users\yangjianzhang\Desktop\server.key;

#开启header的下划线支持:
underscores_in_headers on;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#设置向后端proxy发送X-Forwarded-Proto字段
proxy_set_header X-Forwarded-Proto http;

location /test {
proxy_pass http://127.0.0.1:8080/;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}

三、生成证书和私钥

nginx配置中需要ssl_certificate(证书)和ssl_certificate_key(私钥)

证书中包含了公钥,所以只要证书和私钥即可

1.生成证书库

keytool -genkeypair -alias server -keyalg RSA -keystore C:\Users\yangjianzhang\Desktop\server.keystore

2.导出证书

keytool -export -alias server -keystore C:\Users\yangjianzhang\Desktop\server.keystore -storepass 123456 -rfc -file C:\Users\yangjianzhang\Desktop\server.crt

3.生成私钥

使用java代码生成key(也可以使用openssl转换),将输出的内容放到server.key文件中。

import sun.misc.BASE64Encoder;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;

public class RsaDoMain {
public static void main(String[] args) throws Exception {
getPrivateKey();
}

public static KeyStore getKeyStore(String keyStorePath, String password) throws Exception {
FileInputStream is = new FileInputStream(keyStorePath);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(is, password.toCharArray());
is.close();
return ks;
}

public static PrivateKey getPrivateKey() throws Exception {
BASE64Encoder encoder = new BASE64Encoder();
KeyStore ks = getKeyStore("C:/Users/yangjianzhang/Desktop/server.keystore", "123456");
PrivateKey key = (PrivateKey) ks.getKey("server", "123456".toCharArray());
String encoded = encoder.encode(key.getEncoded());
System.out.println("-----BEGIN RSA PRIVATE KEY-----");
System.out.println(encoded);
System.out.println("-----END RSA PRIVATE KEY-----");
return key;
}

}

四、测试

1.启动nginx

nginx配置ssl认证启用https加密(windows版)_nginx

nginx配置ssl认证启用https加密(windows版)_java_02

2.测试接口


五、参考文献

JAVA利用keytool工具生成.crt和.key文件 - 程序员大本营