Starting a tls communication with python asyncio

时间:2015-06-15 15:20:51

标签: python ssl

I have some python code snippet that uses asyncio and initiates a "plain" connection:

loop = asyncio.get_event_loop()
coro = loop.create_connection(lambda: MyCustomClassProtocol(loop), sock=client_socket)
loop.run_until_complete(coro)

The point is my plain connection switches to a tls one once some exchanges have happened. In the traditional way one would do this:

ssl_sock = ssl.wrap_socket(client_socket, do_handshake_on_connect=False)
ssl_sock.do_handshake()

But I don't really know how I can handle this with asyncio. My data_received method receives the ciphered content though, so I guess I can do something to decipher it, but I cannot figure it out.

2 个答案:

答案 0 :(得分:1)

不幸的是,直到python 3.5还没有标准的方法来做到这一点!从python 3.5开始,在ssl模块中有一个名为MemoryBIO的新东西,您可以使用它来包装TLS的套接字。 你有几个选择:

  1. 使用Python传统(同步)套接字和loop.executor将其包装在异步协程中。

  2. 使用SSL代替TLS。大多数服务器允许它,但仍然有例外(例如Apple的APN!)

答案 1 :(得分:0)

仅使用asyncio的公共API的解决方案:

创建create_connection的副本并修改它以使其返回套接字对象(只需几行),并使用低级函数来操作它(例如sock_connect,sock_read)。当你需要startSSL时,只需将sock传递给open_connection