[英]How to make TLS work with java?
I developed an application working with TCP sockets. 我开发了一个使用TCP套接字的应用程序。
Now I would like it to work with a TLS connection. 现在我希望它能与TLS连接一起使用。
I searched some ressources for now 2 days but there is nothing that looks like a tutorial on how to implement TLS. 我现在搜索了一些资源2天,但没有什么看起来像是关于如何实现TLS的教程。
Here is what I understood with what I have to do : 以下是我对自己所要做的事情的理解:
I can't find a clear sample of code that explain really what to do. 我找不到一个明确的代码示例来解释实际上该做什么。
Can you please help me with some client/server example or other helpful tutorial ? 你能帮助我一些客户端/服务器示例或其他有用的教程吗? (I already tried to search "TLS java", "TLS Java example", "TLS Java tutorial" .... But I could not find anything satisfying.) (我已经尝试搜索“TLS java”,“TLS Java示例”,“TLS Java教程”......但我找不到令人满意的东西。)
Thank you in advance for your attention. 提前感谢您的关注。
There is two way to achieve this. 实现这一目标有两种方法。
The easyest lies in java protocol support and the URL
object. 最简单的是java协议支持和URL
对象。
But since I think you already figured out that new URL("https://www.google.com").openStream()
gives you a clear text input stream while dealing with all the TLS/SSL stuff for you, I'll go for the "hard" way :) 但是,因为我认为您已经发现new URL("https://www.google.com").openStream()
为您提供了明确的文本输入流,同时为您处理所有TLS / SSL内容,我会去“硬”的方式:)
Just before I'll answer your other question : importing a CA. 就在我回答你的另一个问题之前:导入CA. CA certificates are located in your java home at either of theses locations : $JAVA_HOME/lib/security/cacerts
(JRE) or $JAVA_HOME/jre/lib/security/cacerts
(JDK ; notice the 'jre' just after the java home) for both the default password is "changeit" CA证书位于java主目录中的任何一个位置: $JAVA_HOME/lib/security/cacerts
(JRE)或$JAVA_HOME/jre/lib/security/cacerts
(JDK;请注意java home之后的'jre')对于默认密码都是“changeit”
To list it's content you can use keytool
command : 要列出它的内容,您可以使用keytool
命令:
$ keytool -list -keystore cacerts -storepass changeit
To add a new cert just use the -import
subcommand instead of -list
要添加新证书,只需使用-import
子命令而不是-list
So now let's go for the "hard" way (client code) : 那么现在让我们采用“硬”方式(客户端代码):
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
...
String host = "www.google.com";
int port = 443;
SocketFactory basicSocketFactory = SocketFactory.getDefault();
Socket s = basicSocketFactory.createSocket(host,port);
// s is a TCP socket
SSLSocketFactory tlsSocketFactory = SSLSocketFactory.getDefault();
s = tlsSocketFactory.createSocket(s, host, port, true);
// s is now a TLS socket over TCP
it's as simple as that. 就这么简单。
If you need a server socket the code is almost the same, you just have to exchange SocketFactory
for ServerSocketFactory
and SSLSocketFactory
for SSLServerSocketFactory
如果你需要一个服务器套接字代码几乎相同,你只需要交换SocketFactory
for ServerSocketFactory
和SSLSocketFactory
for SSLServerSocketFactory
hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.