简体   繁体   English

创建从Java客户端(在Android上)到Python服务器的自签名SSL套接字

[英]Create self-signed SSL socket from Java client (on Android) to Python server

I created a self-signed certificate (server.crt, server.key, server.p12). 我创建了一个自签名证书(server.crt,server.key,server.p12)。 I get a Python-Python SSL socket connection using this self-signed certificate working just fine. 我使用此自签名证书获得了Python-Python SSL套接字连接,效果很好。

Python server: Python服务器:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 10023))
s.listen(5)
s_, fromaddr = s.accept()
connstream = ssl.wrap_socket(s_,
                             server_side=True,
                             certfile="server.crt",
                             keyfile="server.key")
data = connstream.read()
...

Now, I would like my Android application to talk with my Python server. 现在,我希望我的Android应用程序可以与我的Python服务器通信。 I can get a non SSL connection going. 我可以进行非SSL连接。 I'm not sure how to proceed with self-signed certificates. 我不确定如何进行自签名证书。 My understanding is that I have to store the certificate in Java's truststore. 我的理解是我必须将证书存储在Java的信任库中。 I am having difficulty finding examples of doing this within the Android app (programmatically) using a trusted certificate file (eg the crt?). 我很难找到使用受信任的证书文件(例如crt?)在Android应用程序中(以编程方式)执行此操作的示例。 Obviously, the scope of this trust is limited to the app only, and is not intended to be a permanent solution. 显然,这种信任的范围仅限于应用程序,而并非永久解决方案。

Java client (on Android): Java客户端(在Android上):

SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
Socket socket = ssf.createSocket(HOST, PORT);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println("hello from java!");
out.flush();
...

When I try to connect I get the following error on the server: 当我尝试连接时,服务器上出现以下错误:

ssl.SSLError: [Errno 1] _ssl.c:499: error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown
  • export crt file at server 在服务器上导出crt文件
  • import crt file from asserts or file at Android code 从断言导入crt文件或Android代码中的文件
  • set up crt with TrustManagerFactory at Android code 在Android代码中使用TrustManagerFactory设置crt
  • init SSLContext with TrustManagerFactory 使用TrustManagerFactory初始化SSLContext

this is reference on official document 这是官方文件上的参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM