java tls_使用Java编写使用ssl / tls的客户端-服务器应...

我打算做的是编写一个使用SSL(TLS)连接来交换数据的客户端服务器应用程序.

由于客户端是可下载的,并且我不能保证可以访问密钥库,因此我正在寻找一种在运行时导入证书的方法.

我需要的:

>一种将服务器的公钥/证书导入客户端应用程序的方法

>一种将服务器的私钥/证书导入服务器应用程序的方法

到目前为止,我发现了什么:

// load the servers public crt (pem), exported from a https website

CertificateFactory cf = CertificateFactory.getInstance("X509");

X509Certificate cert = (X509Certificate)cf.generateCertificate(new

FileInputStream("C:certificate.crt"));

// load the pkcs12 key generated with openssl out of the server.crt and server.key (private) (if the private key is stored in the pkcs file, this is not a solution as I need to ship it with my application)

KeyStore ks = KeyStore.getInstance("PKCS12");

ks.load(new FileInputStream("C:certificate.pkcs"), "password".toCharArray());

ks.setCertificateEntry("Alias", cert);

TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

tmf.init(ks);

KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

kmf.init(ks, "password".toCharArray());

// create SSLContext to establish the secure connection

SSLContext ctx = SSLContext.getInstance("TLS");

ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

这对我不起作用,因为出现错误:

java.security.KeyStoreException: TrustedCertEntry not supported at ks.setCertificateEntry(“Alias”, cert);

另外,我认为pkcs12用于存储私钥,这不是我想要的.

我是Java的新手,现在真的很难解决这个问题.

提前致谢,

一雄

我打算做的是编写一个使用SSL(TLS)连接来交换数据的客户端服务器应用程序. 由于客户端是可下载的,并且我不能保证可以访问密钥库,因此我正在寻找一种在运行时导入证书的方法. 我需要的: >一种将服务器的公钥/证书导入客户端应用程序的方法 >一种将服务器的私钥/证书导入服务器应用程序的方法 到目前为止,我发现了什么: // load the servers public crt (pem), exported from a https website CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate)cf.generateCertificate(new FileInputStream("C:certificate.crt")); // load the pkcs12 key generated with openssl out of the server.crt and server.key (private) (if the private key is stored in the pkcs file, this is not a solution as I need to ship it with my application) KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream("C:certificate.pkcs"), "password".toCharArray()); ks.setCertificateEntry("Alias", cert); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, "password".toCharArray()); // create SSLContext to establish the secure connection SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); 这对我不起作用,因为出现错误: java.security.KeyStoreException: TrustedCertEntry not supported at ks.setCertificateEntry(“Alias”, cert); 另外,我认为pkcs12用于存储私钥,这不是我想要的. 我是Java的新手,现在真的很难解决这个问题. 提前致谢, 一雄
经验分享 程序员 微信小程序 职场和发展