Created
April 8, 2023 07:10
-
-
Save abduakhatov/d33016b7fe30879a0ee917309e997752 to your computer and use it in GitHub Desktop.
Transport protocol with SSL in asyncio
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
openssl genrsa -out root-ca.key 2048 | |
openssl req -x509 -new -nodes -key root-ca.key -days 365 -out root-ca.crt | |
python3 ssl_web_server.py | |
echo "then open browser: https://localhost:4433" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Transport and Protocol with SSL | |
import asyncio | |
import ssl | |
def make_header(): | |
head = b"HTTP/1.1 200 OK\r\n" | |
head += b"Content-Type: text/html\r\n" | |
head += b"\r\n" | |
return head | |
def make_body(): | |
resp = b"<html>" | |
resp += b"<h1>Hello SSL</h1>" | |
resp += b"</html>" | |
return resp | |
sslctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) | |
sslctx.load_cert_chain( | |
certfile="./root-ca.crt", keyfile="./root-ca.key" | |
) | |
class Service(asyncio.Protocol): | |
def connection_made(self, tr): | |
self.tr = tr | |
self.total = 0 | |
def data_received(self, data): | |
if data: | |
resp = make_header() | |
resp += make_body() | |
self.tr.write(resp) | |
self.tr.close() | |
async def start(): | |
server = await loop.create_server( | |
Service, "localhost", 4433, ssl=sslctx | |
) | |
await server.wait_closed() | |
try: | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(start()) | |
finally: | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment