thrift ssl 加密

nifty的github地址:https://github.com/facebook/nifty.git

maven依赖:

        <dependency>
            <groupId>com.facebook.nifty</groupId>
            <artifactId>nifty-core</artifactId>
            <version>0.14.0</version>
        </dependency>

顺便说一下,netty4出来了,貌似比以前牛逼了些。但是目前nifty还是使用的netty3.7,不知道什么时候会替换。

先生成公私钥,我写了一个bat脚本:

md .\gen-key

keytool -genkey -v -alias xxserver -keyalg RSA -keysize 1024 -validity 3650 -keystore  .\gen-key\xxserver.keystore -storepass xxserver123 -keypass xxserver123 -dname "CN=servergroup,OU=RDdepartment,O=xx,L=beijing,ST=beijing,C=CN"
 
keytool -export -alias xxserver -keystore .\gen-key\xxserver.keystore -file .\gen-key\xxserver.crt -storepass xxserver123

keytool -import -alias xxserver -file .\gen-key\xxserver.crt -keystore .\gen-key\xxclient.truststore -storepass 123456

pause

xxserver.keystore给服务端用,xxclient.truststore给客户端用。

下面开始编码。

先继承NiftySecurityFactory写一个加密工具类:

public class SslSecurityFactory implements NiftySecurityFactory {
    private static final Logger log = LogWriter.getAccountLog();
    //xxserver.keystore路径
    private static final String SERVER_KEY_STORE= PropertiesUtils.getInstance().getSslKeystore();
    //xxserver.keystore密码
    private static final String SERVER_KEY_STORE_PWD = PropertiesUtils.getInstance().getSslKeypass();
    private static KeyManagerFactory kf = null;
    static{
        try {
            KeyStore ks = KeyStore.getInstance(PropertiesUtils.getInstance().getSslKeystoreType());
            InputStream is = new FileInputStream(SERVER_KEY_STORE);
            char[] passChars = SERVER_KEY_STORE_PWD.trim().toCharArray();
            ks.load(is,passChars);
            kf = KeyManagerFactory.getInstance(PropertiesUtils.getInstance().getSslKeyManagerFactoryType());
            kf.init(ks,passChars);
            is.close();
        } catch (Exception e) {
            log.error("Fail to init KeyManagerFactory...");
            e.printStackTrace();
        }
    }


    static final ChannelHandler noOpHandler = new SimpleChannelHandler() {
        @Override
        public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
            super.channelOpen(ctx, e);
            ctx.getPipeline().remove(this);
        }
    };

    @Override
    public NiftySecurityHandlers getSecurityHandlers(ThriftServerDef thriftServerDef, NettyServerConfig nettyServerConfig) {
        return new NiftySecurityHandlers() {
            @Override
            public ChannelHandler getAuthenticationHandler() {
                return noOpHandler;
            }

            @Override
            public ChannelHandler getEncryptionHandler() {

                // Initialize the SSLContext to work with our key managers.
                SSLEngine engine = null;
                try {
                    SSLContext serverContext = SSLContext.getInstance("TLS");
                    serverContext.init(kf.getKeyManagers(), null, null);
                    engine = serverContext.createSSLEngine();
                    engine.setUseClientMode(false);
                } catch (Exception e) {
                    log.error("Could not create SSLContext or SSLEngine");
                    throw new RuntimeException(e);
                }

                SslHandler ssl = new SslHandler(engine);
                ssl.setIssueHandshake(true);
                return ssl;
            }
        };
    }
}

将加密工具类传递给server配置类:

ThriftServerDef serverDef = new ThriftServerDefBuilder()
                .protocol(new TCompactProtocol.Factory())
                .name(ip)
                .listen(port)
                .withProcessor(processor)
                .withSecurityFactory(new SslSecurityFactory())
                .build();
        final NettyServerTransport server = new NettyServerTransport(serverDef);
        server.start();
        System.out.println("start server...");
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                try {
                    server.stop();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });

客户端访问代码

 //初始化并打开连接
TSSLTransportFactory.TSSLTransportParameters params = new TSSLTransportFactory.TSSLTransportParameters();
params.setTrustStore(
	"D:\\proj\\gen-key\\xxclient.truststore"	//可信证书库路径
	, "123456"	//仓库密码
	, "SunX509"	//数字证书格式
	, "JKS"		//密钥库格式
	);
 TTransport transport = new TFramedTransport(TSSLTransportFactory.getClientSocket("8.8.8.8", 9000,60000,params),300000);
TProtocol protocol = new TMultiplexedProtocol(new TCompactProtocol(transport),"TestProcessor");
TestRPC.Client client = new TestRPC.Client(protocol);
//transport.open();
//请求
TestResponse resp = client.test();
System.out.println(resp);
//关闭连接
transport.close();















你可能感兴趣的:(thrift ssl 加密)